2
0

three.js 801 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '58' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. String.prototype.trim = String.prototype.trim || function () {
  16. return this.replace( /^\s+|\s+$/g, '' );
  17. };
  18. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  19. THREE.extend = function ( obj, source ) {
  20. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  21. if ( Object.keys ) {
  22. var keys = Object.keys( source );
  23. for (var i = 0, il = keys.length; i < il; i++) {
  24. var prop = keys[i];
  25. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  26. }
  27. } else {
  28. var safeHasOwnProperty = {}.hasOwnProperty;
  29. for ( var prop in source ) {
  30. if ( safeHasOwnProperty.call( source, prop ) ) {
  31. obj[prop] = source[prop];
  32. }
  33. }
  34. }
  35. return obj;
  36. };
  37. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  38. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  39. // requestAnimationFrame polyfill by Erik Möller
  40. // fixes from Paul Irish and Tino Zijdel
  41. ( function () {
  42. var lastTime = 0;
  43. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  44. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  45. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  46. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  47. }
  48. if ( window.requestAnimationFrame === undefined ) {
  49. window.requestAnimationFrame = function ( callback ) {
  50. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  51. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  52. lastTime = currTime + timeToCall;
  53. return id;
  54. };
  55. }
  56. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  57. }() );
  58. // GL STATE CONSTANTS
  59. THREE.CullFaceNone = 0;
  60. THREE.CullFaceBack = 1;
  61. THREE.CullFaceFront = 2;
  62. THREE.CullFaceFrontBack = 3;
  63. THREE.FrontFaceDirectionCW = 0;
  64. THREE.FrontFaceDirectionCCW = 1;
  65. // SHADOWING TYPES
  66. THREE.BasicShadowMap = 0;
  67. THREE.PCFShadowMap = 1;
  68. THREE.PCFSoftShadowMap = 2;
  69. // MATERIAL CONSTANTS
  70. // side
  71. THREE.FrontSide = 0;
  72. THREE.BackSide = 1;
  73. THREE.DoubleSide = 2;
  74. // shading
  75. THREE.NoShading = 0;
  76. THREE.FlatShading = 1;
  77. THREE.SmoothShading = 2;
  78. // colors
  79. THREE.NoColors = 0;
  80. THREE.FaceColors = 1;
  81. THREE.VertexColors = 2;
  82. // blending modes
  83. THREE.NoBlending = 0;
  84. THREE.NormalBlending = 1;
  85. THREE.AdditiveBlending = 2;
  86. THREE.SubtractiveBlending = 3;
  87. THREE.MultiplyBlending = 4;
  88. THREE.CustomBlending = 5;
  89. // custom blending equations
  90. // (numbers start from 100 not to clash with other
  91. // mappings to OpenGL constants defined in Texture.js)
  92. THREE.AddEquation = 100;
  93. THREE.SubtractEquation = 101;
  94. THREE.ReverseSubtractEquation = 102;
  95. // custom blending destination factors
  96. THREE.ZeroFactor = 200;
  97. THREE.OneFactor = 201;
  98. THREE.SrcColorFactor = 202;
  99. THREE.OneMinusSrcColorFactor = 203;
  100. THREE.SrcAlphaFactor = 204;
  101. THREE.OneMinusSrcAlphaFactor = 205;
  102. THREE.DstAlphaFactor = 206;
  103. THREE.OneMinusDstAlphaFactor = 207;
  104. // custom blending source factors
  105. //THREE.ZeroFactor = 200;
  106. //THREE.OneFactor = 201;
  107. //THREE.SrcAlphaFactor = 204;
  108. //THREE.OneMinusSrcAlphaFactor = 205;
  109. //THREE.DstAlphaFactor = 206;
  110. //THREE.OneMinusDstAlphaFactor = 207;
  111. THREE.DstColorFactor = 208;
  112. THREE.OneMinusDstColorFactor = 209;
  113. THREE.SrcAlphaSaturateFactor = 210;
  114. // TEXTURE CONSTANTS
  115. THREE.MultiplyOperation = 0;
  116. THREE.MixOperation = 1;
  117. THREE.AddOperation = 2;
  118. // Mapping modes
  119. THREE.UVMapping = function () {};
  120. THREE.CubeReflectionMapping = function () {};
  121. THREE.CubeRefractionMapping = function () {};
  122. THREE.SphericalReflectionMapping = function () {};
  123. THREE.SphericalRefractionMapping = function () {};
  124. // Wrapping modes
  125. THREE.RepeatWrapping = 1000;
  126. THREE.ClampToEdgeWrapping = 1001;
  127. THREE.MirroredRepeatWrapping = 1002;
  128. // Filters
  129. THREE.NearestFilter = 1003;
  130. THREE.NearestMipMapNearestFilter = 1004;
  131. THREE.NearestMipMapLinearFilter = 1005;
  132. THREE.LinearFilter = 1006;
  133. THREE.LinearMipMapNearestFilter = 1007;
  134. THREE.LinearMipMapLinearFilter = 1008;
  135. // Data types
  136. THREE.UnsignedByteType = 1009;
  137. THREE.ByteType = 1010;
  138. THREE.ShortType = 1011;
  139. THREE.UnsignedShortType = 1012;
  140. THREE.IntType = 1013;
  141. THREE.UnsignedIntType = 1014;
  142. THREE.FloatType = 1015;
  143. // Pixel types
  144. //THREE.UnsignedByteType = 1009;
  145. THREE.UnsignedShort4444Type = 1016;
  146. THREE.UnsignedShort5551Type = 1017;
  147. THREE.UnsignedShort565Type = 1018;
  148. // Pixel formats
  149. THREE.AlphaFormat = 1019;
  150. THREE.RGBFormat = 1020;
  151. THREE.RGBAFormat = 1021;
  152. THREE.LuminanceFormat = 1022;
  153. THREE.LuminanceAlphaFormat = 1023;
  154. // Compressed texture formats
  155. THREE.RGB_S3TC_DXT1_Format = 2001;
  156. THREE.RGBA_S3TC_DXT1_Format = 2002;
  157. THREE.RGBA_S3TC_DXT3_Format = 2003;
  158. THREE.RGBA_S3TC_DXT5_Format = 2004;
  159. /*
  160. // Potential future PVRTC compressed texture formats
  161. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  162. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  163. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  164. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  165. */
  166. /**
  167. * @author mrdoob / http://mrdoob.com/
  168. */
  169. THREE.Color = function ( value ) {
  170. if ( value !== undefined ) this.set( value );
  171. return this;
  172. };
  173. THREE.Color.prototype = {
  174. constructor: THREE.Color,
  175. r: 1, g: 1, b: 1,
  176. set: function ( value ) {
  177. if ( value instanceof THREE.Color ) {
  178. this.copy( value );
  179. } else if ( typeof value === 'number' ) {
  180. this.setHex( value );
  181. } else if ( typeof value === 'string' ) {
  182. this.setStyle( value );
  183. }
  184. return this;
  185. },
  186. setHex: function ( hex ) {
  187. hex = Math.floor( hex );
  188. this.r = ( hex >> 16 & 255 ) / 255;
  189. this.g = ( hex >> 8 & 255 ) / 255;
  190. this.b = ( hex & 255 ) / 255;
  191. return this;
  192. },
  193. setRGB: function ( r, g, b ) {
  194. this.r = r;
  195. this.g = g;
  196. this.b = b;
  197. return this;
  198. },
  199. setHSL: function ( h, s, l ) {
  200. // h,s,l ranges are in 0.0 - 1.0
  201. if ( s === 0 ) {
  202. this.r = this.g = this.b = l;
  203. } else {
  204. var hue2rgb = function ( p, q, t ) {
  205. if ( t < 0 ) t += 1;
  206. if ( t > 1 ) t -= 1;
  207. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  208. if ( t < 1 / 2 ) return q;
  209. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  210. return p;
  211. };
  212. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  213. var q = ( 2 * l ) - p;
  214. this.r = hue2rgb( q, p, h + 1 / 3 );
  215. this.g = hue2rgb( q, p, h );
  216. this.b = hue2rgb( q, p, h - 1 / 3 );
  217. }
  218. return this;
  219. },
  220. setStyle: function ( style ) {
  221. // rgb(255,0,0)
  222. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  223. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  224. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  225. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  226. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  227. return this;
  228. }
  229. // rgb(100%,0%,0%)
  230. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  231. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  232. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  233. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  234. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  235. return this;
  236. }
  237. // #ff0000
  238. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  239. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  240. this.setHex( parseInt( color[ 1 ], 16 ) );
  241. return this;
  242. }
  243. // #f00
  244. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  245. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  246. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  247. return this;
  248. }
  249. // red
  250. if ( /^(\w+)$/i.test( style ) ) {
  251. this.setHex( THREE.ColorKeywords[ style ] );
  252. return this;
  253. }
  254. },
  255. copy: function ( color ) {
  256. this.r = color.r;
  257. this.g = color.g;
  258. this.b = color.b;
  259. return this;
  260. },
  261. copyGammaToLinear: function ( color ) {
  262. this.r = color.r * color.r;
  263. this.g = color.g * color.g;
  264. this.b = color.b * color.b;
  265. return this;
  266. },
  267. copyLinearToGamma: function ( color ) {
  268. this.r = Math.sqrt( color.r );
  269. this.g = Math.sqrt( color.g );
  270. this.b = Math.sqrt( color.b );
  271. return this;
  272. },
  273. convertGammaToLinear: function () {
  274. var r = this.r, g = this.g, b = this.b;
  275. this.r = r * r;
  276. this.g = g * g;
  277. this.b = b * b;
  278. return this;
  279. },
  280. convertLinearToGamma: function () {
  281. this.r = Math.sqrt( this.r );
  282. this.g = Math.sqrt( this.g );
  283. this.b = Math.sqrt( this.b );
  284. return this;
  285. },
  286. getHex: function () {
  287. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  288. },
  289. getHexString: function () {
  290. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  291. },
  292. getHSL: function () {
  293. var hsl = { h: 0, s: 0, l: 0 };
  294. return function () {
  295. // h,s,l ranges are in 0.0 - 1.0
  296. var r = this.r, g = this.g, b = this.b;
  297. var max = Math.max( r, g, b );
  298. var min = Math.min( r, g, b );
  299. var hue, saturation;
  300. var lightness = ( min + max ) / 2.0;
  301. if ( min === max ) {
  302. hue = 0;
  303. saturation = 0;
  304. } else {
  305. var delta = max - min;
  306. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  307. switch ( max ) {
  308. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  309. case g: hue = ( b - r ) / delta + 2; break;
  310. case b: hue = ( r - g ) / delta + 4; break;
  311. }
  312. hue /= 6;
  313. }
  314. hsl.h = hue;
  315. hsl.s = saturation;
  316. hsl.l = lightness;
  317. return hsl;
  318. };
  319. }(),
  320. getStyle: function () {
  321. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  322. },
  323. offsetHSL: function ( h, s, l ) {
  324. var hsl = this.getHSL();
  325. hsl.h += h; hsl.s += s; hsl.l += l;
  326. this.setHSL( hsl.h, hsl.s, hsl.l );
  327. return this;
  328. },
  329. add: function ( color ) {
  330. this.r += color.r;
  331. this.g += color.g;
  332. this.b += color.b;
  333. return this;
  334. },
  335. addColors: function ( color1, color2 ) {
  336. this.r = color1.r + color2.r;
  337. this.g = color1.g + color2.g;
  338. this.b = color1.b + color2.b;
  339. return this;
  340. },
  341. addScalar: function ( s ) {
  342. this.r += s;
  343. this.g += s;
  344. this.b += s;
  345. return this;
  346. },
  347. multiply: function ( color ) {
  348. this.r *= color.r;
  349. this.g *= color.g;
  350. this.b *= color.b;
  351. return this;
  352. },
  353. multiplyScalar: function ( s ) {
  354. this.r *= s;
  355. this.g *= s;
  356. this.b *= s;
  357. return this;
  358. },
  359. lerp: function ( color, alpha ) {
  360. this.r += ( color.r - this.r ) * alpha;
  361. this.g += ( color.g - this.g ) * alpha;
  362. this.b += ( color.b - this.b ) * alpha;
  363. return this;
  364. },
  365. equals: function ( c ) {
  366. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  367. },
  368. clone: function () {
  369. return new THREE.Color().setRGB( this.r, this.g, this.b );
  370. }
  371. };
  372. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  373. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  374. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  375. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  376. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  377. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  378. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  379. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  380. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  381. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  382. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  383. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  384. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  385. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  386. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  387. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  388. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  389. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  390. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  391. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  392. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  393. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  394. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  395. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  396. /**
  397. * @author mikael emtinger / http://gomo.se/
  398. * @author alteredq / http://alteredqualia.com/
  399. * @author WestLangley / http://github.com/WestLangley
  400. * @author bhouston / http://exocortex.com
  401. */
  402. THREE.Quaternion = function( x, y, z, w ) {
  403. this.x = x || 0;
  404. this.y = y || 0;
  405. this.z = z || 0;
  406. this.w = ( w !== undefined ) ? w : 1;
  407. };
  408. THREE.Quaternion.prototype = {
  409. constructor: THREE.Quaternion,
  410. set: function ( x, y, z, w ) {
  411. this.x = x;
  412. this.y = y;
  413. this.z = z;
  414. this.w = w;
  415. return this;
  416. },
  417. copy: function ( q ) {
  418. this.x = q.x;
  419. this.y = q.y;
  420. this.z = q.z;
  421. this.w = q.w;
  422. return this;
  423. },
  424. setFromEuler: function ( v, order ) {
  425. // http://www.mathworks.com/matlabcentral/fileexchange/
  426. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  427. // content/SpinCalc.m
  428. var c1 = Math.cos( v.x / 2 );
  429. var c2 = Math.cos( v.y / 2 );
  430. var c3 = Math.cos( v.z / 2 );
  431. var s1 = Math.sin( v.x / 2 );
  432. var s2 = Math.sin( v.y / 2 );
  433. var s3 = Math.sin( v.z / 2 );
  434. if ( order === undefined || order === 'XYZ' ) {
  435. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  436. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  437. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  438. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  439. } else if ( order === 'YXZ' ) {
  440. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  441. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  442. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  443. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  444. } else if ( order === 'ZXY' ) {
  445. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  446. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  447. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  448. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  449. } else if ( order === 'ZYX' ) {
  450. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  451. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  452. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  453. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  454. } else if ( order === 'YZX' ) {
  455. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  456. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  457. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  458. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  459. } else if ( order === 'XZY' ) {
  460. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  461. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  462. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  463. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  464. }
  465. return this;
  466. },
  467. setFromAxisAngle: function ( axis, angle ) {
  468. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  469. // axis have to be normalized
  470. var halfAngle = angle / 2,
  471. s = Math.sin( halfAngle );
  472. this.x = axis.x * s;
  473. this.y = axis.y * s;
  474. this.z = axis.z * s;
  475. this.w = Math.cos( halfAngle );
  476. return this;
  477. },
  478. setFromRotationMatrix: function ( m ) {
  479. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  480. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  481. var te = m.elements,
  482. m11 = te[0], m12 = te[4], m13 = te[8],
  483. m21 = te[1], m22 = te[5], m23 = te[9],
  484. m31 = te[2], m32 = te[6], m33 = te[10],
  485. trace = m11 + m22 + m33,
  486. s;
  487. if ( trace > 0 ) {
  488. s = 0.5 / Math.sqrt( trace + 1.0 );
  489. this.w = 0.25 / s;
  490. this.x = ( m32 - m23 ) * s;
  491. this.y = ( m13 - m31 ) * s;
  492. this.z = ( m21 - m12 ) * s;
  493. } else if ( m11 > m22 && m11 > m33 ) {
  494. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  495. this.w = (m32 - m23 ) / s;
  496. this.x = 0.25 * s;
  497. this.y = (m12 + m21 ) / s;
  498. this.z = (m13 + m31 ) / s;
  499. } else if ( m22 > m33 ) {
  500. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  501. this.w = (m13 - m31 ) / s;
  502. this.x = (m12 + m21 ) / s;
  503. this.y = 0.25 * s;
  504. this.z = (m23 + m32 ) / s;
  505. } else {
  506. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  507. this.w = ( m21 - m12 ) / s;
  508. this.x = ( m13 + m31 ) / s;
  509. this.y = ( m23 + m32 ) / s;
  510. this.z = 0.25 * s;
  511. }
  512. return this;
  513. },
  514. inverse: function () {
  515. this.conjugate().normalize();
  516. return this;
  517. },
  518. conjugate: function () {
  519. this.x *= -1;
  520. this.y *= -1;
  521. this.z *= -1;
  522. return this;
  523. },
  524. lengthSq: function () {
  525. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  526. },
  527. length: function () {
  528. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  529. },
  530. normalize: function () {
  531. var l = this.length();
  532. if ( l === 0 ) {
  533. this.x = 0;
  534. this.y = 0;
  535. this.z = 0;
  536. this.w = 1;
  537. } else {
  538. l = 1 / l;
  539. this.x = this.x * l;
  540. this.y = this.y * l;
  541. this.z = this.z * l;
  542. this.w = this.w * l;
  543. }
  544. return this;
  545. },
  546. multiply: function ( q, p ) {
  547. if ( p !== undefined ) {
  548. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  549. return this.multiplyQuaternions( q, p );
  550. }
  551. return this.multiplyQuaternions( this, q );
  552. },
  553. multiplyQuaternions: function ( a, b ) {
  554. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  555. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  556. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  557. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  558. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  559. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  560. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  561. return this;
  562. },
  563. multiplyVector3: function ( vector ) {
  564. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  565. return vector.applyQuaternion( this );
  566. },
  567. slerp: function ( qb, t ) {
  568. var x = this.x, y = this.y, z = this.z, w = this.w;
  569. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  570. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  571. if ( cosHalfTheta < 0 ) {
  572. this.w = -qb.w;
  573. this.x = -qb.x;
  574. this.y = -qb.y;
  575. this.z = -qb.z;
  576. cosHalfTheta = -cosHalfTheta;
  577. } else {
  578. this.copy( qb );
  579. }
  580. if ( cosHalfTheta >= 1.0 ) {
  581. this.w = w;
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. }
  587. var halfTheta = Math.acos( cosHalfTheta );
  588. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  589. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  590. this.w = 0.5 * ( w + this.w );
  591. this.x = 0.5 * ( x + this.x );
  592. this.y = 0.5 * ( y + this.y );
  593. this.z = 0.5 * ( z + this.z );
  594. return this;
  595. }
  596. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  597. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  598. this.w = ( w * ratioA + this.w * ratioB );
  599. this.x = ( x * ratioA + this.x * ratioB );
  600. this.y = ( y * ratioA + this.y * ratioB );
  601. this.z = ( z * ratioA + this.z * ratioB );
  602. return this;
  603. },
  604. equals: function ( v ) {
  605. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  606. },
  607. fromArray: function ( array ) {
  608. this.x = array[ 0 ];
  609. this.y = array[ 1 ];
  610. this.z = array[ 2 ];
  611. this.w = array[ 3 ];
  612. return this;
  613. },
  614. toArray: function () {
  615. return [ this.x, this.y, this.z, this.w ];
  616. },
  617. clone: function () {
  618. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  619. }
  620. };
  621. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  622. return qm.copy( qa ).slerp( qb, t );
  623. }
  624. /**
  625. * @author mrdoob / http://mrdoob.com/
  626. * @author philogb / http://blog.thejit.org/
  627. * @author egraether / http://egraether.com/
  628. * @author zz85 / http://www.lab4games.net/zz85/blog
  629. */
  630. THREE.Vector2 = function ( x, y ) {
  631. this.x = x || 0;
  632. this.y = y || 0;
  633. };
  634. THREE.Vector2.prototype = {
  635. constructor: THREE.Vector2,
  636. set: function ( x, y ) {
  637. this.x = x;
  638. this.y = y;
  639. return this;
  640. },
  641. setX: function ( x ) {
  642. this.x = x;
  643. return this;
  644. },
  645. setY: function ( y ) {
  646. this.y = y;
  647. return this;
  648. },
  649. setComponent: function ( index, value ) {
  650. switch ( index ) {
  651. case 0: this.x = value; break;
  652. case 1: this.y = value; break;
  653. default: throw new Error( "index is out of range: " + index );
  654. }
  655. },
  656. getComponent: function ( index ) {
  657. switch ( index ) {
  658. case 0: return this.x;
  659. case 1: return this.y;
  660. default: throw new Error( "index is out of range: " + index );
  661. }
  662. },
  663. copy: function ( v ) {
  664. this.x = v.x;
  665. this.y = v.y;
  666. return this;
  667. },
  668. add: function ( v, w ) {
  669. if ( w !== undefined ) {
  670. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  671. return this.addVectors( v, w );
  672. }
  673. this.x += v.x;
  674. this.y += v.y;
  675. return this;
  676. },
  677. addVectors: function ( a, b ) {
  678. this.x = a.x + b.x;
  679. this.y = a.y + b.y;
  680. return this;
  681. },
  682. addScalar: function ( s ) {
  683. this.x += s;
  684. this.y += s;
  685. return this;
  686. },
  687. sub: function ( v, w ) {
  688. if ( w !== undefined ) {
  689. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  690. return this.subVectors( v, w );
  691. }
  692. this.x -= v.x;
  693. this.y -= v.y;
  694. return this;
  695. },
  696. subVectors: function ( a, b ) {
  697. this.x = a.x - b.x;
  698. this.y = a.y - b.y;
  699. return this;
  700. },
  701. multiplyScalar: function ( s ) {
  702. this.x *= s;
  703. this.y *= s;
  704. return this;
  705. },
  706. divideScalar: function ( s ) {
  707. if ( s !== 0 ) {
  708. this.x /= s;
  709. this.y /= s;
  710. } else {
  711. this.set( 0, 0 );
  712. }
  713. return this;
  714. },
  715. min: function ( v ) {
  716. if ( this.x > v.x ) {
  717. this.x = v.x;
  718. }
  719. if ( this.y > v.y ) {
  720. this.y = v.y;
  721. }
  722. return this;
  723. },
  724. max: function ( v ) {
  725. if ( this.x < v.x ) {
  726. this.x = v.x;
  727. }
  728. if ( this.y < v.y ) {
  729. this.y = v.y;
  730. }
  731. return this;
  732. },
  733. clamp: function ( min, max ) {
  734. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  735. if ( this.x < min.x ) {
  736. this.x = min.x;
  737. } else if ( this.x > max.x ) {
  738. this.x = max.x;
  739. }
  740. if ( this.y < min.y ) {
  741. this.y = min.y;
  742. } else if ( this.y > max.y ) {
  743. this.y = max.y;
  744. }
  745. return this;
  746. },
  747. negate: function() {
  748. return this.multiplyScalar( - 1 );
  749. },
  750. dot: function ( v ) {
  751. return this.x * v.x + this.y * v.y;
  752. },
  753. lengthSq: function () {
  754. return this.x * this.x + this.y * this.y;
  755. },
  756. length: function () {
  757. return Math.sqrt( this.x * this.x + this.y * this.y );
  758. },
  759. normalize: function () {
  760. return this.divideScalar( this.length() );
  761. },
  762. distanceTo: function ( v ) {
  763. return Math.sqrt( this.distanceToSquared( v ) );
  764. },
  765. distanceToSquared: function ( v ) {
  766. var dx = this.x - v.x, dy = this.y - v.y;
  767. return dx * dx + dy * dy;
  768. },
  769. setLength: function ( l ) {
  770. var oldLength = this.length();
  771. if ( oldLength !== 0 && l !== oldLength ) {
  772. this.multiplyScalar( l / oldLength );
  773. }
  774. return this;
  775. },
  776. lerp: function ( v, alpha ) {
  777. this.x += ( v.x - this.x ) * alpha;
  778. this.y += ( v.y - this.y ) * alpha;
  779. return this;
  780. },
  781. equals: function( v ) {
  782. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  783. },
  784. fromArray: function ( array ) {
  785. this.x = array[ 0 ];
  786. this.y = array[ 1 ];
  787. return this;
  788. },
  789. toArray: function () {
  790. return [ this.x, this.y ];
  791. },
  792. clone: function () {
  793. return new THREE.Vector2( this.x, this.y );
  794. }
  795. };
  796. /**
  797. * @author mrdoob / http://mrdoob.com/
  798. * @author *kile / http://kile.stravaganza.org/
  799. * @author philogb / http://blog.thejit.org/
  800. * @author mikael emtinger / http://gomo.se/
  801. * @author egraether / http://egraether.com/
  802. * @author WestLangley / http://github.com/WestLangley
  803. */
  804. THREE.Vector3 = function ( x, y, z ) {
  805. this.x = x || 0;
  806. this.y = y || 0;
  807. this.z = z || 0;
  808. };
  809. THREE.Vector3.prototype = {
  810. constructor: THREE.Vector3,
  811. set: function ( x, y, z ) {
  812. this.x = x;
  813. this.y = y;
  814. this.z = z;
  815. return this;
  816. },
  817. setX: function ( x ) {
  818. this.x = x;
  819. return this;
  820. },
  821. setY: function ( y ) {
  822. this.y = y;
  823. return this;
  824. },
  825. setZ: function ( z ) {
  826. this.z = z;
  827. return this;
  828. },
  829. setComponent: function ( index, value ) {
  830. switch ( index ) {
  831. case 0: this.x = value; break;
  832. case 1: this.y = value; break;
  833. case 2: this.z = value; break;
  834. default: throw new Error( "index is out of range: " + index );
  835. }
  836. },
  837. getComponent: function ( index ) {
  838. switch ( index ) {
  839. case 0: return this.x;
  840. case 1: return this.y;
  841. case 2: return this.z;
  842. default: throw new Error( "index is out of range: " + index );
  843. }
  844. },
  845. copy: function ( v ) {
  846. this.x = v.x;
  847. this.y = v.y;
  848. this.z = v.z;
  849. return this;
  850. },
  851. add: function ( v, w ) {
  852. if ( w !== undefined ) {
  853. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  854. return this.addVectors( v, w );
  855. }
  856. this.x += v.x;
  857. this.y += v.y;
  858. this.z += v.z;
  859. return this;
  860. },
  861. addScalar: function ( s ) {
  862. this.x += s;
  863. this.y += s;
  864. this.z += s;
  865. return this;
  866. },
  867. addVectors: function ( a, b ) {
  868. this.x = a.x + b.x;
  869. this.y = a.y + b.y;
  870. this.z = a.z + b.z;
  871. return this;
  872. },
  873. sub: function ( v, w ) {
  874. if ( w !== undefined ) {
  875. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  876. return this.subVectors( v, w );
  877. }
  878. this.x -= v.x;
  879. this.y -= v.y;
  880. this.z -= v.z;
  881. return this;
  882. },
  883. subVectors: function ( a, b ) {
  884. this.x = a.x - b.x;
  885. this.y = a.y - b.y;
  886. this.z = a.z - b.z;
  887. return this;
  888. },
  889. multiply: function ( v, w ) {
  890. if ( w !== undefined ) {
  891. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  892. return this.multiplyVectors( v, w );
  893. }
  894. this.x *= v.x;
  895. this.y *= v.y;
  896. this.z *= v.z;
  897. return this;
  898. },
  899. multiplyScalar: function ( s ) {
  900. this.x *= s;
  901. this.y *= s;
  902. this.z *= s;
  903. return this;
  904. },
  905. multiplyVectors: function ( a, b ) {
  906. this.x = a.x * b.x;
  907. this.y = a.y * b.y;
  908. this.z = a.z * b.z;
  909. return this;
  910. },
  911. applyMatrix3: function ( m ) {
  912. var x = this.x;
  913. var y = this.y;
  914. var z = this.z;
  915. var e = m.elements;
  916. this.x = e[0] * x + e[3] * y + e[6] * z;
  917. this.y = e[1] * x + e[4] * y + e[7] * z;
  918. this.z = e[2] * x + e[5] * y + e[8] * z;
  919. return this;
  920. },
  921. applyMatrix4: function ( m ) {
  922. // input: THREE.Matrix4 affine matrix
  923. var x = this.x, y = this.y, z = this.z;
  924. var e = m.elements;
  925. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  926. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  927. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  928. return this;
  929. },
  930. applyProjection: function ( m ) {
  931. // input: THREE.Matrix4 projection matrix
  932. var x = this.x, y = this.y, z = this.z;
  933. var e = m.elements;
  934. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  935. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  936. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  937. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  938. return this;
  939. },
  940. applyQuaternion: function ( q ) {
  941. var x = this.x;
  942. var y = this.y;
  943. var z = this.z;
  944. var qx = q.x;
  945. var qy = q.y;
  946. var qz = q.z;
  947. var qw = q.w;
  948. // calculate quat * vector
  949. var ix = qw * x + qy * z - qz * y;
  950. var iy = qw * y + qz * x - qx * z;
  951. var iz = qw * z + qx * y - qy * x;
  952. var iw = -qx * x - qy * y - qz * z;
  953. // calculate result * inverse quat
  954. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  955. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  956. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  957. return this;
  958. },
  959. transformDirection: function ( m ) {
  960. // input: THREE.Matrix4 affine matrix
  961. // vector interpreted as a direction
  962. var x = this.x, y = this.y, z = this.z;
  963. var e = m.elements;
  964. this.x = e[0] * x + e[4] * y + e[8] * z;
  965. this.y = e[1] * x + e[5] * y + e[9] * z;
  966. this.z = e[2] * x + e[6] * y + e[10] * z;
  967. this.normalize();
  968. return this;
  969. },
  970. divide: function ( v ) {
  971. this.x /= v.x;
  972. this.y /= v.y;
  973. this.z /= v.z;
  974. return this;
  975. },
  976. divideScalar: function ( s ) {
  977. if ( s !== 0 ) {
  978. this.x /= s;
  979. this.y /= s;
  980. this.z /= s;
  981. } else {
  982. this.x = 0;
  983. this.y = 0;
  984. this.z = 0;
  985. }
  986. return this;
  987. },
  988. min: function ( v ) {
  989. if ( this.x > v.x ) {
  990. this.x = v.x;
  991. }
  992. if ( this.y > v.y ) {
  993. this.y = v.y;
  994. }
  995. if ( this.z > v.z ) {
  996. this.z = v.z;
  997. }
  998. return this;
  999. },
  1000. max: function ( v ) {
  1001. if ( this.x < v.x ) {
  1002. this.x = v.x;
  1003. }
  1004. if ( this.y < v.y ) {
  1005. this.y = v.y;
  1006. }
  1007. if ( this.z < v.z ) {
  1008. this.z = v.z;
  1009. }
  1010. return this;
  1011. },
  1012. clamp: function ( min, max ) {
  1013. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1014. if ( this.x < min.x ) {
  1015. this.x = min.x;
  1016. } else if ( this.x > max.x ) {
  1017. this.x = max.x;
  1018. }
  1019. if ( this.y < min.y ) {
  1020. this.y = min.y;
  1021. } else if ( this.y > max.y ) {
  1022. this.y = max.y;
  1023. }
  1024. if ( this.z < min.z ) {
  1025. this.z = min.z;
  1026. } else if ( this.z > max.z ) {
  1027. this.z = max.z;
  1028. }
  1029. return this;
  1030. },
  1031. negate: function () {
  1032. return this.multiplyScalar( - 1 );
  1033. },
  1034. dot: function ( v ) {
  1035. return this.x * v.x + this.y * v.y + this.z * v.z;
  1036. },
  1037. lengthSq: function () {
  1038. return this.x * this.x + this.y * this.y + this.z * this.z;
  1039. },
  1040. length: function () {
  1041. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1042. },
  1043. lengthManhattan: function () {
  1044. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1045. },
  1046. normalize: function () {
  1047. return this.divideScalar( this.length() );
  1048. },
  1049. setLength: function ( l ) {
  1050. var oldLength = this.length();
  1051. if ( oldLength !== 0 && l !== oldLength ) {
  1052. this.multiplyScalar( l / oldLength );
  1053. }
  1054. return this;
  1055. },
  1056. lerp: function ( v, alpha ) {
  1057. this.x += ( v.x - this.x ) * alpha;
  1058. this.y += ( v.y - this.y ) * alpha;
  1059. this.z += ( v.z - this.z ) * alpha;
  1060. return this;
  1061. },
  1062. cross: function ( v, w ) {
  1063. if ( w !== undefined ) {
  1064. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1065. return this.crossVectors( v, w );
  1066. }
  1067. var x = this.x, y = this.y, z = this.z;
  1068. this.x = y * v.z - z * v.y;
  1069. this.y = z * v.x - x * v.z;
  1070. this.z = x * v.y - y * v.x;
  1071. return this;
  1072. },
  1073. crossVectors: function ( a, b ) {
  1074. this.x = a.y * b.z - a.z * b.y;
  1075. this.y = a.z * b.x - a.x * b.z;
  1076. this.z = a.x * b.y - a.y * b.x;
  1077. return this;
  1078. },
  1079. angleTo: function ( v ) {
  1080. var theta = this.dot( v ) / ( this.length() * v.length() );
  1081. // clamp, to handle numerical problems
  1082. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1083. },
  1084. distanceTo: function ( v ) {
  1085. return Math.sqrt( this.distanceToSquared( v ) );
  1086. },
  1087. distanceToSquared: function ( v ) {
  1088. var dx = this.x - v.x;
  1089. var dy = this.y - v.y;
  1090. var dz = this.z - v.z;
  1091. return dx * dx + dy * dy + dz * dz;
  1092. },
  1093. setEulerFromRotationMatrix: function ( m, order ) {
  1094. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1095. // clamp, to handle numerical problems
  1096. function clamp( x ) {
  1097. return Math.min( Math.max( x, -1 ), 1 );
  1098. }
  1099. var te = m.elements;
  1100. var m11 = te[0], m12 = te[4], m13 = te[8];
  1101. var m21 = te[1], m22 = te[5], m23 = te[9];
  1102. var m31 = te[2], m32 = te[6], m33 = te[10];
  1103. if ( order === undefined || order === 'XYZ' ) {
  1104. this.y = Math.asin( clamp( m13 ) );
  1105. if ( Math.abs( m13 ) < 0.99999 ) {
  1106. this.x = Math.atan2( - m23, m33 );
  1107. this.z = Math.atan2( - m12, m11 );
  1108. } else {
  1109. this.x = Math.atan2( m32, m22 );
  1110. this.z = 0;
  1111. }
  1112. } else if ( order === 'YXZ' ) {
  1113. this.x = Math.asin( - clamp( m23 ) );
  1114. if ( Math.abs( m23 ) < 0.99999 ) {
  1115. this.y = Math.atan2( m13, m33 );
  1116. this.z = Math.atan2( m21, m22 );
  1117. } else {
  1118. this.y = Math.atan2( - m31, m11 );
  1119. this.z = 0;
  1120. }
  1121. } else if ( order === 'ZXY' ) {
  1122. this.x = Math.asin( clamp( m32 ) );
  1123. if ( Math.abs( m32 ) < 0.99999 ) {
  1124. this.y = Math.atan2( - m31, m33 );
  1125. this.z = Math.atan2( - m12, m22 );
  1126. } else {
  1127. this.y = 0;
  1128. this.z = Math.atan2( m21, m11 );
  1129. }
  1130. } else if ( order === 'ZYX' ) {
  1131. this.y = Math.asin( - clamp( m31 ) );
  1132. if ( Math.abs( m31 ) < 0.99999 ) {
  1133. this.x = Math.atan2( m32, m33 );
  1134. this.z = Math.atan2( m21, m11 );
  1135. } else {
  1136. this.x = 0;
  1137. this.z = Math.atan2( - m12, m22 );
  1138. }
  1139. } else if ( order === 'YZX' ) {
  1140. this.z = Math.asin( clamp( m21 ) );
  1141. if ( Math.abs( m21 ) < 0.99999 ) {
  1142. this.x = Math.atan2( - m23, m22 );
  1143. this.y = Math.atan2( - m31, m11 );
  1144. } else {
  1145. this.x = 0;
  1146. this.y = Math.atan2( m13, m33 );
  1147. }
  1148. } else if ( order === 'XZY' ) {
  1149. this.z = Math.asin( - clamp( m12 ) );
  1150. if ( Math.abs( m12 ) < 0.99999 ) {
  1151. this.x = Math.atan2( m32, m22 );
  1152. this.y = Math.atan2( m13, m11 );
  1153. } else {
  1154. this.x = Math.atan2( - m23, m33 );
  1155. this.y = 0;
  1156. }
  1157. }
  1158. return this;
  1159. },
  1160. setEulerFromQuaternion: function ( q, order ) {
  1161. // q is assumed to be normalized
  1162. // clamp, to handle numerical problems
  1163. function clamp( x ) {
  1164. return Math.min( Math.max( x, -1 ), 1 );
  1165. }
  1166. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1167. var sqx = q.x * q.x;
  1168. var sqy = q.y * q.y;
  1169. var sqz = q.z * q.z;
  1170. var sqw = q.w * q.w;
  1171. if ( order === undefined || order === 'XYZ' ) {
  1172. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1173. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1174. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1175. } else if ( order === 'YXZ' ) {
  1176. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1177. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1178. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1179. } else if ( order === 'ZXY' ) {
  1180. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1181. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1182. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1183. } else if ( order === 'ZYX' ) {
  1184. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1185. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1186. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1187. } else if ( order === 'YZX' ) {
  1188. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1189. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1190. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1191. } else if ( order === 'XZY' ) {
  1192. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1193. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1194. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1195. }
  1196. return this;
  1197. },
  1198. getPositionFromMatrix: function ( m ) {
  1199. this.x = m.elements[12];
  1200. this.y = m.elements[13];
  1201. this.z = m.elements[14];
  1202. return this;
  1203. },
  1204. getScaleFromMatrix: function ( m ) {
  1205. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1206. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1207. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1208. this.x = sx;
  1209. this.y = sy;
  1210. this.z = sz;
  1211. return this;
  1212. },
  1213. getColumnFromMatrix: function ( index, matrix ) {
  1214. var offset = index * 4;
  1215. var me = matrix.elements;
  1216. this.x = me[ offset ];
  1217. this.y = me[ offset + 1 ];
  1218. this.z = me[ offset + 2 ];
  1219. return this;
  1220. },
  1221. equals: function ( v ) {
  1222. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1223. },
  1224. fromArray: function ( array ) {
  1225. this.x = array[ 0 ];
  1226. this.y = array[ 1 ];
  1227. this.z = array[ 2 ];
  1228. return this;
  1229. },
  1230. toArray: function () {
  1231. return [ this.x, this.y, this.z ];
  1232. },
  1233. clone: function () {
  1234. return new THREE.Vector3( this.x, this.y, this.z );
  1235. }
  1236. };
  1237. THREE.extend( THREE.Vector3.prototype, {
  1238. applyEuler: function () {
  1239. var q1 = new THREE.Quaternion();
  1240. return function ( v, eulerOrder ) {
  1241. var quaternion = q1.setFromEuler( v, eulerOrder );
  1242. this.applyQuaternion( quaternion );
  1243. return this;
  1244. };
  1245. }(),
  1246. applyAxisAngle: function () {
  1247. var q1 = new THREE.Quaternion();
  1248. return function ( axis, angle ) {
  1249. var quaternion = q1.setFromAxisAngle( axis, angle );
  1250. this.applyQuaternion( quaternion );
  1251. return this;
  1252. };
  1253. }(),
  1254. projectOnVector: function () {
  1255. var v1 = new THREE.Vector3();
  1256. return function ( vector ) {
  1257. v1.copy( vector ).normalize();
  1258. var d = this.dot( v1 );
  1259. return this.copy( v1 ).multiplyScalar( d );
  1260. };
  1261. }(),
  1262. projectOnPlane: function () {
  1263. var v1 = new THREE.Vector3();
  1264. return function ( planeNormal ) {
  1265. v1.copy( this ).projectOnVector( planeNormal );
  1266. return this.sub( v1 );
  1267. }
  1268. }(),
  1269. reflect: function () {
  1270. var v1 = new THREE.Vector3();
  1271. return function ( vector ) {
  1272. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1273. return this.subVectors( v1, this );
  1274. }
  1275. }()
  1276. } );
  1277. /**
  1278. * @author supereggbert / http://www.paulbrunt.co.uk/
  1279. * @author philogb / http://blog.thejit.org/
  1280. * @author mikael emtinger / http://gomo.se/
  1281. * @author egraether / http://egraether.com/
  1282. * @author WestLangley / http://github.com/WestLangley
  1283. */
  1284. THREE.Vector4 = function ( x, y, z, w ) {
  1285. this.x = x || 0;
  1286. this.y = y || 0;
  1287. this.z = z || 0;
  1288. this.w = ( w !== undefined ) ? w : 1;
  1289. };
  1290. THREE.Vector4.prototype = {
  1291. constructor: THREE.Vector4,
  1292. set: function ( x, y, z, w ) {
  1293. this.x = x;
  1294. this.y = y;
  1295. this.z = z;
  1296. this.w = w;
  1297. return this;
  1298. },
  1299. setX: function ( x ) {
  1300. this.x = x;
  1301. return this;
  1302. },
  1303. setY: function ( y ) {
  1304. this.y = y;
  1305. return this;
  1306. },
  1307. setZ: function ( z ) {
  1308. this.z = z;
  1309. return this;
  1310. },
  1311. setW: function ( w ) {
  1312. this.w = w;
  1313. return this;
  1314. },
  1315. setComponent: function ( index, value ) {
  1316. switch ( index ) {
  1317. case 0: this.x = value; break;
  1318. case 1: this.y = value; break;
  1319. case 2: this.z = value; break;
  1320. case 3: this.w = value; break;
  1321. default: throw new Error( "index is out of range: " + index );
  1322. }
  1323. },
  1324. getComponent: function ( index ) {
  1325. switch ( index ) {
  1326. case 0: return this.x;
  1327. case 1: return this.y;
  1328. case 2: return this.z;
  1329. case 3: return this.w;
  1330. default: throw new Error( "index is out of range: " + index );
  1331. }
  1332. },
  1333. copy: function ( v ) {
  1334. this.x = v.x;
  1335. this.y = v.y;
  1336. this.z = v.z;
  1337. this.w = ( v.w !== undefined ) ? v.w : 1;
  1338. return this;
  1339. },
  1340. add: function ( v, w ) {
  1341. if ( w !== undefined ) {
  1342. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1343. return this.addVectors( v, w );
  1344. }
  1345. this.x += v.x;
  1346. this.y += v.y;
  1347. this.z += v.z;
  1348. this.w += v.w;
  1349. return this;
  1350. },
  1351. addScalar: function ( s ) {
  1352. this.x += s;
  1353. this.y += s;
  1354. this.z += s;
  1355. this.w += s;
  1356. return this;
  1357. },
  1358. addVectors: function ( a, b ) {
  1359. this.x = a.x + b.x;
  1360. this.y = a.y + b.y;
  1361. this.z = a.z + b.z;
  1362. this.w = a.w + b.w;
  1363. return this;
  1364. },
  1365. sub: function ( v, w ) {
  1366. if ( w !== undefined ) {
  1367. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1368. return this.subVectors( v, w );
  1369. }
  1370. this.x -= v.x;
  1371. this.y -= v.y;
  1372. this.z -= v.z;
  1373. this.w -= v.w;
  1374. return this;
  1375. },
  1376. subVectors: function ( a, b ) {
  1377. this.x = a.x - b.x;
  1378. this.y = a.y - b.y;
  1379. this.z = a.z - b.z;
  1380. this.w = a.w - b.w;
  1381. return this;
  1382. },
  1383. multiplyScalar: function ( s ) {
  1384. this.x *= s;
  1385. this.y *= s;
  1386. this.z *= s;
  1387. this.w *= s;
  1388. return this;
  1389. },
  1390. applyMatrix4: function ( m ) {
  1391. var x = this.x;
  1392. var y = this.y;
  1393. var z = this.z;
  1394. var w = this.w;
  1395. var e = m.elements;
  1396. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1397. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1398. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1399. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1400. return this;
  1401. },
  1402. divideScalar: function ( s ) {
  1403. if ( s !== 0 ) {
  1404. this.x /= s;
  1405. this.y /= s;
  1406. this.z /= s;
  1407. this.w /= s;
  1408. } else {
  1409. this.x = 0;
  1410. this.y = 0;
  1411. this.z = 0;
  1412. this.w = 1;
  1413. }
  1414. return this;
  1415. },
  1416. setAxisAngleFromQuaternion: function ( q ) {
  1417. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1418. // q is assumed to be normalized
  1419. this.w = 2 * Math.acos( q.w );
  1420. var s = Math.sqrt( 1 - q.w * q.w );
  1421. if ( s < 0.0001 ) {
  1422. this.x = 1;
  1423. this.y = 0;
  1424. this.z = 0;
  1425. } else {
  1426. this.x = q.x / s;
  1427. this.y = q.y / s;
  1428. this.z = q.z / s;
  1429. }
  1430. return this;
  1431. },
  1432. setAxisAngleFromRotationMatrix: function ( m ) {
  1433. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1434. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1435. var angle, x, y, z, // variables for result
  1436. epsilon = 0.01, // margin to allow for rounding errors
  1437. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1438. te = m.elements,
  1439. m11 = te[0], m12 = te[4], m13 = te[8],
  1440. m21 = te[1], m22 = te[5], m23 = te[9],
  1441. m31 = te[2], m32 = te[6], m33 = te[10];
  1442. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1443. && ( Math.abs( m13 - m31 ) < epsilon )
  1444. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1445. // singularity found
  1446. // first check for identity matrix which must have +1 for all terms
  1447. // in leading diagonal and zero in other terms
  1448. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1449. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1450. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1451. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1452. // this singularity is identity matrix so angle = 0
  1453. this.set( 1, 0, 0, 0 );
  1454. return this; // zero angle, arbitrary axis
  1455. }
  1456. // otherwise this singularity is angle = 180
  1457. angle = Math.PI;
  1458. var xx = ( m11 + 1 ) / 2;
  1459. var yy = ( m22 + 1 ) / 2;
  1460. var zz = ( m33 + 1 ) / 2;
  1461. var xy = ( m12 + m21 ) / 4;
  1462. var xz = ( m13 + m31 ) / 4;
  1463. var yz = ( m23 + m32 ) / 4;
  1464. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1465. if ( xx < epsilon ) {
  1466. x = 0;
  1467. y = 0.707106781;
  1468. z = 0.707106781;
  1469. } else {
  1470. x = Math.sqrt( xx );
  1471. y = xy / x;
  1472. z = xz / x;
  1473. }
  1474. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1475. if ( yy < epsilon ) {
  1476. x = 0.707106781;
  1477. y = 0;
  1478. z = 0.707106781;
  1479. } else {
  1480. y = Math.sqrt( yy );
  1481. x = xy / y;
  1482. z = yz / y;
  1483. }
  1484. } else { // m33 is the largest diagonal term so base result on this
  1485. if ( zz < epsilon ) {
  1486. x = 0.707106781;
  1487. y = 0.707106781;
  1488. z = 0;
  1489. } else {
  1490. z = Math.sqrt( zz );
  1491. x = xz / z;
  1492. y = yz / z;
  1493. }
  1494. }
  1495. this.set( x, y, z, angle );
  1496. return this; // return 180 deg rotation
  1497. }
  1498. // as we have reached here there are no singularities so we can handle normally
  1499. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1500. + ( m13 - m31 ) * ( m13 - m31 )
  1501. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1502. if ( Math.abs( s ) < 0.001 ) s = 1;
  1503. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1504. // caught by singularity test above, but I've left it in just in case
  1505. this.x = ( m32 - m23 ) / s;
  1506. this.y = ( m13 - m31 ) / s;
  1507. this.z = ( m21 - m12 ) / s;
  1508. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1509. return this;
  1510. },
  1511. min: function ( v ) {
  1512. if ( this.x > v.x ) {
  1513. this.x = v.x;
  1514. }
  1515. if ( this.y > v.y ) {
  1516. this.y = v.y;
  1517. }
  1518. if ( this.z > v.z ) {
  1519. this.z = v.z;
  1520. }
  1521. if ( this.w > v.w ) {
  1522. this.w = v.w;
  1523. }
  1524. return this;
  1525. },
  1526. max: function ( v ) {
  1527. if ( this.x < v.x ) {
  1528. this.x = v.x;
  1529. }
  1530. if ( this.y < v.y ) {
  1531. this.y = v.y;
  1532. }
  1533. if ( this.z < v.z ) {
  1534. this.z = v.z;
  1535. }
  1536. if ( this.w < v.w ) {
  1537. this.w = v.w;
  1538. }
  1539. return this;
  1540. },
  1541. clamp: function ( min, max ) {
  1542. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1543. if ( this.x < min.x ) {
  1544. this.x = min.x;
  1545. } else if ( this.x > max.x ) {
  1546. this.x = max.x;
  1547. }
  1548. if ( this.y < min.y ) {
  1549. this.y = min.y;
  1550. } else if ( this.y > max.y ) {
  1551. this.y = max.y;
  1552. }
  1553. if ( this.z < min.z ) {
  1554. this.z = min.z;
  1555. } else if ( this.z > max.z ) {
  1556. this.z = max.z;
  1557. }
  1558. if ( this.w < min.w ) {
  1559. this.w = min.w;
  1560. } else if ( this.w > max.w ) {
  1561. this.w = max.w;
  1562. }
  1563. return this;
  1564. },
  1565. negate: function() {
  1566. return this.multiplyScalar( -1 );
  1567. },
  1568. dot: function ( v ) {
  1569. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1570. },
  1571. lengthSq: function () {
  1572. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1573. },
  1574. length: function () {
  1575. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1576. },
  1577. lengthManhattan: function () {
  1578. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1579. },
  1580. normalize: function () {
  1581. return this.divideScalar( this.length() );
  1582. },
  1583. setLength: function ( l ) {
  1584. var oldLength = this.length();
  1585. if ( oldLength !== 0 && l !== oldLength ) {
  1586. this.multiplyScalar( l / oldLength );
  1587. }
  1588. return this;
  1589. },
  1590. lerp: function ( v, alpha ) {
  1591. this.x += ( v.x - this.x ) * alpha;
  1592. this.y += ( v.y - this.y ) * alpha;
  1593. this.z += ( v.z - this.z ) * alpha;
  1594. this.w += ( v.w - this.w ) * alpha;
  1595. return this;
  1596. },
  1597. equals: function ( v ) {
  1598. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1599. },
  1600. fromArray: function ( array ) {
  1601. this.x = array[ 0 ];
  1602. this.y = array[ 1 ];
  1603. this.z = array[ 2 ];
  1604. this.w = array[ 3 ];
  1605. return this;
  1606. },
  1607. toArray: function () {
  1608. return [ this.x, this.y, this.z, this.w ];
  1609. },
  1610. clone: function () {
  1611. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1612. }
  1613. };
  1614. /**
  1615. * @author bhouston / http://exocortex.com
  1616. */
  1617. THREE.Line3 = function ( start, end ) {
  1618. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1619. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1620. };
  1621. THREE.Line3.prototype = {
  1622. constructor: THREE.Line3,
  1623. set: function ( start, end ) {
  1624. this.start.copy( start );
  1625. this.end.copy( end );
  1626. return this;
  1627. },
  1628. copy: function ( line ) {
  1629. this.start.copy( line.start );
  1630. this.end.copy( line.end );
  1631. return this;
  1632. },
  1633. center: function ( optionalTarget ) {
  1634. var result = optionalTarget || new THREE.Vector3();
  1635. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1636. },
  1637. delta: function ( optionalTarget ) {
  1638. var result = optionalTarget || new THREE.Vector3();
  1639. return result.subVectors( this.end, this.start );
  1640. },
  1641. distanceSq: function () {
  1642. return this.start.distanceToSquared( this.end );
  1643. },
  1644. distance: function () {
  1645. return this.start.distanceTo( this.end );
  1646. },
  1647. at: function ( t, optionalTarget ) {
  1648. var result = optionalTarget || new THREE.Vector3();
  1649. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1650. },
  1651. closestPointToPointParameter: function() {
  1652. var startP = new THREE.Vector3();
  1653. var startEnd = new THREE.Vector3();
  1654. return function ( point, clampToLine ) {
  1655. startP.subVectors( point, this.start );
  1656. startEnd.subVectors( this.end, this.start );
  1657. var startEnd2 = startEnd.dot( startEnd );
  1658. var startEnd_startP = startEnd.dot( startP );
  1659. var t = startEnd_startP / startEnd2;
  1660. if ( clampToLine ) {
  1661. t = THREE.Math.clamp( t, 0, 1 );
  1662. }
  1663. return t;
  1664. };
  1665. }(),
  1666. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1667. var t = this.closestPointToPointParameter( point, clampToLine );
  1668. var result = optionalTarget || new THREE.Vector3();
  1669. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1670. },
  1671. applyMatrix4: function ( matrix ) {
  1672. this.start.applyMatrix4( matrix );
  1673. this.end.applyMatrix4( matrix );
  1674. return this;
  1675. },
  1676. equals: function ( line ) {
  1677. return line.start.equals( this.start ) && line.end.equals( this.end );
  1678. },
  1679. clone: function () {
  1680. return new THREE.Line3().copy( this );
  1681. }
  1682. };
  1683. /**
  1684. * @author bhouston / http://exocortex.com
  1685. */
  1686. THREE.Box2 = function ( min, max ) {
  1687. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1688. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1689. };
  1690. THREE.Box2.prototype = {
  1691. constructor: THREE.Box2,
  1692. set: function ( min, max ) {
  1693. this.min.copy( min );
  1694. this.max.copy( max );
  1695. return this;
  1696. },
  1697. setFromPoints: function ( points ) {
  1698. if ( points.length > 0 ) {
  1699. var point = points[ 0 ];
  1700. this.min.copy( point );
  1701. this.max.copy( point );
  1702. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1703. point = points[ i ];
  1704. if ( point.x < this.min.x ) {
  1705. this.min.x = point.x;
  1706. } else if ( point.x > this.max.x ) {
  1707. this.max.x = point.x;
  1708. }
  1709. if ( point.y < this.min.y ) {
  1710. this.min.y = point.y;
  1711. } else if ( point.y > this.max.y ) {
  1712. this.max.y = point.y;
  1713. }
  1714. }
  1715. } else {
  1716. this.makeEmpty();
  1717. }
  1718. return this;
  1719. },
  1720. setFromCenterAndSize: function () {
  1721. var v1 = new THREE.Vector2();
  1722. return function ( center, size ) {
  1723. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1724. this.min.copy( center ).sub( halfSize );
  1725. this.max.copy( center ).add( halfSize );
  1726. return this;
  1727. };
  1728. }(),
  1729. copy: function ( box ) {
  1730. this.min.copy( box.min );
  1731. this.max.copy( box.max );
  1732. return this;
  1733. },
  1734. makeEmpty: function () {
  1735. this.min.x = this.min.y = Infinity;
  1736. this.max.x = this.max.y = -Infinity;
  1737. return this;
  1738. },
  1739. empty: function () {
  1740. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1741. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1742. },
  1743. center: function ( optionalTarget ) {
  1744. var result = optionalTarget || new THREE.Vector2();
  1745. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1746. },
  1747. size: function ( optionalTarget ) {
  1748. var result = optionalTarget || new THREE.Vector2();
  1749. return result.subVectors( this.max, this.min );
  1750. },
  1751. expandByPoint: function ( point ) {
  1752. this.min.min( point );
  1753. this.max.max( point );
  1754. return this;
  1755. },
  1756. expandByVector: function ( vector ) {
  1757. this.min.sub( vector );
  1758. this.max.add( vector );
  1759. return this;
  1760. },
  1761. expandByScalar: function ( scalar ) {
  1762. this.min.addScalar( -scalar );
  1763. this.max.addScalar( scalar );
  1764. return this;
  1765. },
  1766. containsPoint: function ( point ) {
  1767. if ( point.x < this.min.x || point.x > this.max.x ||
  1768. point.y < this.min.y || point.y > this.max.y ) {
  1769. return false;
  1770. }
  1771. return true;
  1772. },
  1773. containsBox: function ( box ) {
  1774. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1775. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1776. return true;
  1777. }
  1778. return false;
  1779. },
  1780. getParameter: function ( point ) {
  1781. // This can potentially have a divide by zero if the box
  1782. // has a size dimension of 0.
  1783. return new THREE.Vector2(
  1784. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1785. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1786. );
  1787. },
  1788. isIntersectionBox: function ( box ) {
  1789. // using 6 splitting planes to rule out intersections.
  1790. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1791. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1792. return false;
  1793. }
  1794. return true;
  1795. },
  1796. clampPoint: function ( point, optionalTarget ) {
  1797. var result = optionalTarget || new THREE.Vector2();
  1798. return result.copy( point ).clamp( this.min, this.max );
  1799. },
  1800. distanceToPoint: function () {
  1801. var v1 = new THREE.Vector2();
  1802. return function ( point ) {
  1803. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1804. return clampedPoint.sub( point ).length();
  1805. };
  1806. }(),
  1807. intersect: function ( box ) {
  1808. this.min.max( box.min );
  1809. this.max.min( box.max );
  1810. return this;
  1811. },
  1812. union: function ( box ) {
  1813. this.min.min( box.min );
  1814. this.max.max( box.max );
  1815. return this;
  1816. },
  1817. translate: function ( offset ) {
  1818. this.min.add( offset );
  1819. this.max.add( offset );
  1820. return this;
  1821. },
  1822. equals: function ( box ) {
  1823. return box.min.equals( this.min ) && box.max.equals( this.max );
  1824. },
  1825. clone: function () {
  1826. return new THREE.Box2().copy( this );
  1827. }
  1828. };
  1829. /**
  1830. * @author bhouston / http://exocortex.com
  1831. */
  1832. THREE.Box3 = function ( min, max ) {
  1833. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1834. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1835. };
  1836. THREE.Box3.prototype = {
  1837. constructor: THREE.Box3,
  1838. set: function ( min, max ) {
  1839. this.min.copy( min );
  1840. this.max.copy( max );
  1841. return this;
  1842. },
  1843. setFromPoints: function ( points ) {
  1844. if ( points.length > 0 ) {
  1845. var point = points[ 0 ];
  1846. this.min.copy( point );
  1847. this.max.copy( point );
  1848. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1849. point = points[ i ];
  1850. if ( point.x < this.min.x ) {
  1851. this.min.x = point.x;
  1852. } else if ( point.x > this.max.x ) {
  1853. this.max.x = point.x;
  1854. }
  1855. if ( point.y < this.min.y ) {
  1856. this.min.y = point.y;
  1857. } else if ( point.y > this.max.y ) {
  1858. this.max.y = point.y;
  1859. }
  1860. if ( point.z < this.min.z ) {
  1861. this.min.z = point.z;
  1862. } else if ( point.z > this.max.z ) {
  1863. this.max.z = point.z;
  1864. }
  1865. }
  1866. } else {
  1867. this.makeEmpty();
  1868. }
  1869. return this;
  1870. },
  1871. setFromCenterAndSize: function() {
  1872. var v1 = new THREE.Vector3();
  1873. return function ( center, size ) {
  1874. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1875. this.min.copy( center ).sub( halfSize );
  1876. this.max.copy( center ).add( halfSize );
  1877. return this;
  1878. };
  1879. }(),
  1880. copy: function ( box ) {
  1881. this.min.copy( box.min );
  1882. this.max.copy( box.max );
  1883. return this;
  1884. },
  1885. makeEmpty: function () {
  1886. this.min.x = this.min.y = this.min.z = Infinity;
  1887. this.max.x = this.max.y = this.max.z = -Infinity;
  1888. return this;
  1889. },
  1890. empty: function () {
  1891. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1892. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1893. },
  1894. center: function ( optionalTarget ) {
  1895. var result = optionalTarget || new THREE.Vector3();
  1896. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1897. },
  1898. size: function ( optionalTarget ) {
  1899. var result = optionalTarget || new THREE.Vector3();
  1900. return result.subVectors( this.max, this.min );
  1901. },
  1902. expandByPoint: function ( point ) {
  1903. this.min.min( point );
  1904. this.max.max( point );
  1905. return this;
  1906. },
  1907. expandByVector: function ( vector ) {
  1908. this.min.sub( vector );
  1909. this.max.add( vector );
  1910. return this;
  1911. },
  1912. expandByScalar: function ( scalar ) {
  1913. this.min.addScalar( -scalar );
  1914. this.max.addScalar( scalar );
  1915. return this;
  1916. },
  1917. containsPoint: function ( point ) {
  1918. if ( point.x < this.min.x || point.x > this.max.x ||
  1919. point.y < this.min.y || point.y > this.max.y ||
  1920. point.z < this.min.z || point.z > this.max.z ) {
  1921. return false;
  1922. }
  1923. return true;
  1924. },
  1925. containsBox: function ( box ) {
  1926. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1927. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1928. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1929. return true;
  1930. }
  1931. return false;
  1932. },
  1933. getParameter: function ( point ) {
  1934. // This can potentially have a divide by zero if the box
  1935. // has a size dimension of 0.
  1936. return new THREE.Vector3(
  1937. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1938. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1939. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1940. );
  1941. },
  1942. isIntersectionBox: function ( box ) {
  1943. // using 6 splitting planes to rule out intersections.
  1944. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1945. box.max.y < this.min.y || box.min.y > this.max.y ||
  1946. box.max.z < this.min.z || box.min.z > this.max.z ) {
  1947. return false;
  1948. }
  1949. return true;
  1950. },
  1951. clampPoint: function ( point, optionalTarget ) {
  1952. var result = optionalTarget || new THREE.Vector3();
  1953. return result.copy( point ).clamp( this.min, this.max );
  1954. },
  1955. distanceToPoint: function() {
  1956. var v1 = new THREE.Vector3();
  1957. return function ( point ) {
  1958. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1959. return clampedPoint.sub( point ).length();
  1960. };
  1961. }(),
  1962. getBoundingSphere: function() {
  1963. var v1 = new THREE.Vector3();
  1964. return function ( optionalTarget ) {
  1965. var result = optionalTarget || new THREE.Sphere();
  1966. result.center = this.center();
  1967. result.radius = this.size( v1 ).length() * 0.5;
  1968. return result;
  1969. };
  1970. }(),
  1971. intersect: function ( box ) {
  1972. this.min.max( box.min );
  1973. this.max.min( box.max );
  1974. return this;
  1975. },
  1976. union: function ( box ) {
  1977. this.min.min( box.min );
  1978. this.max.max( box.max );
  1979. return this;
  1980. },
  1981. applyMatrix4: function() {
  1982. var points = [
  1983. new THREE.Vector3(),
  1984. new THREE.Vector3(),
  1985. new THREE.Vector3(),
  1986. new THREE.Vector3(),
  1987. new THREE.Vector3(),
  1988. new THREE.Vector3(),
  1989. new THREE.Vector3(),
  1990. new THREE.Vector3()
  1991. ];
  1992. return function ( matrix ) {
  1993. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1994. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  1995. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  1996. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  1997. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  1998. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  1999. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2000. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2001. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2002. this.makeEmpty();
  2003. this.setFromPoints( points );
  2004. return this;
  2005. };
  2006. }(),
  2007. translate: function ( offset ) {
  2008. this.min.add( offset );
  2009. this.max.add( offset );
  2010. return this;
  2011. },
  2012. equals: function ( box ) {
  2013. return box.min.equals( this.min ) && box.max.equals( this.max );
  2014. },
  2015. clone: function () {
  2016. return new THREE.Box3().copy( this );
  2017. }
  2018. };
  2019. /**
  2020. * @author alteredq / http://alteredqualia.com/
  2021. * @author WestLangley / http://github.com/WestLangley
  2022. * @author bhouston / http://exocortex.com
  2023. */
  2024. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2025. this.elements = new Float32Array(9);
  2026. this.set(
  2027. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2028. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2029. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2030. );
  2031. };
  2032. THREE.Matrix3.prototype = {
  2033. constructor: THREE.Matrix3,
  2034. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2035. var te = this.elements;
  2036. te[0] = n11; te[3] = n12; te[6] = n13;
  2037. te[1] = n21; te[4] = n22; te[7] = n23;
  2038. te[2] = n31; te[5] = n32; te[8] = n33;
  2039. return this;
  2040. },
  2041. identity: function () {
  2042. this.set(
  2043. 1, 0, 0,
  2044. 0, 1, 0,
  2045. 0, 0, 1
  2046. );
  2047. return this;
  2048. },
  2049. copy: function ( m ) {
  2050. var me = m.elements;
  2051. this.set(
  2052. me[0], me[3], me[6],
  2053. me[1], me[4], me[7],
  2054. me[2], me[5], me[8]
  2055. );
  2056. return this;
  2057. },
  2058. multiplyVector3: function ( vector ) {
  2059. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2060. return vector.applyMatrix3( this );
  2061. },
  2062. multiplyVector3Array: function() {
  2063. var v1 = new THREE.Vector3();
  2064. return function ( a ) {
  2065. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2066. v1.x = a[ i ];
  2067. v1.y = a[ i + 1 ];
  2068. v1.z = a[ i + 2 ];
  2069. v1.applyMatrix3(this);
  2070. a[ i ] = v1.x;
  2071. a[ i + 1 ] = v1.y;
  2072. a[ i + 2 ] = v1.z;
  2073. }
  2074. return a;
  2075. };
  2076. }(),
  2077. multiplyScalar: function ( s ) {
  2078. var te = this.elements;
  2079. te[0] *= s; te[3] *= s; te[6] *= s;
  2080. te[1] *= s; te[4] *= s; te[7] *= s;
  2081. te[2] *= s; te[5] *= s; te[8] *= s;
  2082. return this;
  2083. },
  2084. determinant: function () {
  2085. var te = this.elements;
  2086. var a = te[0], b = te[1], c = te[2],
  2087. d = te[3], e = te[4], f = te[5],
  2088. g = te[6], h = te[7], i = te[8];
  2089. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2090. },
  2091. getInverse: function ( matrix, throwOnInvertible ) {
  2092. // input: THREE.Matrix4
  2093. // ( based on http://code.google.com/p/webgl-mjs/ )
  2094. var me = matrix.elements;
  2095. var te = this.elements;
  2096. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2097. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2098. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2099. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2100. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2101. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2102. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2103. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2104. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2105. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2106. // no inverse
  2107. if ( det === 0 ) {
  2108. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2109. if ( throwOnInvertible || false ) {
  2110. throw new Error( msg );
  2111. } else {
  2112. console.warn( msg );
  2113. }
  2114. this.identity();
  2115. return this;
  2116. }
  2117. this.multiplyScalar( 1.0 / det );
  2118. return this;
  2119. },
  2120. transpose: function () {
  2121. var tmp, m = this.elements;
  2122. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2123. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2124. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2125. return this;
  2126. },
  2127. getNormalMatrix: function ( m ) {
  2128. // input: THREE.Matrix4
  2129. this.getInverse( m ).transpose();
  2130. return this;
  2131. },
  2132. transposeIntoArray: function ( r ) {
  2133. var m = this.elements;
  2134. r[ 0 ] = m[ 0 ];
  2135. r[ 1 ] = m[ 3 ];
  2136. r[ 2 ] = m[ 6 ];
  2137. r[ 3 ] = m[ 1 ];
  2138. r[ 4 ] = m[ 4 ];
  2139. r[ 5 ] = m[ 7 ];
  2140. r[ 6 ] = m[ 2 ];
  2141. r[ 7 ] = m[ 5 ];
  2142. r[ 8 ] = m[ 8 ];
  2143. return this;
  2144. },
  2145. clone: function () {
  2146. var te = this.elements;
  2147. return new THREE.Matrix3(
  2148. te[0], te[3], te[6],
  2149. te[1], te[4], te[7],
  2150. te[2], te[5], te[8]
  2151. );
  2152. }
  2153. };
  2154. /**
  2155. * @author mrdoob / http://mrdoob.com/
  2156. * @author supereggbert / http://www.paulbrunt.co.uk/
  2157. * @author philogb / http://blog.thejit.org/
  2158. * @author jordi_ros / http://plattsoft.com
  2159. * @author D1plo1d / http://github.com/D1plo1d
  2160. * @author alteredq / http://alteredqualia.com/
  2161. * @author mikael emtinger / http://gomo.se/
  2162. * @author timknip / http://www.floorplanner.com/
  2163. * @author bhouston / http://exocortex.com
  2164. * @author WestLangley / http://github.com/WestLangley
  2165. */
  2166. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2167. var te = this.elements = new Float32Array( 16 );
  2168. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2169. // we should not support semi specification of Matrix4, it is just weird.
  2170. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2171. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2172. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2173. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2174. };
  2175. THREE.Matrix4.prototype = {
  2176. constructor: THREE.Matrix4,
  2177. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2178. var te = this.elements;
  2179. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2180. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2181. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2182. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2183. return this;
  2184. },
  2185. identity: function () {
  2186. this.set(
  2187. 1, 0, 0, 0,
  2188. 0, 1, 0, 0,
  2189. 0, 0, 1, 0,
  2190. 0, 0, 0, 1
  2191. );
  2192. return this;
  2193. },
  2194. copy: function ( m ) {
  2195. var me = m.elements;
  2196. this.set(
  2197. me[0], me[4], me[8], me[12],
  2198. me[1], me[5], me[9], me[13],
  2199. me[2], me[6], me[10], me[14],
  2200. me[3], me[7], me[11], me[15]
  2201. );
  2202. return this;
  2203. },
  2204. extractPosition: function ( m ) {
  2205. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2206. return this.copyPosition( m );
  2207. },
  2208. copyPosition: function ( m ) {
  2209. var te = this.elements;
  2210. var me = m.elements;
  2211. te[12] = me[12];
  2212. te[13] = me[13];
  2213. te[14] = me[14];
  2214. return this;
  2215. },
  2216. extractRotation: function () {
  2217. var v1 = new THREE.Vector3();
  2218. return function ( m ) {
  2219. var te = this.elements;
  2220. var me = m.elements;
  2221. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2222. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2223. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2224. te[0] = me[0] * scaleX;
  2225. te[1] = me[1] * scaleX;
  2226. te[2] = me[2] * scaleX;
  2227. te[4] = me[4] * scaleY;
  2228. te[5] = me[5] * scaleY;
  2229. te[6] = me[6] * scaleY;
  2230. te[8] = me[8] * scaleZ;
  2231. te[9] = me[9] * scaleZ;
  2232. te[10] = me[10] * scaleZ;
  2233. return this;
  2234. };
  2235. }(),
  2236. setRotationFromEuler: function ( v, order ) {
  2237. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromEuler() has been deprecated in favor of makeRotationFromEuler. Please update your code.' );
  2238. return this.makeRotationFromEuler( v, order );
  2239. },
  2240. makeRotationFromEuler: function ( v, order ) {
  2241. var te = this.elements;
  2242. var x = v.x, y = v.y, z = v.z;
  2243. var a = Math.cos( x ), b = Math.sin( x );
  2244. var c = Math.cos( y ), d = Math.sin( y );
  2245. var e = Math.cos( z ), f = Math.sin( z );
  2246. if ( order === undefined || order === 'XYZ' ) {
  2247. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2248. te[0] = c * e;
  2249. te[4] = - c * f;
  2250. te[8] = d;
  2251. te[1] = af + be * d;
  2252. te[5] = ae - bf * d;
  2253. te[9] = - b * c;
  2254. te[2] = bf - ae * d;
  2255. te[6] = be + af * d;
  2256. te[10] = a * c;
  2257. } else if ( order === 'YXZ' ) {
  2258. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2259. te[0] = ce + df * b;
  2260. te[4] = de * b - cf;
  2261. te[8] = a * d;
  2262. te[1] = a * f;
  2263. te[5] = a * e;
  2264. te[9] = - b;
  2265. te[2] = cf * b - de;
  2266. te[6] = df + ce * b;
  2267. te[10] = a * c;
  2268. } else if ( order === 'ZXY' ) {
  2269. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2270. te[0] = ce - df * b;
  2271. te[4] = - a * f;
  2272. te[8] = de + cf * b;
  2273. te[1] = cf + de * b;
  2274. te[5] = a * e;
  2275. te[9] = df - ce * b;
  2276. te[2] = - a * d;
  2277. te[6] = b;
  2278. te[10] = a * c;
  2279. } else if ( order === 'ZYX' ) {
  2280. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2281. te[0] = c * e;
  2282. te[4] = be * d - af;
  2283. te[8] = ae * d + bf;
  2284. te[1] = c * f;
  2285. te[5] = bf * d + ae;
  2286. te[9] = af * d - be;
  2287. te[2] = - d;
  2288. te[6] = b * c;
  2289. te[10] = a * c;
  2290. } else if ( order === 'YZX' ) {
  2291. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2292. te[0] = c * e;
  2293. te[4] = bd - ac * f;
  2294. te[8] = bc * f + ad;
  2295. te[1] = f;
  2296. te[5] = a * e;
  2297. te[9] = - b * e;
  2298. te[2] = - d * e;
  2299. te[6] = ad * f + bc;
  2300. te[10] = ac - bd * f;
  2301. } else if ( order === 'XZY' ) {
  2302. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2303. te[0] = c * e;
  2304. te[4] = - f;
  2305. te[8] = d * e;
  2306. te[1] = ac * f + bd;
  2307. te[5] = a * e;
  2308. te[9] = ad * f - bc;
  2309. te[2] = bc * f - ad;
  2310. te[6] = b * e;
  2311. te[10] = bd * f + ac;
  2312. }
  2313. // last column
  2314. te[3] = 0;
  2315. te[7] = 0;
  2316. te[11] = 0;
  2317. // bottom row
  2318. te[12] = 0;
  2319. te[13] = 0;
  2320. te[14] = 0;
  2321. te[15] = 1;
  2322. return this;
  2323. },
  2324. setRotationFromQuaternion: function ( q ) {
  2325. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2326. return this.makeRotationFromQuaternion( q );
  2327. },
  2328. makeRotationFromQuaternion: function ( q ) {
  2329. var te = this.elements;
  2330. var x = q.x, y = q.y, z = q.z, w = q.w;
  2331. var x2 = x + x, y2 = y + y, z2 = z + z;
  2332. var xx = x * x2, xy = x * y2, xz = x * z2;
  2333. var yy = y * y2, yz = y * z2, zz = z * z2;
  2334. var wx = w * x2, wy = w * y2, wz = w * z2;
  2335. te[0] = 1 - ( yy + zz );
  2336. te[4] = xy - wz;
  2337. te[8] = xz + wy;
  2338. te[1] = xy + wz;
  2339. te[5] = 1 - ( xx + zz );
  2340. te[9] = yz - wx;
  2341. te[2] = xz - wy;
  2342. te[6] = yz + wx;
  2343. te[10] = 1 - ( xx + yy );
  2344. // last column
  2345. te[3] = 0;
  2346. te[7] = 0;
  2347. te[11] = 0;
  2348. // bottom row
  2349. te[12] = 0;
  2350. te[13] = 0;
  2351. te[14] = 0;
  2352. te[15] = 1;
  2353. return this;
  2354. },
  2355. lookAt: function() {
  2356. var x = new THREE.Vector3();
  2357. var y = new THREE.Vector3();
  2358. var z = new THREE.Vector3();
  2359. return function ( eye, target, up ) {
  2360. var te = this.elements;
  2361. z.subVectors( eye, target ).normalize();
  2362. if ( z.length() === 0 ) {
  2363. z.z = 1;
  2364. }
  2365. x.crossVectors( up, z ).normalize();
  2366. if ( x.length() === 0 ) {
  2367. z.x += 0.0001;
  2368. x.crossVectors( up, z ).normalize();
  2369. }
  2370. y.crossVectors( z, x );
  2371. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2372. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2373. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2374. return this;
  2375. };
  2376. }(),
  2377. multiply: function ( m, n ) {
  2378. if ( n !== undefined ) {
  2379. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2380. return this.multiplyMatrices( m, n );
  2381. }
  2382. return this.multiplyMatrices( this, m );
  2383. },
  2384. multiplyMatrices: function ( a, b ) {
  2385. var ae = a.elements;
  2386. var be = b.elements;
  2387. var te = this.elements;
  2388. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2389. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2390. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2391. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2392. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2393. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2394. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2395. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2396. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2397. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2398. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2399. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2400. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2401. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2402. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2403. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2404. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2405. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2406. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2407. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2408. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2409. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2410. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2411. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2412. return this;
  2413. },
  2414. multiplyToArray: function ( a, b, r ) {
  2415. var te = this.elements;
  2416. this.multiplyMatrices( a, b );
  2417. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2418. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2419. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2420. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2421. return this;
  2422. },
  2423. multiplyScalar: function ( s ) {
  2424. var te = this.elements;
  2425. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2426. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2427. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2428. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2429. return this;
  2430. },
  2431. multiplyVector3: function ( vector ) {
  2432. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2433. return vector.applyProjection( this );
  2434. },
  2435. multiplyVector4: function ( vector ) {
  2436. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2437. return vector.applyMatrix4( this );
  2438. },
  2439. multiplyVector3Array: function() {
  2440. var v1 = new THREE.Vector3();
  2441. return function ( a ) {
  2442. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2443. v1.x = a[ i ];
  2444. v1.y = a[ i + 1 ];
  2445. v1.z = a[ i + 2 ];
  2446. v1.applyProjection( this );
  2447. a[ i ] = v1.x;
  2448. a[ i + 1 ] = v1.y;
  2449. a[ i + 2 ] = v1.z;
  2450. }
  2451. return a;
  2452. };
  2453. }(),
  2454. rotateAxis: function ( v ) {
  2455. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2456. v.transformDirection( this );
  2457. },
  2458. crossVector: function ( vector ) {
  2459. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2460. return vector.applyMatrix4( this );
  2461. },
  2462. determinant: function () {
  2463. var te = this.elements;
  2464. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2465. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2466. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2467. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2468. //TODO: make this more efficient
  2469. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2470. return (
  2471. n41 * (
  2472. +n14 * n23 * n32
  2473. -n13 * n24 * n32
  2474. -n14 * n22 * n33
  2475. +n12 * n24 * n33
  2476. +n13 * n22 * n34
  2477. -n12 * n23 * n34
  2478. ) +
  2479. n42 * (
  2480. +n11 * n23 * n34
  2481. -n11 * n24 * n33
  2482. +n14 * n21 * n33
  2483. -n13 * n21 * n34
  2484. +n13 * n24 * n31
  2485. -n14 * n23 * n31
  2486. ) +
  2487. n43 * (
  2488. +n11 * n24 * n32
  2489. -n11 * n22 * n34
  2490. -n14 * n21 * n32
  2491. +n12 * n21 * n34
  2492. +n14 * n22 * n31
  2493. -n12 * n24 * n31
  2494. ) +
  2495. n44 * (
  2496. -n13 * n22 * n31
  2497. -n11 * n23 * n32
  2498. +n11 * n22 * n33
  2499. +n13 * n21 * n32
  2500. -n12 * n21 * n33
  2501. +n12 * n23 * n31
  2502. )
  2503. );
  2504. },
  2505. transpose: function () {
  2506. var te = this.elements;
  2507. var tmp;
  2508. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2509. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2510. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2511. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2512. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2513. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2514. return this;
  2515. },
  2516. flattenToArray: function ( flat ) {
  2517. var te = this.elements;
  2518. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2519. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2520. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2521. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2522. return flat;
  2523. },
  2524. flattenToArrayOffset: function( flat, offset ) {
  2525. var te = this.elements;
  2526. flat[ offset ] = te[0];
  2527. flat[ offset + 1 ] = te[1];
  2528. flat[ offset + 2 ] = te[2];
  2529. flat[ offset + 3 ] = te[3];
  2530. flat[ offset + 4 ] = te[4];
  2531. flat[ offset + 5 ] = te[5];
  2532. flat[ offset + 6 ] = te[6];
  2533. flat[ offset + 7 ] = te[7];
  2534. flat[ offset + 8 ] = te[8];
  2535. flat[ offset + 9 ] = te[9];
  2536. flat[ offset + 10 ] = te[10];
  2537. flat[ offset + 11 ] = te[11];
  2538. flat[ offset + 12 ] = te[12];
  2539. flat[ offset + 13 ] = te[13];
  2540. flat[ offset + 14 ] = te[14];
  2541. flat[ offset + 15 ] = te[15];
  2542. return flat;
  2543. },
  2544. getPosition: function() {
  2545. var v1 = new THREE.Vector3();
  2546. return function () {
  2547. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2548. var te = this.elements;
  2549. return v1.set( te[12], te[13], te[14] );
  2550. };
  2551. }(),
  2552. setPosition: function ( v ) {
  2553. var te = this.elements;
  2554. te[12] = v.x;
  2555. te[13] = v.y;
  2556. te[14] = v.z;
  2557. return this;
  2558. },
  2559. getInverse: function ( m, throwOnInvertible ) {
  2560. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2561. var te = this.elements;
  2562. var me = m.elements;
  2563. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2564. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2565. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2566. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2567. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2568. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2569. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2570. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2571. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2572. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2573. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2574. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2575. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2576. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2577. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2578. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2579. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2580. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2581. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2582. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2583. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 4 ] + me[ 2 ] * te[ 8 ] + me[ 3 ] * te[ 12 ];
  2584. if ( det == 0 ) {
  2585. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2586. if ( throwOnInvertible || false ) {
  2587. throw new Error( msg );
  2588. } else {
  2589. console.warn( msg );
  2590. }
  2591. this.identity();
  2592. return this;
  2593. }
  2594. this.multiplyScalar( 1 / det );
  2595. return this;
  2596. },
  2597. translate: function ( v ) {
  2598. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2599. },
  2600. rotateX: function ( angle ) {
  2601. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2602. },
  2603. rotateY: function ( angle ) {
  2604. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2605. },
  2606. rotateZ: function ( angle ) {
  2607. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2608. },
  2609. rotateByAxis: function ( axis, angle ) {
  2610. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2611. },
  2612. scale: function ( v ) {
  2613. var te = this.elements;
  2614. var x = v.x, y = v.y, z = v.z;
  2615. te[0] *= x; te[4] *= y; te[8] *= z;
  2616. te[1] *= x; te[5] *= y; te[9] *= z;
  2617. te[2] *= x; te[6] *= y; te[10] *= z;
  2618. te[3] *= x; te[7] *= y; te[11] *= z;
  2619. return this;
  2620. },
  2621. getMaxScaleOnAxis: function () {
  2622. var te = this.elements;
  2623. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2624. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2625. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2626. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2627. },
  2628. makeTranslation: function ( x, y, z ) {
  2629. this.set(
  2630. 1, 0, 0, x,
  2631. 0, 1, 0, y,
  2632. 0, 0, 1, z,
  2633. 0, 0, 0, 1
  2634. );
  2635. return this;
  2636. },
  2637. makeRotationX: function ( theta ) {
  2638. var c = Math.cos( theta ), s = Math.sin( theta );
  2639. this.set(
  2640. 1, 0, 0, 0,
  2641. 0, c, -s, 0,
  2642. 0, s, c, 0,
  2643. 0, 0, 0, 1
  2644. );
  2645. return this;
  2646. },
  2647. makeRotationY: function ( theta ) {
  2648. var c = Math.cos( theta ), s = Math.sin( theta );
  2649. this.set(
  2650. c, 0, s, 0,
  2651. 0, 1, 0, 0,
  2652. -s, 0, c, 0,
  2653. 0, 0, 0, 1
  2654. );
  2655. return this;
  2656. },
  2657. makeRotationZ: function ( theta ) {
  2658. var c = Math.cos( theta ), s = Math.sin( theta );
  2659. this.set(
  2660. c, -s, 0, 0,
  2661. s, c, 0, 0,
  2662. 0, 0, 1, 0,
  2663. 0, 0, 0, 1
  2664. );
  2665. return this;
  2666. },
  2667. makeRotationAxis: function ( axis, angle ) {
  2668. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2669. var c = Math.cos( angle );
  2670. var s = Math.sin( angle );
  2671. var t = 1 - c;
  2672. var x = axis.x, y = axis.y, z = axis.z;
  2673. var tx = t * x, ty = t * y;
  2674. this.set(
  2675. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2676. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2677. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2678. 0, 0, 0, 1
  2679. );
  2680. return this;
  2681. },
  2682. makeScale: function ( x, y, z ) {
  2683. this.set(
  2684. x, 0, 0, 0,
  2685. 0, y, 0, 0,
  2686. 0, 0, z, 0,
  2687. 0, 0, 0, 1
  2688. );
  2689. return this;
  2690. },
  2691. compose: function ( position, quaternion, scale ) {
  2692. console.warn( 'DEPRECATED: Matrix4\'s .compose() has been deprecated in favor of makeFromPositionQuaternionScale. Please update your code.' );
  2693. return this.makeFromPositionQuaternionScale( position, quaternion, scale );
  2694. },
  2695. makeFromPositionQuaternionScale: function ( position, quaternion, scale ) {
  2696. this.makeRotationFromQuaternion( quaternion );
  2697. this.scale( scale );
  2698. this.setPosition( position );
  2699. return this;
  2700. },
  2701. makeFromPositionEulerScale: function ( position, rotation, eulerOrder, scale ) {
  2702. this.makeRotationFromEuler( rotation, eulerOrder );
  2703. this.scale( scale );
  2704. this.setPosition( position );
  2705. return this;
  2706. },
  2707. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2708. var te = this.elements;
  2709. var x = 2 * near / ( right - left );
  2710. var y = 2 * near / ( top - bottom );
  2711. var a = ( right + left ) / ( right - left );
  2712. var b = ( top + bottom ) / ( top - bottom );
  2713. var c = - ( far + near ) / ( far - near );
  2714. var d = - 2 * far * near / ( far - near );
  2715. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2716. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2717. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2718. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2719. return this;
  2720. },
  2721. makePerspective: function ( fov, aspect, near, far ) {
  2722. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2723. var ymin = - ymax;
  2724. var xmin = ymin * aspect;
  2725. var xmax = ymax * aspect;
  2726. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2727. },
  2728. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2729. var te = this.elements;
  2730. var w = right - left;
  2731. var h = top - bottom;
  2732. var p = far - near;
  2733. var x = ( right + left ) / w;
  2734. var y = ( top + bottom ) / h;
  2735. var z = ( far + near ) / p;
  2736. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2737. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2738. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2739. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2740. return this;
  2741. },
  2742. clone: function () {
  2743. var te = this.elements;
  2744. return new THREE.Matrix4(
  2745. te[0], te[4], te[8], te[12],
  2746. te[1], te[5], te[9], te[13],
  2747. te[2], te[6], te[10], te[14],
  2748. te[3], te[7], te[11], te[15]
  2749. );
  2750. }
  2751. };
  2752. THREE.extend( THREE.Matrix4.prototype, {
  2753. decompose: function() {
  2754. var x = new THREE.Vector3();
  2755. var y = new THREE.Vector3();
  2756. var z = new THREE.Vector3();
  2757. var matrix = new THREE.Matrix4();
  2758. return function ( position, quaternion, scale ) {
  2759. var te = this.elements;
  2760. // grab the axis vectors
  2761. x.set( te[0], te[1], te[2] );
  2762. y.set( te[4], te[5], te[6] );
  2763. z.set( te[8], te[9], te[10] );
  2764. position = ( position instanceof THREE.Vector3 ) ? position : new THREE.Vector3();
  2765. quaternion = ( quaternion instanceof THREE.Quaternion ) ? quaternion : new THREE.Quaternion();
  2766. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2767. scale.x = x.length();
  2768. scale.y = y.length();
  2769. scale.z = z.length();
  2770. position.x = te[12];
  2771. position.y = te[13];
  2772. position.z = te[14];
  2773. // scale the rotation part
  2774. matrix.copy( this );
  2775. matrix.elements[0] /= scale.x;
  2776. matrix.elements[1] /= scale.x;
  2777. matrix.elements[2] /= scale.x;
  2778. matrix.elements[4] /= scale.y;
  2779. matrix.elements[5] /= scale.y;
  2780. matrix.elements[6] /= scale.y;
  2781. matrix.elements[8] /= scale.z;
  2782. matrix.elements[9] /= scale.z;
  2783. matrix.elements[10] /= scale.z;
  2784. quaternion.setFromRotationMatrix( matrix );
  2785. return [ position, quaternion, scale ];
  2786. };
  2787. }()
  2788. } );
  2789. /**
  2790. * @author bhouston / http://exocortex.com
  2791. */
  2792. THREE.Ray = function ( origin, direction ) {
  2793. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2794. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2795. };
  2796. THREE.Ray.prototype = {
  2797. constructor: THREE.Ray,
  2798. set: function ( origin, direction ) {
  2799. this.origin.copy( origin );
  2800. this.direction.copy( direction );
  2801. return this;
  2802. },
  2803. copy: function ( ray ) {
  2804. this.origin.copy( ray.origin );
  2805. this.direction.copy( ray.direction );
  2806. return this;
  2807. },
  2808. at: function( t, optionalTarget ) {
  2809. var result = optionalTarget || new THREE.Vector3();
  2810. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2811. },
  2812. recast: function() {
  2813. var v1 = new THREE.Vector3();
  2814. return function ( t ) {
  2815. this.origin.copy( this.at( t, v1 ) );
  2816. return this;
  2817. };
  2818. }(),
  2819. closestPointToPoint: function ( point, optionalTarget ) {
  2820. var result = optionalTarget || new THREE.Vector3();
  2821. result.subVectors( point, this.origin );
  2822. var directionDistance = result.dot( this.direction );
  2823. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2824. },
  2825. distanceToPoint: function() {
  2826. var v1 = new THREE.Vector3();
  2827. return function ( point ) {
  2828. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  2829. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2830. return v1.distanceTo( point );
  2831. };
  2832. }(),
  2833. isIntersectionSphere: function( sphere ) {
  2834. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2835. },
  2836. isIntersectionPlane: function ( plane ) {
  2837. // check if the line and plane are non-perpendicular, if they
  2838. // eventually they will intersect.
  2839. var denominator = plane.normal.dot( this.direction );
  2840. if ( denominator != 0 ) {
  2841. return true;
  2842. }
  2843. // line is coplanar, return origin
  2844. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2845. return true;
  2846. }
  2847. return false;
  2848. },
  2849. distanceToPlane: function ( plane ) {
  2850. var denominator = plane.normal.dot( this.direction );
  2851. if ( denominator == 0 ) {
  2852. // line is coplanar, return origin
  2853. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2854. return 0;
  2855. }
  2856. // Unsure if this is the correct method to handle this case.
  2857. return undefined;
  2858. }
  2859. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2860. return t;
  2861. },
  2862. intersectPlane: function ( plane, optionalTarget ) {
  2863. var t = this.distanceToPlane( plane );
  2864. if ( t === undefined ) {
  2865. return undefined;
  2866. }
  2867. return this.at( t, optionalTarget );
  2868. },
  2869. applyMatrix4: function ( matrix4 ) {
  2870. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2871. this.origin.applyMatrix4( matrix4 );
  2872. this.direction.sub( this.origin );
  2873. return this;
  2874. },
  2875. equals: function ( ray ) {
  2876. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2877. },
  2878. clone: function () {
  2879. return new THREE.Ray().copy( this );
  2880. }
  2881. };
  2882. /**
  2883. * @author bhouston / http://exocortex.com
  2884. * @author mrdoob / http://mrdoob.com/
  2885. */
  2886. THREE.Sphere = function ( center, radius ) {
  2887. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  2888. this.radius = ( radius !== undefined ) ? radius : 0;
  2889. };
  2890. THREE.Sphere.prototype = {
  2891. constructor: THREE.Sphere,
  2892. set: function ( center, radius ) {
  2893. this.center.copy( center );
  2894. this.radius = radius;
  2895. return this;
  2896. },
  2897. setFromCenterAndPoints: function ( center, points ) {
  2898. var maxRadiusSq = 0;
  2899. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2900. var radiusSq = center.distanceToSquared( points[ i ] );
  2901. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2902. }
  2903. this.center = center;
  2904. this.radius = Math.sqrt( maxRadiusSq );
  2905. return this;
  2906. },
  2907. copy: function ( sphere ) {
  2908. this.center.copy( sphere.center );
  2909. this.radius = sphere.radius;
  2910. return this;
  2911. },
  2912. empty: function () {
  2913. return ( this.radius <= 0 );
  2914. },
  2915. containsPoint: function ( point ) {
  2916. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2917. },
  2918. distanceToPoint: function ( point ) {
  2919. return ( point.distanceTo( this.center ) - this.radius );
  2920. },
  2921. intersectsSphere: function ( sphere ) {
  2922. var radiusSum = this.radius + sphere.radius;
  2923. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2924. },
  2925. clampPoint: function ( point, optionalTarget ) {
  2926. var deltaLengthSq = this.center.distanceToSquared( point );
  2927. var result = optionalTarget || new THREE.Vector3();
  2928. result.copy( point );
  2929. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2930. result.sub( this.center ).normalize();
  2931. result.multiplyScalar( this.radius ).add( this.center );
  2932. }
  2933. return result;
  2934. },
  2935. getBoundingBox: function ( optionalTarget ) {
  2936. var box = optionalTarget || new THREE.Box3();
  2937. box.set( this.center, this.center );
  2938. box.expandByScalar( this.radius );
  2939. return box;
  2940. },
  2941. applyMatrix4: function ( matrix ) {
  2942. this.center.applyMatrix4( matrix );
  2943. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2944. return this;
  2945. },
  2946. translate: function ( offset ) {
  2947. this.center.add( offset );
  2948. return this;
  2949. },
  2950. equals: function ( sphere ) {
  2951. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2952. },
  2953. clone: function () {
  2954. return new THREE.Sphere().copy( this );
  2955. }
  2956. };
  2957. /**
  2958. * @author mrdoob / http://mrdoob.com/
  2959. * @author alteredq / http://alteredqualia.com/
  2960. * @author bhouston / http://exocortex.com
  2961. */
  2962. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  2963. this.planes = [
  2964. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  2965. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  2966. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  2967. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  2968. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  2969. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  2970. ];
  2971. };
  2972. THREE.Frustum.prototype = {
  2973. constructor: THREE.Frustum,
  2974. set: function ( p0, p1, p2, p3, p4, p5 ) {
  2975. var planes = this.planes;
  2976. planes[0].copy( p0 );
  2977. planes[1].copy( p1 );
  2978. planes[2].copy( p2 );
  2979. planes[3].copy( p3 );
  2980. planes[4].copy( p4 );
  2981. planes[5].copy( p5 );
  2982. return this;
  2983. },
  2984. copy: function ( frustum ) {
  2985. var planes = this.planes;
  2986. for( var i = 0; i < 6; i ++ ) {
  2987. planes[i].copy( frustum.planes[i] );
  2988. }
  2989. return this;
  2990. },
  2991. setFromMatrix: function ( m ) {
  2992. var planes = this.planes;
  2993. var me = m.elements;
  2994. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2995. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2996. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2997. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2998. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  2999. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3000. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3001. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3002. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3003. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3004. return this;
  3005. },
  3006. intersectsObject: function () {
  3007. var center = new THREE.Vector3();
  3008. return function ( object ) {
  3009. // this method is expanded inlined for performance reasons.
  3010. var matrix = object.matrixWorld;
  3011. var planes = this.planes;
  3012. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  3013. center.getPositionFromMatrix( matrix );
  3014. for ( var i = 0; i < 6; i ++ ) {
  3015. var distance = planes[ i ].distanceToPoint( center );
  3016. if ( distance < negRadius ) {
  3017. return false;
  3018. }
  3019. }
  3020. return true;
  3021. };
  3022. }(),
  3023. intersectsSphere: function ( sphere ) {
  3024. var planes = this.planes;
  3025. var center = sphere.center;
  3026. var negRadius = -sphere.radius;
  3027. for ( var i = 0; i < 6; i ++ ) {
  3028. var distance = planes[ i ].distanceToPoint( center );
  3029. if ( distance < negRadius ) {
  3030. return false;
  3031. }
  3032. }
  3033. return true;
  3034. },
  3035. containsPoint: function ( point ) {
  3036. var planes = this.planes;
  3037. for ( var i = 0; i < 6; i ++ ) {
  3038. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3039. return false;
  3040. }
  3041. }
  3042. return true;
  3043. },
  3044. clone: function () {
  3045. return new THREE.Frustum().copy( this );
  3046. }
  3047. };
  3048. /**
  3049. * @author bhouston / http://exocortex.com
  3050. */
  3051. THREE.Plane = function ( normal, constant ) {
  3052. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3053. this.constant = ( constant !== undefined ) ? constant : 0;
  3054. };
  3055. THREE.Plane.prototype = {
  3056. constructor: THREE.Plane,
  3057. set: function ( normal, constant ) {
  3058. this.normal.copy( normal );
  3059. this.constant = constant;
  3060. return this;
  3061. },
  3062. setComponents: function ( x, y, z, w ) {
  3063. this.normal.set( x, y, z );
  3064. this.constant = w;
  3065. return this;
  3066. },
  3067. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3068. this.normal.copy( normal );
  3069. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3070. return this;
  3071. },
  3072. setFromCoplanarPoints: function() {
  3073. var v1 = new THREE.Vector3();
  3074. var v2 = new THREE.Vector3();
  3075. return function ( a, b, c ) {
  3076. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3077. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3078. this.setFromNormalAndCoplanarPoint( normal, a );
  3079. return this;
  3080. };
  3081. }(),
  3082. copy: function ( plane ) {
  3083. this.normal.copy( plane.normal );
  3084. this.constant = plane.constant;
  3085. return this;
  3086. },
  3087. normalize: function () {
  3088. // Note: will lead to a divide by zero if the plane is invalid.
  3089. var inverseNormalLength = 1.0 / this.normal.length();
  3090. this.normal.multiplyScalar( inverseNormalLength );
  3091. this.constant *= inverseNormalLength;
  3092. return this;
  3093. },
  3094. negate: function () {
  3095. this.constant *= -1;
  3096. this.normal.negate();
  3097. return this;
  3098. },
  3099. distanceToPoint: function ( point ) {
  3100. return this.normal.dot( point ) + this.constant;
  3101. },
  3102. distanceToSphere: function ( sphere ) {
  3103. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3104. },
  3105. projectPoint: function ( point, optionalTarget ) {
  3106. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3107. },
  3108. orthoPoint: function ( point, optionalTarget ) {
  3109. var perpendicularMagnitude = this.distanceToPoint( point );
  3110. var result = optionalTarget || new THREE.Vector3();
  3111. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3112. },
  3113. isIntersectionLine: function ( line ) {
  3114. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3115. var startSign = this.distanceToPoint( line.start );
  3116. var endSign = this.distanceToPoint( line.end );
  3117. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3118. },
  3119. intersectLine: function() {
  3120. var v1 = new THREE.Vector3();
  3121. return function ( line, optionalTarget ) {
  3122. var result = optionalTarget || new THREE.Vector3();
  3123. var direction = line.delta( v1 );
  3124. var denominator = this.normal.dot( direction );
  3125. if ( denominator == 0 ) {
  3126. // line is coplanar, return origin
  3127. if( this.distanceToPoint( line.start ) == 0 ) {
  3128. return result.copy( line.start );
  3129. }
  3130. // Unsure if this is the correct method to handle this case.
  3131. return undefined;
  3132. }
  3133. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3134. if( t < 0 || t > 1 ) {
  3135. return undefined;
  3136. }
  3137. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3138. };
  3139. }(),
  3140. coplanarPoint: function ( optionalTarget ) {
  3141. var result = optionalTarget || new THREE.Vector3();
  3142. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3143. },
  3144. applyMatrix4: function() {
  3145. var v1 = new THREE.Vector3();
  3146. var v2 = new THREE.Vector3();
  3147. return function ( matrix, optionalNormalMatrix ) {
  3148. // compute new normal based on theory here:
  3149. // http://www.songho.ca/opengl/gl_normaltransform.html
  3150. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getNormalMatrix( matrix );
  3151. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3152. var newCoplanarPoint = this.coplanarPoint( v2 );
  3153. newCoplanarPoint.applyMatrix4( matrix );
  3154. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3155. return this;
  3156. };
  3157. }(),
  3158. translate: function ( offset ) {
  3159. this.constant = this.constant - offset.dot( this.normal );
  3160. return this;
  3161. },
  3162. equals: function ( plane ) {
  3163. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3164. },
  3165. clone: function () {
  3166. return new THREE.Plane().copy( this );
  3167. }
  3168. };
  3169. /**
  3170. * @author alteredq / http://alteredqualia.com/
  3171. */
  3172. THREE.Math = {
  3173. // Clamp value to range <a, b>
  3174. clamp: function ( x, a, b ) {
  3175. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3176. },
  3177. // Clamp value to range <a, inf)
  3178. clampBottom: function ( x, a ) {
  3179. return x < a ? a : x;
  3180. },
  3181. // Linear mapping from range <a1, a2> to range <b1, b2>
  3182. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3183. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3184. },
  3185. // http://en.wikipedia.org/wiki/Smoothstep
  3186. smoothstep: function ( x, min, max ) {
  3187. if ( x <= min ) return 0;
  3188. if ( x >= max ) return 1;
  3189. x = ( x - min )/( max - min );
  3190. return x*x*(3 - 2*x);
  3191. },
  3192. smootherstep: function ( x, min, max ) {
  3193. if ( x <= min ) return 0;
  3194. if ( x >= max ) return 1;
  3195. x = ( x - min )/( max - min );
  3196. return x*x*x*(x*(x*6 - 15) + 10);
  3197. },
  3198. // Random float from <0, 1> with 16 bits of randomness
  3199. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3200. random16: function () {
  3201. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3202. },
  3203. // Random integer from <low, high> interval
  3204. randInt: function ( low, high ) {
  3205. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3206. },
  3207. // Random float from <low, high> interval
  3208. randFloat: function ( low, high ) {
  3209. return low + Math.random() * ( high - low );
  3210. },
  3211. // Random float from <-range/2, range/2> interval
  3212. randFloatSpread: function ( range ) {
  3213. return range * ( 0.5 - Math.random() );
  3214. },
  3215. sign: function ( x ) {
  3216. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3217. },
  3218. degToRad: function() {
  3219. var degreeToRadiansFactor = Math.PI / 180;
  3220. return function ( degrees ) {
  3221. return degrees * degreeToRadiansFactor;
  3222. };
  3223. }(),
  3224. radToDeg: function() {
  3225. var radianToDegreesFactor = 180 / Math.PI;
  3226. return function ( radians ) {
  3227. return radians * radianToDegreesFactor;
  3228. };
  3229. }()
  3230. };
  3231. /**
  3232. * Spline from Tween.js, slightly optimized (and trashed)
  3233. * http://sole.github.com/tween.js/examples/05_spline.html
  3234. *
  3235. * @author mrdoob / http://mrdoob.com/
  3236. * @author alteredq / http://alteredqualia.com/
  3237. */
  3238. THREE.Spline = function ( points ) {
  3239. this.points = points;
  3240. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3241. point, intPoint, weight, w2, w3,
  3242. pa, pb, pc, pd;
  3243. this.initFromArray = function( a ) {
  3244. this.points = [];
  3245. for ( var i = 0; i < a.length; i++ ) {
  3246. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3247. }
  3248. };
  3249. this.getPoint = function ( k ) {
  3250. point = ( this.points.length - 1 ) * k;
  3251. intPoint = Math.floor( point );
  3252. weight = point - intPoint;
  3253. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3254. c[ 1 ] = intPoint;
  3255. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3256. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3257. pa = this.points[ c[ 0 ] ];
  3258. pb = this.points[ c[ 1 ] ];
  3259. pc = this.points[ c[ 2 ] ];
  3260. pd = this.points[ c[ 3 ] ];
  3261. w2 = weight * weight;
  3262. w3 = weight * w2;
  3263. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3264. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3265. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3266. return v3;
  3267. };
  3268. this.getControlPointsArray = function () {
  3269. var i, p, l = this.points.length,
  3270. coords = [];
  3271. for ( i = 0; i < l; i ++ ) {
  3272. p = this.points[ i ];
  3273. coords[ i ] = [ p.x, p.y, p.z ];
  3274. }
  3275. return coords;
  3276. };
  3277. // approximate length by summing linear segments
  3278. this.getLength = function ( nSubDivisions ) {
  3279. var i, index, nSamples, position,
  3280. point = 0, intPoint = 0, oldIntPoint = 0,
  3281. oldPosition = new THREE.Vector3(),
  3282. tmpVec = new THREE.Vector3(),
  3283. chunkLengths = [],
  3284. totalLength = 0;
  3285. // first point has 0 length
  3286. chunkLengths[ 0 ] = 0;
  3287. if ( !nSubDivisions ) nSubDivisions = 100;
  3288. nSamples = this.points.length * nSubDivisions;
  3289. oldPosition.copy( this.points[ 0 ] );
  3290. for ( i = 1; i < nSamples; i ++ ) {
  3291. index = i / nSamples;
  3292. position = this.getPoint( index );
  3293. tmpVec.copy( position );
  3294. totalLength += tmpVec.distanceTo( oldPosition );
  3295. oldPosition.copy( position );
  3296. point = ( this.points.length - 1 ) * index;
  3297. intPoint = Math.floor( point );
  3298. if ( intPoint != oldIntPoint ) {
  3299. chunkLengths[ intPoint ] = totalLength;
  3300. oldIntPoint = intPoint;
  3301. }
  3302. }
  3303. // last point ends with total length
  3304. chunkLengths[ chunkLengths.length ] = totalLength;
  3305. return { chunks: chunkLengths, total: totalLength };
  3306. };
  3307. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3308. var i, j,
  3309. index, indexCurrent, indexNext,
  3310. linearDistance, realDistance,
  3311. sampling, position,
  3312. newpoints = [],
  3313. tmpVec = new THREE.Vector3(),
  3314. sl = this.getLength();
  3315. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3316. for ( i = 1; i < this.points.length; i++ ) {
  3317. //tmpVec.copy( this.points[ i - 1 ] );
  3318. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3319. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3320. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3321. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3322. indexNext = i / ( this.points.length - 1 );
  3323. for ( j = 1; j < sampling - 1; j++ ) {
  3324. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3325. position = this.getPoint( index );
  3326. newpoints.push( tmpVec.copy( position ).clone() );
  3327. }
  3328. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3329. }
  3330. this.points = newpoints;
  3331. };
  3332. // Catmull-Rom
  3333. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3334. var v0 = ( p2 - p0 ) * 0.5,
  3335. v1 = ( p3 - p1 ) * 0.5;
  3336. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3337. };
  3338. };
  3339. /**
  3340. * @author bhouston / http://exocortex.com
  3341. * @author mrdoob / http://mrdoob.com/
  3342. */
  3343. THREE.Triangle = function ( a, b, c ) {
  3344. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3345. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3346. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3347. };
  3348. THREE.Triangle.normal = function() {
  3349. var v0 = new THREE.Vector3();
  3350. return function ( a, b, c, optionalTarget ) {
  3351. var result = optionalTarget || new THREE.Vector3();
  3352. result.subVectors( c, b );
  3353. v0.subVectors( a, b );
  3354. result.cross( v0 );
  3355. var resultLengthSq = result.lengthSq();
  3356. if( resultLengthSq > 0 ) {
  3357. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3358. }
  3359. return result.set( 0, 0, 0 );
  3360. };
  3361. }();
  3362. // static/instance method to calculate barycoordinates
  3363. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3364. THREE.Triangle.barycoordFromPoint = function() {
  3365. var v0 = new THREE.Vector3();
  3366. var v1 = new THREE.Vector3();
  3367. var v2 = new THREE.Vector3();
  3368. return function ( point, a, b, c, optionalTarget ) {
  3369. v0.subVectors( c, a );
  3370. v1.subVectors( b, a );
  3371. v2.subVectors( point, a );
  3372. var dot00 = v0.dot( v0 );
  3373. var dot01 = v0.dot( v1 );
  3374. var dot02 = v0.dot( v2 );
  3375. var dot11 = v1.dot( v1 );
  3376. var dot12 = v1.dot( v2 );
  3377. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3378. var result = optionalTarget || new THREE.Vector3();
  3379. // colinear or singular triangle
  3380. if( denom == 0 ) {
  3381. // arbitrary location outside of triangle?
  3382. // not sure if this is the best idea, maybe should be returning undefined
  3383. return result.set( -2, -1, -1 );
  3384. }
  3385. var invDenom = 1 / denom;
  3386. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3387. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3388. // barycoordinates must always sum to 1
  3389. return result.set( 1 - u - v, v, u );
  3390. };
  3391. }();
  3392. THREE.Triangle.containsPoint = function() {
  3393. var v1 = new THREE.Vector3();
  3394. return function ( point, a, b, c ) {
  3395. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3396. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3397. };
  3398. }();
  3399. THREE.Triangle.prototype = {
  3400. constructor: THREE.Triangle,
  3401. set: function ( a, b, c ) {
  3402. this.a.copy( a );
  3403. this.b.copy( b );
  3404. this.c.copy( c );
  3405. return this;
  3406. },
  3407. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3408. this.a.copy( points[i0] );
  3409. this.b.copy( points[i1] );
  3410. this.c.copy( points[i2] );
  3411. return this;
  3412. },
  3413. copy: function ( triangle ) {
  3414. this.a.copy( triangle.a );
  3415. this.b.copy( triangle.b );
  3416. this.c.copy( triangle.c );
  3417. return this;
  3418. },
  3419. area: function() {
  3420. var v0 = new THREE.Vector3();
  3421. var v1 = new THREE.Vector3();
  3422. return function () {
  3423. v0.subVectors( this.c, this.b );
  3424. v1.subVectors( this.a, this.b );
  3425. return v0.cross( v1 ).length() * 0.5;
  3426. };
  3427. }(),
  3428. midpoint: function ( optionalTarget ) {
  3429. var result = optionalTarget || new THREE.Vector3();
  3430. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3431. },
  3432. normal: function ( optionalTarget ) {
  3433. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3434. },
  3435. plane: function ( optionalTarget ) {
  3436. var result = optionalTarget || new THREE.Plane();
  3437. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3438. },
  3439. barycoordFromPoint: function ( point, optionalTarget ) {
  3440. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3441. },
  3442. containsPoint: function ( point ) {
  3443. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3444. },
  3445. equals: function ( triangle ) {
  3446. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3447. },
  3448. clone: function () {
  3449. return new THREE.Triangle().copy( this );
  3450. }
  3451. };
  3452. /**
  3453. * @author mrdoob / http://mrdoob.com/
  3454. */
  3455. THREE.Vertex = function ( v ) {
  3456. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3457. return v;
  3458. };
  3459. /**
  3460. * @author mrdoob / http://mrdoob.com/
  3461. */
  3462. THREE.UV = function ( u, v ) {
  3463. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3464. return new THREE.Vector2( u, v );
  3465. };
  3466. /**
  3467. * @author alteredq / http://alteredqualia.com/
  3468. */
  3469. THREE.Clock = function ( autoStart ) {
  3470. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3471. this.startTime = 0;
  3472. this.oldTime = 0;
  3473. this.elapsedTime = 0;
  3474. this.running = false;
  3475. };
  3476. THREE.Clock.prototype = {
  3477. constructor: THREE.Clock,
  3478. start: function () {
  3479. this.startTime = window.performance !== undefined && window.performance.now !== undefined
  3480. ? window.performance.now()
  3481. : Date.now();
  3482. this.oldTime = this.startTime;
  3483. this.running = true;
  3484. },
  3485. stop: function () {
  3486. this.getElapsedTime();
  3487. this.running = false;
  3488. },
  3489. getElapsedTime: function () {
  3490. this.getDelta();
  3491. return this.elapsedTime;
  3492. },
  3493. getDelta: function () {
  3494. var diff = 0;
  3495. if ( this.autoStart && ! this.running ) {
  3496. this.start();
  3497. }
  3498. if ( this.running ) {
  3499. var newTime = window.performance !== undefined && window.performance.now !== undefined
  3500. ? window.performance.now()
  3501. : Date.now();
  3502. diff = 0.001 * ( newTime - this.oldTime );
  3503. this.oldTime = newTime;
  3504. this.elapsedTime += diff;
  3505. }
  3506. return diff;
  3507. }
  3508. };
  3509. /**
  3510. * https://github.com/mrdoob/eventdispatcher.js/
  3511. */
  3512. THREE.EventDispatcher = function () {}
  3513. THREE.EventDispatcher.prototype = {
  3514. constructor: THREE.EventDispatcher,
  3515. addEventListener: function ( type, listener ) {
  3516. if ( this._listeners === undefined ) this._listeners = {};
  3517. var listeners = this._listeners;
  3518. if ( listeners[ type ] === undefined ) {
  3519. listeners[ type ] = [];
  3520. }
  3521. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3522. listeners[ type ].push( listener );
  3523. }
  3524. },
  3525. hasEventListener: function ( type, listener ) {
  3526. if ( this._listeners === undefined ) return false;
  3527. var listeners = this._listeners;
  3528. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3529. return true;
  3530. }
  3531. return false;
  3532. },
  3533. removeEventListener: function ( type, listener ) {
  3534. if ( this._listeners === undefined ) return;
  3535. var listeners = this._listeners;
  3536. var index = listeners[ type ].indexOf( listener );
  3537. if ( index !== - 1 ) {
  3538. listeners[ type ].splice( index, 1 );
  3539. }
  3540. },
  3541. dispatchEvent: function ( event ) {
  3542. if ( this._listeners === undefined ) return;
  3543. var listeners = this._listeners;
  3544. var listenerArray = listeners[ event.type ];
  3545. if ( listenerArray !== undefined ) {
  3546. event.target = this;
  3547. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3548. listenerArray[ i ].call( this, event );
  3549. }
  3550. }
  3551. }
  3552. };
  3553. /**
  3554. * @author mrdoob / http://mrdoob.com/
  3555. * @author bhouston / http://exocortex.com/
  3556. */
  3557. ( function ( THREE ) {
  3558. THREE.Raycaster = function ( origin, direction, near, far ) {
  3559. this.ray = new THREE.Ray( origin, direction );
  3560. // normalized ray.direction required for accurate distance calculations
  3561. if ( this.ray.direction.lengthSq() > 0 ) {
  3562. this.ray.direction.normalize();
  3563. }
  3564. this.near = near || 0;
  3565. this.far = far || Infinity;
  3566. };
  3567. var sphere = new THREE.Sphere();
  3568. var localRay = new THREE.Ray();
  3569. var facePlane = new THREE.Plane();
  3570. var intersectPoint = new THREE.Vector3();
  3571. var matrixPosition = new THREE.Vector3();
  3572. var inverseMatrix = new THREE.Matrix4();
  3573. var descSort = function ( a, b ) {
  3574. return a.distance - b.distance;
  3575. };
  3576. var intersectObject = function ( object, raycaster, intersects ) {
  3577. if ( object instanceof THREE.Particle ) {
  3578. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3579. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3580. if ( distance > object.scale.x ) {
  3581. return intersects;
  3582. }
  3583. intersects.push( {
  3584. distance: distance,
  3585. point: object.position,
  3586. face: null,
  3587. object: object
  3588. } );
  3589. } else if ( object instanceof THREE.LOD ) {
  3590. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3591. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  3592. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  3593. } else if ( object instanceof THREE.Mesh ) {
  3594. // Checking boundingSphere distance to ray
  3595. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3596. sphere.set(
  3597. matrixPosition,
  3598. object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3599. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3600. return intersects;
  3601. }
  3602. // Checking faces
  3603. var geometry = object.geometry;
  3604. var vertices = geometry.vertices;
  3605. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3606. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3607. var side = object.material.side;
  3608. var a, b, c, d;
  3609. var precision = raycaster.precision;
  3610. inverseMatrix.getInverse( object.matrixWorld );
  3611. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3612. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3613. var face = geometry.faces[ f ];
  3614. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3615. if ( material === undefined ) continue;
  3616. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3617. var planeDistance = localRay.distanceToPlane( facePlane );
  3618. // bail if raycaster and plane are parallel
  3619. if ( Math.abs( planeDistance ) < precision ) continue;
  3620. // if negative distance, then plane is behind raycaster
  3621. if ( planeDistance < 0 ) continue;
  3622. // check if we hit the wrong side of a single sided face
  3623. side = material.side;
  3624. if ( side !== THREE.DoubleSide ) {
  3625. var planeSign = localRay.direction.dot( facePlane.normal );
  3626. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3627. }
  3628. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3629. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3630. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3631. if ( face instanceof THREE.Face3 ) {
  3632. a = vertices[ face.a ];
  3633. b = vertices[ face.b ];
  3634. c = vertices[ face.c ];
  3635. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3636. } else if ( face instanceof THREE.Face4 ) {
  3637. a = vertices[ face.a ];
  3638. b = vertices[ face.b ];
  3639. c = vertices[ face.c ];
  3640. d = vertices[ face.d ];
  3641. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3642. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3643. } else {
  3644. // This is added because if we call out of this if/else group when none of the cases
  3645. // match it will add a point to the intersection list erroneously.
  3646. throw Error( "face type not supported" );
  3647. }
  3648. intersects.push( {
  3649. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3650. point: raycaster.ray.at( planeDistance ),
  3651. face: face,
  3652. faceIndex: f,
  3653. object: object
  3654. } );
  3655. }
  3656. }
  3657. };
  3658. var intersectDescendants = function ( object, raycaster, intersects ) {
  3659. var descendants = object.getDescendants();
  3660. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3661. intersectObject( descendants[ i ], raycaster, intersects );
  3662. }
  3663. };
  3664. //
  3665. THREE.Raycaster.prototype.precision = 0.0001;
  3666. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3667. this.ray.set( origin, direction );
  3668. // normalized ray.direction required for accurate distance calculations
  3669. if ( this.ray.direction.length() > 0 ) {
  3670. this.ray.direction.normalize();
  3671. }
  3672. };
  3673. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3674. var intersects = [];
  3675. if ( recursive === true ) {
  3676. intersectDescendants( object, this, intersects );
  3677. }
  3678. intersectObject( object, this, intersects );
  3679. intersects.sort( descSort );
  3680. return intersects;
  3681. };
  3682. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3683. var intersects = [];
  3684. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3685. intersectObject( objects[ i ], this, intersects );
  3686. if ( recursive === true ) {
  3687. intersectDescendants( objects[ i ], this, intersects );
  3688. }
  3689. }
  3690. intersects.sort( descSort );
  3691. return intersects;
  3692. };
  3693. }( THREE ) );
  3694. /**
  3695. * @author mrdoob / http://mrdoob.com/
  3696. * @author mikael emtinger / http://gomo.se/
  3697. * @author alteredq / http://alteredqualia.com/
  3698. * @author WestLangley / http://github.com/WestLangley
  3699. */
  3700. THREE.Object3D = function () {
  3701. this.id = THREE.Object3DIdCount ++;
  3702. this.name = '';
  3703. this.parent = undefined;
  3704. this.children = [];
  3705. this.up = new THREE.Vector3( 0, 1, 0 );
  3706. this.position = new THREE.Vector3();
  3707. this.rotation = new THREE.Vector3();
  3708. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3709. this.scale = new THREE.Vector3( 1, 1, 1 );
  3710. this.renderDepth = null;
  3711. this.rotationAutoUpdate = true;
  3712. this.matrix = new THREE.Matrix4();
  3713. this.matrixWorld = new THREE.Matrix4();
  3714. this.matrixAutoUpdate = true;
  3715. this.matrixWorldNeedsUpdate = true;
  3716. this.quaternion = new THREE.Quaternion();
  3717. this.useQuaternion = false;
  3718. this.visible = true;
  3719. this.castShadow = false;
  3720. this.receiveShadow = false;
  3721. this.frustumCulled = true;
  3722. this.userData = {};
  3723. };
  3724. THREE.Object3D.prototype = {
  3725. constructor: THREE.Object3D,
  3726. applyMatrix: function () {
  3727. var m1 = new THREE.Matrix4();
  3728. return function ( matrix ) {
  3729. this.matrix.multiplyMatrices( matrix, this.matrix );
  3730. this.position.getPositionFromMatrix( this.matrix );
  3731. this.scale.getScaleFromMatrix( this.matrix );
  3732. m1.extractRotation( this.matrix );
  3733. if ( this.useQuaternion === true ) {
  3734. this.quaternion.setFromRotationMatrix( m1 );
  3735. } else {
  3736. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3737. }
  3738. }
  3739. }(),
  3740. rotateOnAxis: function() {
  3741. // rotate object on axis in object space
  3742. // axis is assumed to be normalized
  3743. var q1 = new THREE.Quaternion();
  3744. var q2 = new THREE.Quaternion();
  3745. return function ( axis, angle ) {
  3746. q1.setFromAxisAngle( axis, angle );
  3747. if ( this.useQuaternion === true ) {
  3748. this.quaternion.multiply( q1 );
  3749. } else {
  3750. q2.setFromEuler( this.rotation, this.eulerOrder );
  3751. q2.multiply( q1 );
  3752. this.rotation.setEulerFromQuaternion( q2, this.eulerOrder );
  3753. }
  3754. return this;
  3755. }
  3756. }(),
  3757. translateOnAxis: function () {
  3758. // translate object by distance along axis in object space
  3759. // axis is assumed to be normalized
  3760. var v1 = new THREE.Vector3();
  3761. return function ( axis, distance ) {
  3762. v1.copy( axis );
  3763. if ( this.useQuaternion === true ) {
  3764. v1.applyQuaternion( this.quaternion );
  3765. } else {
  3766. v1.applyEuler( this.rotation, this.eulerOrder );
  3767. }
  3768. this.position.add( v1.multiplyScalar( distance ) );
  3769. return this;
  3770. }
  3771. }(),
  3772. translate: function ( distance, axis ) {
  3773. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  3774. return this.translateOnAxis( axis, distance );
  3775. },
  3776. translateX: function () {
  3777. var v1 = new THREE.Vector3( 1, 0, 0 );
  3778. return function ( distance ) {
  3779. return this.translateOnAxis( v1, distance );
  3780. };
  3781. }(),
  3782. translateY: function () {
  3783. var v1 = new THREE.Vector3( 0, 1, 0 );
  3784. return function ( distance ) {
  3785. return this.translateOnAxis( v1, distance );
  3786. };
  3787. }(),
  3788. translateZ: function () {
  3789. var v1 = new THREE.Vector3( 0, 0, 1 );
  3790. return function ( distance ) {
  3791. return this.translateOnAxis( v1, distance );
  3792. };
  3793. }(),
  3794. localToWorld: function ( vector ) {
  3795. return vector.applyMatrix4( this.matrixWorld );
  3796. },
  3797. worldToLocal: function () {
  3798. var m1 = new THREE.Matrix4();
  3799. return function ( vector ) {
  3800. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  3801. };
  3802. }(),
  3803. lookAt: function () {
  3804. // This routine does not support objects with rotated and/or translated parent(s)
  3805. var m1 = new THREE.Matrix4();
  3806. return function ( vector ) {
  3807. m1.lookAt( vector, this.position, this.up );
  3808. if ( this.useQuaternion === true ) {
  3809. this.quaternion.setFromRotationMatrix( m1 );
  3810. } else {
  3811. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3812. }
  3813. };
  3814. }(),
  3815. add: function ( object ) {
  3816. if ( object === this ) {
  3817. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3818. return;
  3819. }
  3820. if ( object instanceof THREE.Object3D ) {
  3821. if ( object.parent !== undefined ) {
  3822. object.parent.remove( object );
  3823. }
  3824. object.parent = this;
  3825. this.children.push( object );
  3826. // add to scene
  3827. var scene = this;
  3828. while ( scene.parent !== undefined ) {
  3829. scene = scene.parent;
  3830. }
  3831. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3832. scene.__addObject( object );
  3833. }
  3834. }
  3835. },
  3836. remove: function ( object ) {
  3837. var index = this.children.indexOf( object );
  3838. if ( index !== - 1 ) {
  3839. object.parent = undefined;
  3840. this.children.splice( index, 1 );
  3841. // remove from scene
  3842. var scene = this;
  3843. while ( scene.parent !== undefined ) {
  3844. scene = scene.parent;
  3845. }
  3846. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3847. scene.__removeObject( object );
  3848. }
  3849. }
  3850. },
  3851. traverse: function ( callback ) {
  3852. callback( this );
  3853. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3854. this.children[ i ].traverse( callback );
  3855. }
  3856. },
  3857. getObjectById: function ( id, recursive ) {
  3858. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3859. var child = this.children[ i ];
  3860. if ( child.id === id ) {
  3861. return child;
  3862. }
  3863. if ( recursive === true ) {
  3864. child = child.getObjectById( id, recursive );
  3865. if ( child !== undefined ) {
  3866. return child;
  3867. }
  3868. }
  3869. }
  3870. return undefined;
  3871. },
  3872. getObjectByName: function ( name, recursive ) {
  3873. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3874. var child = this.children[ i ];
  3875. if ( child.name === name ) {
  3876. return child;
  3877. }
  3878. if ( recursive === true ) {
  3879. child = child.getObjectByName( name, recursive );
  3880. if ( child !== undefined ) {
  3881. return child;
  3882. }
  3883. }
  3884. }
  3885. return undefined;
  3886. },
  3887. getChildByName: function ( name, recursive ) {
  3888. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  3889. return this.getObjectByName( name, recursive );
  3890. },
  3891. getDescendants: function ( array ) {
  3892. if ( array === undefined ) array = [];
  3893. Array.prototype.push.apply( array, this.children );
  3894. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3895. this.children[ i ].getDescendants( array );
  3896. }
  3897. return array;
  3898. },
  3899. updateMatrix: function () {
  3900. // if we are not using a quaternion directly, convert Euler rotation to this.quaternion.
  3901. if ( this.useQuaternion === false ) {
  3902. this.matrix.makeFromPositionEulerScale( this.position, this.rotation, this.eulerOrder, this.scale );
  3903. } else {
  3904. this.matrix.makeFromPositionQuaternionScale( this.position, this.quaternion, this.scale );
  3905. }
  3906. this.matrixWorldNeedsUpdate = true;
  3907. },
  3908. updateMatrixWorld: function ( force ) {
  3909. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3910. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3911. if ( this.parent === undefined ) {
  3912. this.matrixWorld.copy( this.matrix );
  3913. } else {
  3914. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  3915. }
  3916. this.matrixWorldNeedsUpdate = false;
  3917. force = true;
  3918. }
  3919. // update children
  3920. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3921. this.children[ i ].updateMatrixWorld( force );
  3922. }
  3923. },
  3924. clone: function ( object ) {
  3925. if ( object === undefined ) object = new THREE.Object3D();
  3926. object.name = this.name;
  3927. object.up.copy( this.up );
  3928. object.position.copy( this.position );
  3929. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3930. object.eulerOrder = this.eulerOrder;
  3931. object.scale.copy( this.scale );
  3932. object.renderDepth = this.renderDepth;
  3933. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3934. object.matrix.copy( this.matrix );
  3935. object.matrixWorld.copy( this.matrixWorld );
  3936. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3937. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3938. object.quaternion.copy( this.quaternion );
  3939. object.useQuaternion = this.useQuaternion;
  3940. object.visible = this.visible;
  3941. object.castShadow = this.castShadow;
  3942. object.receiveShadow = this.receiveShadow;
  3943. object.frustumCulled = this.frustumCulled;
  3944. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  3945. for ( var i = 0; i < this.children.length; i ++ ) {
  3946. var child = this.children[ i ];
  3947. object.add( child.clone() );
  3948. }
  3949. return object;
  3950. }
  3951. };
  3952. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3953. THREE.Object3DIdCount = 0;
  3954. /**
  3955. * @author mrdoob / http://mrdoob.com/
  3956. * @author supereggbert / http://www.paulbrunt.co.uk/
  3957. * @author julianwa / https://github.com/julianwa
  3958. */
  3959. THREE.Projector = function () {
  3960. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3961. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3962. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3963. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3964. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3965. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3966. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3967. _vector3 = new THREE.Vector3(),
  3968. _vector4 = new THREE.Vector4(),
  3969. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  3970. _boundingBox = new THREE.Box3(),
  3971. _points3 = new Array( 3 ),
  3972. _points4 = new Array( 4 ),
  3973. _viewMatrix = new THREE.Matrix4(),
  3974. _viewProjectionMatrix = new THREE.Matrix4(),
  3975. _modelMatrix,
  3976. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3977. _normalMatrix = new THREE.Matrix3(),
  3978. _normalViewMatrix = new THREE.Matrix3(),
  3979. _centroid = new THREE.Vector3(),
  3980. _frustum = new THREE.Frustum(),
  3981. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3982. _clippedVertex2PositionScreen = new THREE.Vector4();
  3983. this.projectVector = function ( vector, camera ) {
  3984. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3985. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  3986. return vector.applyProjection( _viewProjectionMatrix );
  3987. };
  3988. this.unprojectVector = function ( vector, camera ) {
  3989. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3990. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  3991. return vector.applyProjection( _viewProjectionMatrix );
  3992. };
  3993. this.pickingRay = function ( vector, camera ) {
  3994. // set two vectors with opposing z values
  3995. vector.z = -1.0;
  3996. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3997. this.unprojectVector( vector, camera );
  3998. this.unprojectVector( end, camera );
  3999. // find direction from vector to end
  4000. end.sub( vector ).normalize();
  4001. return new THREE.Raycaster( vector, end );
  4002. };
  4003. var projectGraph = function ( root, sortObjects ) {
  4004. _objectCount = 0;
  4005. _renderData.objects.length = 0;
  4006. _renderData.sprites.length = 0;
  4007. _renderData.lights.length = 0;
  4008. var projectObject = function ( parent ) {
  4009. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  4010. var object = parent.children[ c ];
  4011. if ( object.visible === false ) continue;
  4012. if ( object instanceof THREE.Light ) {
  4013. _renderData.lights.push( object );
  4014. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4015. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4016. _object = getNextObjectInPool();
  4017. _object.object = object;
  4018. if ( object.renderDepth !== null ) {
  4019. _object.z = object.renderDepth;
  4020. } else {
  4021. _vector3.getPositionFromMatrix( object.matrixWorld );
  4022. _vector3.applyProjection( _viewProjectionMatrix );
  4023. _object.z = _vector3.z;
  4024. }
  4025. _renderData.objects.push( _object );
  4026. }
  4027. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  4028. _object = getNextObjectInPool();
  4029. _object.object = object;
  4030. // TODO: Find an elegant and performant solution and remove this dupe code.
  4031. if ( object.renderDepth !== null ) {
  4032. _object.z = object.renderDepth;
  4033. } else {
  4034. _vector3.getPositionFromMatrix( object.matrixWorld );
  4035. _vector3.applyProjection( _viewProjectionMatrix );
  4036. _object.z = _vector3.z;
  4037. }
  4038. _renderData.sprites.push( _object );
  4039. } else {
  4040. _object = getNextObjectInPool();
  4041. _object.object = object;
  4042. if ( object.renderDepth !== null ) {
  4043. _object.z = object.renderDepth;
  4044. } else {
  4045. _vector3.getPositionFromMatrix( object.matrixWorld );
  4046. _vector3.applyProjection( _viewProjectionMatrix );
  4047. _object.z = _vector3.z;
  4048. }
  4049. _renderData.objects.push( _object );
  4050. }
  4051. projectObject( object );
  4052. }
  4053. };
  4054. projectObject( root );
  4055. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  4056. return _renderData;
  4057. };
  4058. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4059. var visible = false,
  4060. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4061. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4062. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4063. _face3Count = 0;
  4064. _face4Count = 0;
  4065. _lineCount = 0;
  4066. _particleCount = 0;
  4067. _renderData.elements.length = 0;
  4068. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4069. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4070. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4071. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4072. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4073. _frustum.setFromMatrix( _viewProjectionMatrix );
  4074. _renderData = projectGraph( scene, sortObjects );
  4075. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4076. object = _renderData.objects[ o ].object;
  4077. _modelMatrix = object.matrixWorld;
  4078. _vertexCount = 0;
  4079. if ( object instanceof THREE.Mesh ) {
  4080. geometry = object.geometry;
  4081. vertices = geometry.vertices;
  4082. faces = geometry.faces;
  4083. faceVertexUvs = geometry.faceVertexUvs;
  4084. _normalMatrix.getNormalMatrix( _modelMatrix );
  4085. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4086. objectMaterials = isFaceMaterial === true ? object.material : null;
  4087. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4088. _vertex = getNextVertexInPool();
  4089. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4090. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4091. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  4092. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  4093. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  4094. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4095. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4096. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4097. }
  4098. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4099. face = faces[ f ];
  4100. var material = isFaceMaterial === true
  4101. ? objectMaterials.materials[ face.materialIndex ]
  4102. : object.material;
  4103. if ( material === undefined ) continue;
  4104. var side = material.side;
  4105. if ( face instanceof THREE.Face3 ) {
  4106. v1 = _vertexPool[ face.a ];
  4107. v2 = _vertexPool[ face.b ];
  4108. v3 = _vertexPool[ face.c ];
  4109. _points3[ 0 ] = v1.positionScreen;
  4110. _points3[ 1 ] = v2.positionScreen;
  4111. _points3[ 2 ] = v3.positionScreen;
  4112. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4113. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4114. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4115. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4116. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4117. _face = getNextFace3InPool();
  4118. _face.v1.copy( v1 );
  4119. _face.v2.copy( v2 );
  4120. _face.v3.copy( v3 );
  4121. } else {
  4122. continue;
  4123. }
  4124. } else {
  4125. continue;
  4126. }
  4127. } else if ( face instanceof THREE.Face4 ) {
  4128. v1 = _vertexPool[ face.a ];
  4129. v2 = _vertexPool[ face.b ];
  4130. v3 = _vertexPool[ face.c ];
  4131. v4 = _vertexPool[ face.d ];
  4132. _points4[ 0 ] = v1.positionScreen;
  4133. _points4[ 1 ] = v2.positionScreen;
  4134. _points4[ 2 ] = v3.positionScreen;
  4135. _points4[ 3 ] = v4.positionScreen;
  4136. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4137. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4138. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4139. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4140. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4141. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4142. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4143. _face = getNextFace4InPool();
  4144. _face.v1.copy( v1 );
  4145. _face.v2.copy( v2 );
  4146. _face.v3.copy( v3 );
  4147. _face.v4.copy( v4 );
  4148. } else {
  4149. continue;
  4150. }
  4151. } else {
  4152. continue;
  4153. }
  4154. }
  4155. _face.normalModel.copy( face.normal );
  4156. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4157. _face.normalModel.negate();
  4158. }
  4159. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4160. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4161. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4162. faceVertexNormals = face.vertexNormals;
  4163. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4164. var normalModel = _face.vertexNormalsModel[ n ];
  4165. normalModel.copy( faceVertexNormals[ n ] );
  4166. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4167. normalModel.negate();
  4168. }
  4169. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4170. var normalModelView = _face.vertexNormalsModelView[ n ];
  4171. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4172. }
  4173. _face.vertexNormalsLength = faceVertexNormals.length;
  4174. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4175. uvs = faceVertexUvs[ c ][ f ];
  4176. if ( uvs === undefined ) continue;
  4177. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4178. _face.uvs[ c ][ u ] = uvs[ u ];
  4179. }
  4180. }
  4181. _face.color = face.color;
  4182. _face.material = material;
  4183. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4184. _face.z = _centroid.z;
  4185. _renderData.elements.push( _face );
  4186. }
  4187. } else if ( object instanceof THREE.Line ) {
  4188. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4189. vertices = object.geometry.vertices;
  4190. v1 = getNextVertexInPool();
  4191. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4192. // Handle LineStrip and LinePieces
  4193. var step = object.type === THREE.LinePieces ? 2 : 1;
  4194. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4195. v1 = getNextVertexInPool();
  4196. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4197. if ( ( v + 1 ) % step > 0 ) continue;
  4198. v2 = _vertexPool[ _vertexCount - 2 ];
  4199. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4200. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4201. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4202. // Perform the perspective divide
  4203. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4204. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4205. _line = getNextLineInPool();
  4206. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4207. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4208. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4209. _line.material = object.material;
  4210. if ( object.material.vertexColors === THREE.VertexColors ) {
  4211. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4212. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4213. }
  4214. _renderData.elements.push( _line );
  4215. }
  4216. }
  4217. }
  4218. }
  4219. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4220. object = _renderData.sprites[ o ].object;
  4221. _modelMatrix = object.matrixWorld;
  4222. if ( object instanceof THREE.Particle ) {
  4223. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4224. _vector4.applyMatrix4( _viewProjectionMatrix );
  4225. _vector4.z /= _vector4.w;
  4226. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4227. _particle = getNextParticleInPool();
  4228. _particle.object = object;
  4229. _particle.x = _vector4.x / _vector4.w;
  4230. _particle.y = _vector4.y / _vector4.w;
  4231. _particle.z = _vector4.z;
  4232. _particle.rotation = object.rotation.z;
  4233. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4234. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4235. _particle.material = object.material;
  4236. _renderData.elements.push( _particle );
  4237. }
  4238. }
  4239. }
  4240. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4241. return _renderData;
  4242. };
  4243. // Pools
  4244. function getNextObjectInPool() {
  4245. if ( _objectCount === _objectPoolLength ) {
  4246. var object = new THREE.RenderableObject();
  4247. _objectPool.push( object );
  4248. _objectPoolLength ++;
  4249. _objectCount ++;
  4250. return object;
  4251. }
  4252. return _objectPool[ _objectCount ++ ];
  4253. }
  4254. function getNextVertexInPool() {
  4255. if ( _vertexCount === _vertexPoolLength ) {
  4256. var vertex = new THREE.RenderableVertex();
  4257. _vertexPool.push( vertex );
  4258. _vertexPoolLength ++;
  4259. _vertexCount ++;
  4260. return vertex;
  4261. }
  4262. return _vertexPool[ _vertexCount ++ ];
  4263. }
  4264. function getNextFace3InPool() {
  4265. if ( _face3Count === _face3PoolLength ) {
  4266. var face = new THREE.RenderableFace3();
  4267. _face3Pool.push( face );
  4268. _face3PoolLength ++;
  4269. _face3Count ++;
  4270. return face;
  4271. }
  4272. return _face3Pool[ _face3Count ++ ];
  4273. }
  4274. function getNextFace4InPool() {
  4275. if ( _face4Count === _face4PoolLength ) {
  4276. var face = new THREE.RenderableFace4();
  4277. _face4Pool.push( face );
  4278. _face4PoolLength ++;
  4279. _face4Count ++;
  4280. return face;
  4281. }
  4282. return _face4Pool[ _face4Count ++ ];
  4283. }
  4284. function getNextLineInPool() {
  4285. if ( _lineCount === _linePoolLength ) {
  4286. var line = new THREE.RenderableLine();
  4287. _linePool.push( line );
  4288. _linePoolLength ++;
  4289. _lineCount ++
  4290. return line;
  4291. }
  4292. return _linePool[ _lineCount ++ ];
  4293. }
  4294. function getNextParticleInPool() {
  4295. if ( _particleCount === _particlePoolLength ) {
  4296. var particle = new THREE.RenderableParticle();
  4297. _particlePool.push( particle );
  4298. _particlePoolLength ++;
  4299. _particleCount ++
  4300. return particle;
  4301. }
  4302. return _particlePool[ _particleCount ++ ];
  4303. }
  4304. //
  4305. function painterSort( a, b ) {
  4306. return b.z - a.z;
  4307. }
  4308. function clipLine( s1, s2 ) {
  4309. var alpha1 = 0, alpha2 = 1,
  4310. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4311. // Z = -1 and Z = +1, respectively.
  4312. bc1near = s1.z + s1.w,
  4313. bc2near = s2.z + s2.w,
  4314. bc1far = - s1.z + s1.w,
  4315. bc2far = - s2.z + s2.w;
  4316. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4317. // Both vertices lie entirely within all clip planes.
  4318. return true;
  4319. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4320. // Both vertices lie entirely outside one of the clip planes.
  4321. return false;
  4322. } else {
  4323. // The line segment spans at least one clip plane.
  4324. if ( bc1near < 0 ) {
  4325. // v1 lies outside the near plane, v2 inside
  4326. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4327. } else if ( bc2near < 0 ) {
  4328. // v2 lies outside the near plane, v1 inside
  4329. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4330. }
  4331. if ( bc1far < 0 ) {
  4332. // v1 lies outside the far plane, v2 inside
  4333. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4334. } else if ( bc2far < 0 ) {
  4335. // v2 lies outside the far plane, v2 inside
  4336. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4337. }
  4338. if ( alpha2 < alpha1 ) {
  4339. // The line segment spans two boundaries, but is outside both of them.
  4340. // (This can't happen when we're only clipping against just near/far but good
  4341. // to leave the check here for future usage if other clip planes are added.)
  4342. return false;
  4343. } else {
  4344. // Update the s1 and s2 vertices to match the clipped line segment.
  4345. s1.lerp( s2, alpha1 );
  4346. s2.lerp( s1, 1 - alpha2 );
  4347. return true;
  4348. }
  4349. }
  4350. }
  4351. };
  4352. /**
  4353. * @author mrdoob / http://mrdoob.com/
  4354. * @author alteredq / http://alteredqualia.com/
  4355. */
  4356. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4357. this.a = a;
  4358. this.b = b;
  4359. this.c = c;
  4360. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4361. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4362. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4363. this.vertexColors = color instanceof Array ? color : [];
  4364. this.vertexTangents = [];
  4365. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4366. this.centroid = new THREE.Vector3();
  4367. };
  4368. THREE.Face3.prototype = {
  4369. constructor: THREE.Face3,
  4370. clone: function () {
  4371. var face = new THREE.Face3( this.a, this.b, this.c );
  4372. face.normal.copy( this.normal );
  4373. face.color.copy( this.color );
  4374. face.centroid.copy( this.centroid );
  4375. face.materialIndex = this.materialIndex;
  4376. var i, il;
  4377. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4378. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4379. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4380. return face;
  4381. }
  4382. };
  4383. /**
  4384. * @author mrdoob / http://mrdoob.com/
  4385. * @author alteredq / http://alteredqualia.com/
  4386. */
  4387. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4388. this.a = a;
  4389. this.b = b;
  4390. this.c = c;
  4391. this.d = d;
  4392. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4393. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4394. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4395. this.vertexColors = color instanceof Array ? color : [];
  4396. this.vertexTangents = [];
  4397. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4398. this.centroid = new THREE.Vector3();
  4399. };
  4400. THREE.Face4.prototype = {
  4401. constructor: THREE.Face4,
  4402. clone: function () {
  4403. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4404. face.normal.copy( this.normal );
  4405. face.color.copy( this.color );
  4406. face.centroid.copy( this.centroid );
  4407. face.materialIndex = this.materialIndex;
  4408. var i, il;
  4409. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4410. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4411. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4412. return face;
  4413. }
  4414. };
  4415. /**
  4416. * @author mrdoob / http://mrdoob.com/
  4417. * @author kile / http://kile.stravaganza.org/
  4418. * @author alteredq / http://alteredqualia.com/
  4419. * @author mikael emtinger / http://gomo.se/
  4420. * @author zz85 / http://www.lab4games.net/zz85/blog
  4421. * @author bhouston / http://exocortex.com
  4422. */
  4423. THREE.Geometry = function () {
  4424. this.id = THREE.GeometryIdCount ++;
  4425. this.name = '';
  4426. this.vertices = [];
  4427. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4428. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4429. this.faces = [];
  4430. this.faceUvs = [[]];
  4431. this.faceVertexUvs = [[]];
  4432. this.morphTargets = [];
  4433. this.morphColors = [];
  4434. this.morphNormals = [];
  4435. this.skinWeights = [];
  4436. this.skinIndices = [];
  4437. this.lineDistances = [];
  4438. this.boundingBox = null;
  4439. this.boundingSphere = null;
  4440. this.hasTangents = false;
  4441. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4442. // update flags
  4443. this.verticesNeedUpdate = false;
  4444. this.elementsNeedUpdate = false;
  4445. this.uvsNeedUpdate = false;
  4446. this.normalsNeedUpdate = false;
  4447. this.tangentsNeedUpdate = false;
  4448. this.colorsNeedUpdate = false;
  4449. this.lineDistancesNeedUpdate = false;
  4450. this.buffersNeedUpdate = false;
  4451. };
  4452. THREE.Geometry.prototype = {
  4453. constructor: THREE.Geometry,
  4454. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4455. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4456. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4457. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4458. applyMatrix: function ( matrix ) {
  4459. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4460. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4461. var vertex = this.vertices[ i ];
  4462. vertex.applyMatrix4( matrix );
  4463. }
  4464. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4465. var face = this.faces[ i ];
  4466. face.normal.applyMatrix3( normalMatrix ).normalize();
  4467. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4468. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4469. }
  4470. face.centroid.applyMatrix4( matrix );
  4471. }
  4472. },
  4473. computeCentroids: function () {
  4474. var f, fl, face;
  4475. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4476. face = this.faces[ f ];
  4477. face.centroid.set( 0, 0, 0 );
  4478. if ( face instanceof THREE.Face3 ) {
  4479. face.centroid.add( this.vertices[ face.a ] );
  4480. face.centroid.add( this.vertices[ face.b ] );
  4481. face.centroid.add( this.vertices[ face.c ] );
  4482. face.centroid.divideScalar( 3 );
  4483. } else if ( face instanceof THREE.Face4 ) {
  4484. face.centroid.add( this.vertices[ face.a ] );
  4485. face.centroid.add( this.vertices[ face.b ] );
  4486. face.centroid.add( this.vertices[ face.c ] );
  4487. face.centroid.add( this.vertices[ face.d ] );
  4488. face.centroid.divideScalar( 4 );
  4489. }
  4490. }
  4491. },
  4492. computeFaceNormals: function () {
  4493. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4494. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4495. var face = this.faces[ f ];
  4496. var vA = this.vertices[ face.a ];
  4497. var vB = this.vertices[ face.b ];
  4498. var vC = this.vertices[ face.c ];
  4499. cb.subVectors( vC, vB );
  4500. ab.subVectors( vA, vB );
  4501. cb.cross( ab );
  4502. cb.normalize();
  4503. face.normal.copy( cb );
  4504. }
  4505. },
  4506. computeVertexNormals: function ( areaWeighted ) {
  4507. var v, vl, f, fl, face, vertices;
  4508. // create internal buffers for reuse when calling this method repeatedly
  4509. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4510. if ( this.__tmpVertices === undefined ) {
  4511. this.__tmpVertices = new Array( this.vertices.length );
  4512. vertices = this.__tmpVertices;
  4513. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4514. vertices[ v ] = new THREE.Vector3();
  4515. }
  4516. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4517. face = this.faces[ f ];
  4518. if ( face instanceof THREE.Face3 ) {
  4519. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4520. } else if ( face instanceof THREE.Face4 ) {
  4521. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4522. }
  4523. }
  4524. } else {
  4525. vertices = this.__tmpVertices;
  4526. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4527. vertices[ v ].set( 0, 0, 0 );
  4528. }
  4529. }
  4530. if ( areaWeighted ) {
  4531. // vertex normals weighted by triangle areas
  4532. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4533. var vA, vB, vC, vD;
  4534. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4535. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4536. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4537. face = this.faces[ f ];
  4538. if ( face instanceof THREE.Face3 ) {
  4539. vA = this.vertices[ face.a ];
  4540. vB = this.vertices[ face.b ];
  4541. vC = this.vertices[ face.c ];
  4542. cb.subVectors( vC, vB );
  4543. ab.subVectors( vA, vB );
  4544. cb.cross( ab );
  4545. vertices[ face.a ].add( cb );
  4546. vertices[ face.b ].add( cb );
  4547. vertices[ face.c ].add( cb );
  4548. } else if ( face instanceof THREE.Face4 ) {
  4549. vA = this.vertices[ face.a ];
  4550. vB = this.vertices[ face.b ];
  4551. vC = this.vertices[ face.c ];
  4552. vD = this.vertices[ face.d ];
  4553. // abd
  4554. db.subVectors( vD, vB );
  4555. ab.subVectors( vA, vB );
  4556. db.cross( ab );
  4557. vertices[ face.a ].add( db );
  4558. vertices[ face.b ].add( db );
  4559. vertices[ face.d ].add( db );
  4560. // bcd
  4561. dc.subVectors( vD, vC );
  4562. bc.subVectors( vB, vC );
  4563. dc.cross( bc );
  4564. vertices[ face.b ].add( dc );
  4565. vertices[ face.c ].add( dc );
  4566. vertices[ face.d ].add( dc );
  4567. }
  4568. }
  4569. } else {
  4570. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4571. face = this.faces[ f ];
  4572. if ( face instanceof THREE.Face3 ) {
  4573. vertices[ face.a ].add( face.normal );
  4574. vertices[ face.b ].add( face.normal );
  4575. vertices[ face.c ].add( face.normal );
  4576. } else if ( face instanceof THREE.Face4 ) {
  4577. vertices[ face.a ].add( face.normal );
  4578. vertices[ face.b ].add( face.normal );
  4579. vertices[ face.c ].add( face.normal );
  4580. vertices[ face.d ].add( face.normal );
  4581. }
  4582. }
  4583. }
  4584. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4585. vertices[ v ].normalize();
  4586. }
  4587. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4588. face = this.faces[ f ];
  4589. if ( face instanceof THREE.Face3 ) {
  4590. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4591. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4592. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4593. } else if ( face instanceof THREE.Face4 ) {
  4594. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4595. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4596. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4597. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4598. }
  4599. }
  4600. },
  4601. computeMorphNormals: function () {
  4602. var i, il, f, fl, face;
  4603. // save original normals
  4604. // - create temp variables on first access
  4605. // otherwise just copy (for faster repeated calls)
  4606. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4607. face = this.faces[ f ];
  4608. if ( ! face.__originalFaceNormal ) {
  4609. face.__originalFaceNormal = face.normal.clone();
  4610. } else {
  4611. face.__originalFaceNormal.copy( face.normal );
  4612. }
  4613. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4614. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4615. if ( ! face.__originalVertexNormals[ i ] ) {
  4616. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4617. } else {
  4618. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4619. }
  4620. }
  4621. }
  4622. // use temp geometry to compute face and vertex normals for each morph
  4623. var tmpGeo = new THREE.Geometry();
  4624. tmpGeo.faces = this.faces;
  4625. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4626. // create on first access
  4627. if ( ! this.morphNormals[ i ] ) {
  4628. this.morphNormals[ i ] = {};
  4629. this.morphNormals[ i ].faceNormals = [];
  4630. this.morphNormals[ i ].vertexNormals = [];
  4631. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4632. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4633. var faceNormal, vertexNormals;
  4634. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4635. face = this.faces[ f ];
  4636. faceNormal = new THREE.Vector3();
  4637. if ( face instanceof THREE.Face3 ) {
  4638. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4639. } else {
  4640. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4641. }
  4642. dstNormalsFace.push( faceNormal );
  4643. dstNormalsVertex.push( vertexNormals );
  4644. }
  4645. }
  4646. var morphNormals = this.morphNormals[ i ];
  4647. // set vertices to morph target
  4648. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4649. // compute morph normals
  4650. tmpGeo.computeFaceNormals();
  4651. tmpGeo.computeVertexNormals();
  4652. // store morph normals
  4653. var faceNormal, vertexNormals;
  4654. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4655. face = this.faces[ f ];
  4656. faceNormal = morphNormals.faceNormals[ f ];
  4657. vertexNormals = morphNormals.vertexNormals[ f ];
  4658. faceNormal.copy( face.normal );
  4659. if ( face instanceof THREE.Face3 ) {
  4660. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4661. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4662. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4663. } else {
  4664. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4665. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4666. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4667. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4668. }
  4669. }
  4670. }
  4671. // restore original normals
  4672. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4673. face = this.faces[ f ];
  4674. face.normal = face.__originalFaceNormal;
  4675. face.vertexNormals = face.__originalVertexNormals;
  4676. }
  4677. },
  4678. computeTangents: function () {
  4679. // based on http://www.terathon.com/code/tangent.html
  4680. // tangents go to vertices
  4681. var f, fl, v, vl, i, il, vertexIndex,
  4682. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4683. x1, x2, y1, y2, z1, z2,
  4684. s1, s2, t1, t2, r, t, test,
  4685. tan1 = [], tan2 = [],
  4686. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4687. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4688. n = new THREE.Vector3(), w;
  4689. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4690. tan1[ v ] = new THREE.Vector3();
  4691. tan2[ v ] = new THREE.Vector3();
  4692. }
  4693. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4694. vA = context.vertices[ a ];
  4695. vB = context.vertices[ b ];
  4696. vC = context.vertices[ c ];
  4697. uvA = uv[ ua ];
  4698. uvB = uv[ ub ];
  4699. uvC = uv[ uc ];
  4700. x1 = vB.x - vA.x;
  4701. x2 = vC.x - vA.x;
  4702. y1 = vB.y - vA.y;
  4703. y2 = vC.y - vA.y;
  4704. z1 = vB.z - vA.z;
  4705. z2 = vC.z - vA.z;
  4706. s1 = uvB.x - uvA.x;
  4707. s2 = uvC.x - uvA.x;
  4708. t1 = uvB.y - uvA.y;
  4709. t2 = uvC.y - uvA.y;
  4710. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4711. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4712. ( t2 * y1 - t1 * y2 ) * r,
  4713. ( t2 * z1 - t1 * z2 ) * r );
  4714. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4715. ( s1 * y2 - s2 * y1 ) * r,
  4716. ( s1 * z2 - s2 * z1 ) * r );
  4717. tan1[ a ].add( sdir );
  4718. tan1[ b ].add( sdir );
  4719. tan1[ c ].add( sdir );
  4720. tan2[ a ].add( tdir );
  4721. tan2[ b ].add( tdir );
  4722. tan2[ c ].add( tdir );
  4723. }
  4724. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4725. face = this.faces[ f ];
  4726. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4727. if ( face instanceof THREE.Face3 ) {
  4728. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4729. } else if ( face instanceof THREE.Face4 ) {
  4730. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4731. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4732. }
  4733. }
  4734. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4735. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4736. face = this.faces[ f ];
  4737. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4738. n.copy( face.vertexNormals[ i ] );
  4739. vertexIndex = face[ faceIndex[ i ] ];
  4740. t = tan1[ vertexIndex ];
  4741. // Gram-Schmidt orthogonalize
  4742. tmp.copy( t );
  4743. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4744. // Calculate handedness
  4745. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4746. test = tmp2.dot( tan2[ vertexIndex ] );
  4747. w = (test < 0.0) ? -1.0 : 1.0;
  4748. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4749. }
  4750. }
  4751. this.hasTangents = true;
  4752. },
  4753. computeLineDistances: function ( ) {
  4754. var d = 0;
  4755. var vertices = this.vertices;
  4756. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4757. if ( i > 0 ) {
  4758. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4759. }
  4760. this.lineDistances[ i ] = d;
  4761. }
  4762. },
  4763. computeBoundingBox: function () {
  4764. if ( this.boundingBox === null ) {
  4765. this.boundingBox = new THREE.Box3();
  4766. }
  4767. this.boundingBox.setFromPoints( this.vertices );
  4768. },
  4769. computeBoundingSphere: function () {
  4770. if ( this.boundingSphere === null ) {
  4771. this.boundingSphere = new THREE.Sphere();
  4772. }
  4773. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4774. },
  4775. /*
  4776. * Checks for duplicate vertices with hashmap.
  4777. * Duplicated vertices are removed
  4778. * and faces' vertices are updated.
  4779. */
  4780. mergeVertices: function () {
  4781. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4782. var unique = [], changes = [];
  4783. var v, key;
  4784. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4785. var precision = Math.pow( 10, precisionPoints );
  4786. var i,il, face;
  4787. var indices, k, j, jl, u;
  4788. // reset cache of vertices as it now will be changing.
  4789. this.__tmpVertices = undefined;
  4790. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4791. v = this.vertices[ i ];
  4792. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4793. if ( verticesMap[ key ] === undefined ) {
  4794. verticesMap[ key ] = i;
  4795. unique.push( this.vertices[ i ] );
  4796. changes[ i ] = unique.length - 1;
  4797. } else {
  4798. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4799. changes[ i ] = changes[ verticesMap[ key ] ];
  4800. }
  4801. };
  4802. // if faces are completely degenerate after merging vertices, we
  4803. // have to remove them from the geometry.
  4804. var faceIndicesToRemove = [];
  4805. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4806. face = this.faces[ i ];
  4807. if ( face instanceof THREE.Face3 ) {
  4808. face.a = changes[ face.a ];
  4809. face.b = changes[ face.b ];
  4810. face.c = changes[ face.c ];
  4811. indices = [ face.a, face.b, face.c ];
  4812. var dupIndex = -1;
  4813. // if any duplicate vertices are found in a Face3
  4814. // we have to remove the face as nothing can be saved
  4815. for ( var n = 0; n < 3; n ++ ) {
  4816. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4817. dupIndex = n;
  4818. faceIndicesToRemove.push( i );
  4819. break;
  4820. }
  4821. }
  4822. } else if ( face instanceof THREE.Face4 ) {
  4823. face.a = changes[ face.a ];
  4824. face.b = changes[ face.b ];
  4825. face.c = changes[ face.c ];
  4826. face.d = changes[ face.d ];
  4827. // check dups in (a, b, c, d) and convert to -> face3
  4828. indices = [ face.a, face.b, face.c, face.d ];
  4829. var dupIndex = -1;
  4830. for ( var n = 0; n < 4; n ++ ) {
  4831. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4832. // if more than one duplicated vertex is found
  4833. // we can't generate any valid Face3's, thus
  4834. // we need to remove this face complete.
  4835. if ( dupIndex >= 0 ) {
  4836. faceIndicesToRemove.push( i );
  4837. }
  4838. dupIndex = n;
  4839. }
  4840. }
  4841. if ( dupIndex >= 0 ) {
  4842. indices.splice( dupIndex, 1 );
  4843. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4844. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4845. u = this.faceVertexUvs[ j ][ i ];
  4846. if ( u ) {
  4847. u.splice( dupIndex, 1 );
  4848. }
  4849. }
  4850. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4851. newFace.vertexNormals = face.vertexNormals;
  4852. newFace.vertexNormals.splice( dupIndex, 1 );
  4853. }
  4854. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4855. newFace.vertexColors = face.vertexColors;
  4856. newFace.vertexColors.splice( dupIndex, 1 );
  4857. }
  4858. this.faces[ i ] = newFace;
  4859. }
  4860. }
  4861. }
  4862. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4863. this.faces.splice( i, 1 );
  4864. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4865. this.faceVertexUvs[ j ].splice( i, 1 );
  4866. }
  4867. }
  4868. // Use unique set of vertices
  4869. var diff = this.vertices.length - unique.length;
  4870. this.vertices = unique;
  4871. return diff;
  4872. },
  4873. clone: function () {
  4874. var geometry = new THREE.Geometry();
  4875. var vertices = this.vertices;
  4876. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4877. geometry.vertices.push( vertices[ i ].clone() );
  4878. }
  4879. var faces = this.faces;
  4880. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4881. geometry.faces.push( faces[ i ].clone() );
  4882. }
  4883. var uvs = this.faceVertexUvs[ 0 ];
  4884. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4885. var uv = uvs[ i ], uvCopy = [];
  4886. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4887. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4888. }
  4889. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4890. }
  4891. return geometry;
  4892. },
  4893. dispose: function () {
  4894. this.dispatchEvent( { type: 'dispose' } );
  4895. }
  4896. };
  4897. THREE.GeometryIdCount = 0;
  4898. /**
  4899. * @author alteredq / http://alteredqualia.com/
  4900. */
  4901. THREE.BufferGeometry = function () {
  4902. this.id = THREE.GeometryIdCount ++;
  4903. // attributes
  4904. this.attributes = {};
  4905. // attributes typed arrays are kept only if dynamic flag is set
  4906. this.dynamic = false;
  4907. // offsets for chunks when using indexed elements
  4908. this.offsets = [];
  4909. // boundings
  4910. this.boundingBox = null;
  4911. this.boundingSphere = null;
  4912. this.hasTangents = false;
  4913. // for compatibility
  4914. this.morphTargets = [];
  4915. };
  4916. THREE.BufferGeometry.prototype = {
  4917. constructor: THREE.BufferGeometry,
  4918. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4919. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4920. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4921. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4922. applyMatrix: function ( matrix ) {
  4923. var positionArray;
  4924. var normalArray;
  4925. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4926. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4927. if ( positionArray !== undefined ) {
  4928. matrix.multiplyVector3Array( positionArray );
  4929. this.verticesNeedUpdate = true;
  4930. }
  4931. if ( normalArray !== undefined ) {
  4932. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4933. normalMatrix.multiplyVector3Array( normalArray );
  4934. this.normalizeNormals();
  4935. this.normalsNeedUpdate = true;
  4936. }
  4937. },
  4938. computeBoundingBox: function () {
  4939. if ( this.boundingBox === null ) {
  4940. this.boundingBox = new THREE.Box3();
  4941. }
  4942. var positions = this.attributes[ "position" ].array;
  4943. if ( positions ) {
  4944. var bb = this.boundingBox;
  4945. var x, y, z;
  4946. if( positions.length >= 3 ) {
  4947. bb.min.x = bb.max.x = positions[ 0 ];
  4948. bb.min.y = bb.max.y = positions[ 1 ];
  4949. bb.min.z = bb.max.z = positions[ 2 ];
  4950. }
  4951. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4952. x = positions[ i ];
  4953. y = positions[ i + 1 ];
  4954. z = positions[ i + 2 ];
  4955. // bounding box
  4956. if ( x < bb.min.x ) {
  4957. bb.min.x = x;
  4958. } else if ( x > bb.max.x ) {
  4959. bb.max.x = x;
  4960. }
  4961. if ( y < bb.min.y ) {
  4962. bb.min.y = y;
  4963. } else if ( y > bb.max.y ) {
  4964. bb.max.y = y;
  4965. }
  4966. if ( z < bb.min.z ) {
  4967. bb.min.z = z;
  4968. } else if ( z > bb.max.z ) {
  4969. bb.max.z = z;
  4970. }
  4971. }
  4972. }
  4973. if ( positions === undefined || positions.length === 0 ) {
  4974. this.boundingBox.min.set( 0, 0, 0 );
  4975. this.boundingBox.max.set( 0, 0, 0 );
  4976. }
  4977. },
  4978. computeBoundingSphere: function () {
  4979. if ( this.boundingSphere === null ) {
  4980. this.boundingSphere = new THREE.Sphere();
  4981. }
  4982. var positions = this.attributes[ "position" ].array;
  4983. if ( positions ) {
  4984. var radiusSq, maxRadiusSq = 0;
  4985. var x, y, z;
  4986. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4987. x = positions[ i ];
  4988. y = positions[ i + 1 ];
  4989. z = positions[ i + 2 ];
  4990. radiusSq = x * x + y * y + z * z;
  4991. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4992. }
  4993. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4994. }
  4995. },
  4996. computeVertexNormals: function () {
  4997. if ( this.attributes[ "position" ] ) {
  4998. var i, il;
  4999. var j, jl;
  5000. var nVertexElements = this.attributes[ "position" ].array.length;
  5001. if ( this.attributes[ "normal" ] === undefined ) {
  5002. this.attributes[ "normal" ] = {
  5003. itemSize: 3,
  5004. array: new Float32Array( nVertexElements ),
  5005. numItems: nVertexElements
  5006. };
  5007. } else {
  5008. // reset existing normals to zero
  5009. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5010. this.attributes[ "normal" ].array[ i ] = 0;
  5011. }
  5012. }
  5013. var positions = this.attributes[ "position" ].array;
  5014. var normals = this.attributes[ "normal" ].array;
  5015. var vA, vB, vC, x, y, z,
  5016. pA = new THREE.Vector3(),
  5017. pB = new THREE.Vector3(),
  5018. pC = new THREE.Vector3(),
  5019. cb = new THREE.Vector3(),
  5020. ab = new THREE.Vector3();
  5021. // indexed elements
  5022. if ( this.attributes[ "index" ] ) {
  5023. var indices = this.attributes[ "index" ].array;
  5024. var offsets = this.offsets;
  5025. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5026. var start = offsets[ j ].start;
  5027. var count = offsets[ j ].count;
  5028. var index = offsets[ j ].index;
  5029. for ( i = start, il = start + count; i < il; i += 3 ) {
  5030. vA = index + indices[ i ];
  5031. vB = index + indices[ i + 1 ];
  5032. vC = index + indices[ i + 2 ];
  5033. x = positions[ vA * 3 ];
  5034. y = positions[ vA * 3 + 1 ];
  5035. z = positions[ vA * 3 + 2 ];
  5036. pA.set( x, y, z );
  5037. x = positions[ vB * 3 ];
  5038. y = positions[ vB * 3 + 1 ];
  5039. z = positions[ vB * 3 + 2 ];
  5040. pB.set( x, y, z );
  5041. x = positions[ vC * 3 ];
  5042. y = positions[ vC * 3 + 1 ];
  5043. z = positions[ vC * 3 + 2 ];
  5044. pC.set( x, y, z );
  5045. cb.subVectors( pC, pB );
  5046. ab.subVectors( pA, pB );
  5047. cb.cross( ab );
  5048. normals[ vA * 3 ] += cb.x;
  5049. normals[ vA * 3 + 1 ] += cb.y;
  5050. normals[ vA * 3 + 2 ] += cb.z;
  5051. normals[ vB * 3 ] += cb.x;
  5052. normals[ vB * 3 + 1 ] += cb.y;
  5053. normals[ vB * 3 + 2 ] += cb.z;
  5054. normals[ vC * 3 ] += cb.x;
  5055. normals[ vC * 3 + 1 ] += cb.y;
  5056. normals[ vC * 3 + 2 ] += cb.z;
  5057. }
  5058. }
  5059. // non-indexed elements (unconnected triangle soup)
  5060. } else {
  5061. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5062. x = positions[ i ];
  5063. y = positions[ i + 1 ];
  5064. z = positions[ i + 2 ];
  5065. pA.set( x, y, z );
  5066. x = positions[ i + 3 ];
  5067. y = positions[ i + 4 ];
  5068. z = positions[ i + 5 ];
  5069. pB.set( x, y, z );
  5070. x = positions[ i + 6 ];
  5071. y = positions[ i + 7 ];
  5072. z = positions[ i + 8 ];
  5073. pC.set( x, y, z );
  5074. cb.subVectors( pC, pB );
  5075. ab.subVectors( pA, pB );
  5076. cb.cross( ab );
  5077. normals[ i ] = cb.x;
  5078. normals[ i + 1 ] = cb.y;
  5079. normals[ i + 2 ] = cb.z;
  5080. normals[ i + 3 ] = cb.x;
  5081. normals[ i + 4 ] = cb.y;
  5082. normals[ i + 5 ] = cb.z;
  5083. normals[ i + 6 ] = cb.x;
  5084. normals[ i + 7 ] = cb.y;
  5085. normals[ i + 8 ] = cb.z;
  5086. }
  5087. }
  5088. this.normalizeNormals();
  5089. this.normalsNeedUpdate = true;
  5090. }
  5091. },
  5092. normalizeNormals: function () {
  5093. var normals = this.attributes[ "normal" ].array;
  5094. var x, y, z, n;
  5095. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5096. x = normals[ i ];
  5097. y = normals[ i + 1 ];
  5098. z = normals[ i + 2 ];
  5099. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5100. normals[ i ] *= n;
  5101. normals[ i + 1 ] *= n;
  5102. normals[ i + 2 ] *= n;
  5103. }
  5104. },
  5105. computeTangents: function () {
  5106. // based on http://www.terathon.com/code/tangent.html
  5107. // (per vertex tangents)
  5108. if ( this.attributes[ "index" ] === undefined ||
  5109. this.attributes[ "position" ] === undefined ||
  5110. this.attributes[ "normal" ] === undefined ||
  5111. this.attributes[ "uv" ] === undefined ) {
  5112. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5113. return;
  5114. }
  5115. var indices = this.attributes[ "index" ].array;
  5116. var positions = this.attributes[ "position" ].array;
  5117. var normals = this.attributes[ "normal" ].array;
  5118. var uvs = this.attributes[ "uv" ].array;
  5119. var nVertices = positions.length / 3;
  5120. if ( this.attributes[ "tangent" ] === undefined ) {
  5121. var nTangentElements = 4 * nVertices;
  5122. this.attributes[ "tangent" ] = {
  5123. itemSize: 4,
  5124. array: new Float32Array( nTangentElements ),
  5125. numItems: nTangentElements
  5126. };
  5127. }
  5128. var tangents = this.attributes[ "tangent" ].array;
  5129. var tan1 = [], tan2 = [];
  5130. for ( var k = 0; k < nVertices; k ++ ) {
  5131. tan1[ k ] = new THREE.Vector3();
  5132. tan2[ k ] = new THREE.Vector3();
  5133. }
  5134. var xA, yA, zA,
  5135. xB, yB, zB,
  5136. xC, yC, zC,
  5137. uA, vA,
  5138. uB, vB,
  5139. uC, vC,
  5140. x1, x2, y1, y2, z1, z2,
  5141. s1, s2, t1, t2, r;
  5142. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5143. function handleTriangle( a, b, c ) {
  5144. xA = positions[ a * 3 ];
  5145. yA = positions[ a * 3 + 1 ];
  5146. zA = positions[ a * 3 + 2 ];
  5147. xB = positions[ b * 3 ];
  5148. yB = positions[ b * 3 + 1 ];
  5149. zB = positions[ b * 3 + 2 ];
  5150. xC = positions[ c * 3 ];
  5151. yC = positions[ c * 3 + 1 ];
  5152. zC = positions[ c * 3 + 2 ];
  5153. uA = uvs[ a * 2 ];
  5154. vA = uvs[ a * 2 + 1 ];
  5155. uB = uvs[ b * 2 ];
  5156. vB = uvs[ b * 2 + 1 ];
  5157. uC = uvs[ c * 2 ];
  5158. vC = uvs[ c * 2 + 1 ];
  5159. x1 = xB - xA;
  5160. x2 = xC - xA;
  5161. y1 = yB - yA;
  5162. y2 = yC - yA;
  5163. z1 = zB - zA;
  5164. z2 = zC - zA;
  5165. s1 = uB - uA;
  5166. s2 = uC - uA;
  5167. t1 = vB - vA;
  5168. t2 = vC - vA;
  5169. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5170. sdir.set(
  5171. ( t2 * x1 - t1 * x2 ) * r,
  5172. ( t2 * y1 - t1 * y2 ) * r,
  5173. ( t2 * z1 - t1 * z2 ) * r
  5174. );
  5175. tdir.set(
  5176. ( s1 * x2 - s2 * x1 ) * r,
  5177. ( s1 * y2 - s2 * y1 ) * r,
  5178. ( s1 * z2 - s2 * z1 ) * r
  5179. );
  5180. tan1[ a ].add( sdir );
  5181. tan1[ b ].add( sdir );
  5182. tan1[ c ].add( sdir );
  5183. tan2[ a ].add( tdir );
  5184. tan2[ b ].add( tdir );
  5185. tan2[ c ].add( tdir );
  5186. }
  5187. var i, il;
  5188. var j, jl;
  5189. var iA, iB, iC;
  5190. var offsets = this.offsets;
  5191. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5192. var start = offsets[ j ].start;
  5193. var count = offsets[ j ].count;
  5194. var index = offsets[ j ].index;
  5195. for ( i = start, il = start + count; i < il; i += 3 ) {
  5196. iA = index + indices[ i ];
  5197. iB = index + indices[ i + 1 ];
  5198. iC = index + indices[ i + 2 ];
  5199. handleTriangle( iA, iB, iC );
  5200. }
  5201. }
  5202. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5203. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5204. var w, t, test;
  5205. function handleVertex( v ) {
  5206. n.x = normals[ v * 3 ];
  5207. n.y = normals[ v * 3 + 1 ];
  5208. n.z = normals[ v * 3 + 2 ];
  5209. n2.copy( n );
  5210. t = tan1[ v ];
  5211. // Gram-Schmidt orthogonalize
  5212. tmp.copy( t );
  5213. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5214. // Calculate handedness
  5215. tmp2.crossVectors( n2, t );
  5216. test = tmp2.dot( tan2[ v ] );
  5217. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5218. tangents[ v * 4 ] = tmp.x;
  5219. tangents[ v * 4 + 1 ] = tmp.y;
  5220. tangents[ v * 4 + 2 ] = tmp.z;
  5221. tangents[ v * 4 + 3 ] = w;
  5222. }
  5223. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5224. var start = offsets[ j ].start;
  5225. var count = offsets[ j ].count;
  5226. var index = offsets[ j ].index;
  5227. for ( i = start, il = start + count; i < il; i += 3 ) {
  5228. iA = index + indices[ i ];
  5229. iB = index + indices[ i + 1 ];
  5230. iC = index + indices[ i + 2 ];
  5231. handleVertex( iA );
  5232. handleVertex( iB );
  5233. handleVertex( iC );
  5234. }
  5235. }
  5236. this.hasTangents = true;
  5237. this.tangentsNeedUpdate = true;
  5238. },
  5239. dispose: function () {
  5240. this.dispatchEvent( { type: 'dispose' } );
  5241. }
  5242. };
  5243. /**
  5244. * @author mrdoob / http://mrdoob.com/
  5245. * @author mikael emtinger / http://gomo.se/
  5246. * @author WestLangley / http://github.com/WestLangley
  5247. */
  5248. THREE.Camera = function () {
  5249. THREE.Object3D.call( this );
  5250. this.matrixWorldInverse = new THREE.Matrix4();
  5251. this.projectionMatrix = new THREE.Matrix4();
  5252. this.projectionMatrixInverse = new THREE.Matrix4();
  5253. };
  5254. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5255. THREE.Camera.prototype.lookAt = function () {
  5256. // This routine does not support cameras with rotated and/or translated parent(s)
  5257. var m1 = new THREE.Matrix4();
  5258. return function ( vector ) {
  5259. m1.lookAt( this.position, vector, this.up );
  5260. if ( this.useQuaternion === true ) {
  5261. this.quaternion.setFromRotationMatrix( m1 );
  5262. } else {
  5263. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  5264. }
  5265. };
  5266. }();
  5267. /**
  5268. * @author alteredq / http://alteredqualia.com/
  5269. */
  5270. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5271. THREE.Camera.call( this );
  5272. this.left = left;
  5273. this.right = right;
  5274. this.top = top;
  5275. this.bottom = bottom;
  5276. this.near = ( near !== undefined ) ? near : 0.1;
  5277. this.far = ( far !== undefined ) ? far : 2000;
  5278. this.updateProjectionMatrix();
  5279. };
  5280. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5281. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5282. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5283. };
  5284. /**
  5285. * @author mrdoob / http://mrdoob.com/
  5286. * @author greggman / http://games.greggman.com/
  5287. * @author zz85 / http://www.lab4games.net/zz85/blog
  5288. */
  5289. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5290. THREE.Camera.call( this );
  5291. this.fov = fov !== undefined ? fov : 50;
  5292. this.aspect = aspect !== undefined ? aspect : 1;
  5293. this.near = near !== undefined ? near : 0.1;
  5294. this.far = far !== undefined ? far : 2000;
  5295. this.updateProjectionMatrix();
  5296. };
  5297. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5298. /**
  5299. * Uses Focal Length (in mm) to estimate and set FOV
  5300. * 35mm (fullframe) camera is used if frame size is not specified;
  5301. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5302. */
  5303. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5304. if ( frameHeight === undefined ) frameHeight = 24;
  5305. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5306. this.updateProjectionMatrix();
  5307. }
  5308. /**
  5309. * Sets an offset in a larger frustum. This is useful for multi-window or
  5310. * multi-monitor/multi-machine setups.
  5311. *
  5312. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5313. * the monitors are in grid like this
  5314. *
  5315. * +---+---+---+
  5316. * | A | B | C |
  5317. * +---+---+---+
  5318. * | D | E | F |
  5319. * +---+---+---+
  5320. *
  5321. * then for each monitor you would call it like this
  5322. *
  5323. * var w = 1920;
  5324. * var h = 1080;
  5325. * var fullWidth = w * 3;
  5326. * var fullHeight = h * 2;
  5327. *
  5328. * --A--
  5329. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5330. * --B--
  5331. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5332. * --C--
  5333. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5334. * --D--
  5335. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5336. * --E--
  5337. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5338. * --F--
  5339. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5340. *
  5341. * Note there is no reason monitors have to be the same size or in a grid.
  5342. */
  5343. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5344. this.fullWidth = fullWidth;
  5345. this.fullHeight = fullHeight;
  5346. this.x = x;
  5347. this.y = y;
  5348. this.width = width;
  5349. this.height = height;
  5350. this.updateProjectionMatrix();
  5351. };
  5352. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5353. if ( this.fullWidth ) {
  5354. var aspect = this.fullWidth / this.fullHeight;
  5355. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5356. var bottom = -top;
  5357. var left = aspect * bottom;
  5358. var right = aspect * top;
  5359. var width = Math.abs( right - left );
  5360. var height = Math.abs( top - bottom );
  5361. this.projectionMatrix.makeFrustum(
  5362. left + this.x * width / this.fullWidth,
  5363. left + ( this.x + this.width ) * width / this.fullWidth,
  5364. top - ( this.y + this.height ) * height / this.fullHeight,
  5365. top - this.y * height / this.fullHeight,
  5366. this.near,
  5367. this.far
  5368. );
  5369. } else {
  5370. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5371. }
  5372. };
  5373. /**
  5374. * @author mrdoob / http://mrdoob.com/
  5375. * @author alteredq / http://alteredqualia.com/
  5376. */
  5377. THREE.Light = function ( hex ) {
  5378. THREE.Object3D.call( this );
  5379. this.color = new THREE.Color( hex );
  5380. };
  5381. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5382. THREE.Light.prototype.clone = function ( light ) {
  5383. if ( light === undefined ) light = new THREE.Light();
  5384. THREE.Object3D.prototype.clone.call( this, light );
  5385. light.color.copy( this.color );
  5386. return light;
  5387. };
  5388. /**
  5389. * @author mrdoob / http://mrdoob.com/
  5390. */
  5391. THREE.AmbientLight = function ( hex ) {
  5392. THREE.Light.call( this, hex );
  5393. };
  5394. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5395. THREE.AmbientLight.prototype.clone = function () {
  5396. var light = new THREE.AmbientLight();
  5397. THREE.Light.prototype.clone.call( this, light );
  5398. return light;
  5399. };
  5400. /**
  5401. * @author MPanknin / http://www.redplant.de/
  5402. * @author alteredq / http://alteredqualia.com/
  5403. */
  5404. THREE.AreaLight = function ( hex, intensity ) {
  5405. THREE.Light.call( this, hex );
  5406. this.normal = new THREE.Vector3( 0, -1, 0 );
  5407. this.right = new THREE.Vector3( 1, 0, 0 );
  5408. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5409. this.width = 1.0;
  5410. this.height = 1.0;
  5411. this.constantAttenuation = 1.5;
  5412. this.linearAttenuation = 0.5;
  5413. this.quadraticAttenuation = 0.1;
  5414. };
  5415. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5416. /**
  5417. * @author mrdoob / http://mrdoob.com/
  5418. * @author alteredq / http://alteredqualia.com/
  5419. */
  5420. THREE.DirectionalLight = function ( hex, intensity ) {
  5421. THREE.Light.call( this, hex );
  5422. this.position.set( 0, 1, 0 );
  5423. this.target = new THREE.Object3D();
  5424. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5425. this.castShadow = false;
  5426. this.onlyShadow = false;
  5427. //
  5428. this.shadowCameraNear = 50;
  5429. this.shadowCameraFar = 5000;
  5430. this.shadowCameraLeft = -500;
  5431. this.shadowCameraRight = 500;
  5432. this.shadowCameraTop = 500;
  5433. this.shadowCameraBottom = -500;
  5434. this.shadowCameraVisible = false;
  5435. this.shadowBias = 0;
  5436. this.shadowDarkness = 0.5;
  5437. this.shadowMapWidth = 512;
  5438. this.shadowMapHeight = 512;
  5439. //
  5440. this.shadowCascade = false;
  5441. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5442. this.shadowCascadeCount = 2;
  5443. this.shadowCascadeBias = [ 0, 0, 0 ];
  5444. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5445. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5446. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5447. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5448. this.shadowCascadeArray = [];
  5449. //
  5450. this.shadowMap = null;
  5451. this.shadowMapSize = null;
  5452. this.shadowCamera = null;
  5453. this.shadowMatrix = null;
  5454. };
  5455. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5456. THREE.DirectionalLight.prototype.clone = function () {
  5457. var light = new THREE.DirectionalLight();
  5458. THREE.Light.prototype.clone.call( this, light );
  5459. light.target = this.target.clone();
  5460. light.intensity = this.intensity;
  5461. light.castShadow = this.castShadow;
  5462. light.onlyShadow = this.onlyShadow;
  5463. return light;
  5464. };
  5465. /**
  5466. * @author alteredq / http://alteredqualia.com/
  5467. */
  5468. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5469. THREE.Light.call( this, skyColorHex );
  5470. this.position.set( 0, 100, 0 );
  5471. this.groundColor = new THREE.Color( groundColorHex );
  5472. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5473. };
  5474. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5475. THREE.HemisphereLight.prototype.clone = function () {
  5476. var light = new THREE.PointLight();
  5477. THREE.Light.prototype.clone.call( this, light );
  5478. light.groundColor.copy( this.groundColor );
  5479. light.intensity = this.intensity;
  5480. return light;
  5481. };
  5482. /**
  5483. * @author mrdoob / http://mrdoob.com/
  5484. */
  5485. THREE.PointLight = function ( hex, intensity, distance ) {
  5486. THREE.Light.call( this, hex );
  5487. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5488. this.distance = ( distance !== undefined ) ? distance : 0;
  5489. };
  5490. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5491. THREE.PointLight.prototype.clone = function () {
  5492. var light = new THREE.PointLight();
  5493. THREE.Light.prototype.clone.call( this, light );
  5494. light.intensity = this.intensity;
  5495. light.distance = this.distance;
  5496. return light;
  5497. };
  5498. /**
  5499. * @author alteredq / http://alteredqualia.com/
  5500. */
  5501. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5502. THREE.Light.call( this, hex );
  5503. this.position.set( 0, 1, 0 );
  5504. this.target = new THREE.Object3D();
  5505. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5506. this.distance = ( distance !== undefined ) ? distance : 0;
  5507. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5508. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5509. this.castShadow = false;
  5510. this.onlyShadow = false;
  5511. //
  5512. this.shadowCameraNear = 50;
  5513. this.shadowCameraFar = 5000;
  5514. this.shadowCameraFov = 50;
  5515. this.shadowCameraVisible = false;
  5516. this.shadowBias = 0;
  5517. this.shadowDarkness = 0.5;
  5518. this.shadowMapWidth = 512;
  5519. this.shadowMapHeight = 512;
  5520. //
  5521. this.shadowMap = null;
  5522. this.shadowMapSize = null;
  5523. this.shadowCamera = null;
  5524. this.shadowMatrix = null;
  5525. };
  5526. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5527. THREE.SpotLight.prototype.clone = function () {
  5528. var light = new THREE.SpotLight();
  5529. THREE.Light.prototype.clone.call( this, light );
  5530. light.target = this.target.clone();
  5531. light.intensity = this.intensity;
  5532. light.distance = this.distance;
  5533. light.angle = this.angle;
  5534. light.exponent = this.exponent;
  5535. light.castShadow = this.castShadow;
  5536. light.onlyShadow = this.onlyShadow;
  5537. return light;
  5538. };
  5539. /**
  5540. * @author alteredq / http://alteredqualia.com/
  5541. */
  5542. THREE.Loader = function ( showStatus ) {
  5543. this.showStatus = showStatus;
  5544. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5545. this.onLoadStart = function () {};
  5546. this.onLoadProgress = function () {};
  5547. this.onLoadComplete = function () {};
  5548. };
  5549. THREE.Loader.prototype = {
  5550. constructor: THREE.Loader,
  5551. crossOrigin: 'anonymous',
  5552. addStatusElement: function () {
  5553. var e = document.createElement( "div" );
  5554. e.style.position = "absolute";
  5555. e.style.right = "0px";
  5556. e.style.top = "0px";
  5557. e.style.fontSize = "0.8em";
  5558. e.style.textAlign = "left";
  5559. e.style.background = "rgba(0,0,0,0.25)";
  5560. e.style.color = "#fff";
  5561. e.style.width = "120px";
  5562. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5563. e.style.zIndex = 1000;
  5564. e.innerHTML = "Loading ...";
  5565. return e;
  5566. },
  5567. updateProgress: function ( progress ) {
  5568. var message = "Loaded ";
  5569. if ( progress.total ) {
  5570. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5571. } else {
  5572. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5573. }
  5574. this.statusDomElement.innerHTML = message;
  5575. },
  5576. extractUrlBase: function ( url ) {
  5577. var parts = url.split( '/' );
  5578. parts.pop();
  5579. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5580. },
  5581. initMaterials: function ( materials, texturePath ) {
  5582. var array = [];
  5583. for ( var i = 0; i < materials.length; ++ i ) {
  5584. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5585. }
  5586. return array;
  5587. },
  5588. needsTangents: function ( materials ) {
  5589. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5590. var m = materials[ i ];
  5591. if ( m instanceof THREE.ShaderMaterial ) return true;
  5592. }
  5593. return false;
  5594. },
  5595. createMaterial: function ( m, texturePath ) {
  5596. var _this = this;
  5597. function is_pow2( n ) {
  5598. var l = Math.log( n ) / Math.LN2;
  5599. return Math.floor( l ) == l;
  5600. }
  5601. function nearest_pow2( n ) {
  5602. var l = Math.log( n ) / Math.LN2;
  5603. return Math.pow( 2, Math.round( l ) );
  5604. }
  5605. function load_image( where, url ) {
  5606. var image = new Image();
  5607. image.onload = function () {
  5608. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5609. var width = nearest_pow2( this.width );
  5610. var height = nearest_pow2( this.height );
  5611. where.image.width = width;
  5612. where.image.height = height;
  5613. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5614. } else {
  5615. where.image = this;
  5616. }
  5617. where.needsUpdate = true;
  5618. };
  5619. image.crossOrigin = _this.crossOrigin;
  5620. image.src = url;
  5621. }
  5622. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5623. var isCompressed = /\.dds$/i.test( sourceFile );
  5624. var fullPath = texturePath + "/" + sourceFile;
  5625. if ( isCompressed ) {
  5626. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5627. where[ name ] = texture;
  5628. } else {
  5629. var texture = document.createElement( 'canvas' );
  5630. where[ name ] = new THREE.Texture( texture );
  5631. }
  5632. where[ name ].sourceFile = sourceFile;
  5633. if( repeat ) {
  5634. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5635. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5636. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5637. }
  5638. if ( offset ) {
  5639. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5640. }
  5641. if ( wrap ) {
  5642. var wrapMap = {
  5643. "repeat": THREE.RepeatWrapping,
  5644. "mirror": THREE.MirroredRepeatWrapping
  5645. }
  5646. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5647. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5648. }
  5649. if ( anisotropy ) {
  5650. where[ name ].anisotropy = anisotropy;
  5651. }
  5652. if ( ! isCompressed ) {
  5653. load_image( where[ name ], fullPath );
  5654. }
  5655. }
  5656. function rgb2hex( rgb ) {
  5657. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5658. }
  5659. // defaults
  5660. var mtype = "MeshLambertMaterial";
  5661. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5662. // parameters from model file
  5663. if ( m.shading ) {
  5664. var shading = m.shading.toLowerCase();
  5665. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5666. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5667. }
  5668. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5669. mpars.blending = THREE[ m.blending ];
  5670. }
  5671. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5672. mpars.transparent = m.transparent;
  5673. }
  5674. if ( m.depthTest !== undefined ) {
  5675. mpars.depthTest = m.depthTest;
  5676. }
  5677. if ( m.depthWrite !== undefined ) {
  5678. mpars.depthWrite = m.depthWrite;
  5679. }
  5680. if ( m.visible !== undefined ) {
  5681. mpars.visible = m.visible;
  5682. }
  5683. if ( m.flipSided !== undefined ) {
  5684. mpars.side = THREE.BackSide;
  5685. }
  5686. if ( m.doubleSided !== undefined ) {
  5687. mpars.side = THREE.DoubleSide;
  5688. }
  5689. if ( m.wireframe !== undefined ) {
  5690. mpars.wireframe = m.wireframe;
  5691. }
  5692. if ( m.vertexColors !== undefined ) {
  5693. if ( m.vertexColors === "face" ) {
  5694. mpars.vertexColors = THREE.FaceColors;
  5695. } else if ( m.vertexColors ) {
  5696. mpars.vertexColors = THREE.VertexColors;
  5697. }
  5698. }
  5699. // colors
  5700. if ( m.colorDiffuse ) {
  5701. mpars.color = rgb2hex( m.colorDiffuse );
  5702. } else if ( m.DbgColor ) {
  5703. mpars.color = m.DbgColor;
  5704. }
  5705. if ( m.colorSpecular ) {
  5706. mpars.specular = rgb2hex( m.colorSpecular );
  5707. }
  5708. if ( m.colorAmbient ) {
  5709. mpars.ambient = rgb2hex( m.colorAmbient );
  5710. }
  5711. // modifiers
  5712. if ( m.transparency ) {
  5713. mpars.opacity = m.transparency;
  5714. }
  5715. if ( m.specularCoef ) {
  5716. mpars.shininess = m.specularCoef;
  5717. }
  5718. // textures
  5719. if ( m.mapDiffuse && texturePath ) {
  5720. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5721. }
  5722. if ( m.mapLight && texturePath ) {
  5723. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5724. }
  5725. if ( m.mapBump && texturePath ) {
  5726. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5727. }
  5728. if ( m.mapNormal && texturePath ) {
  5729. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5730. }
  5731. if ( m.mapSpecular && texturePath ) {
  5732. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5733. }
  5734. //
  5735. if ( m.mapBumpScale ) {
  5736. mpars.bumpScale = m.mapBumpScale;
  5737. }
  5738. // special case for normal mapped material
  5739. if ( m.mapNormal ) {
  5740. var shader = THREE.ShaderLib[ "normalmap" ];
  5741. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5742. uniforms[ "tNormal" ].value = mpars.normalMap;
  5743. if ( m.mapNormalFactor ) {
  5744. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5745. }
  5746. if ( mpars.map ) {
  5747. uniforms[ "tDiffuse" ].value = mpars.map;
  5748. uniforms[ "enableDiffuse" ].value = true;
  5749. }
  5750. if ( mpars.specularMap ) {
  5751. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5752. uniforms[ "enableSpecular" ].value = true;
  5753. }
  5754. if ( mpars.lightMap ) {
  5755. uniforms[ "tAO" ].value = mpars.lightMap;
  5756. uniforms[ "enableAO" ].value = true;
  5757. }
  5758. // for the moment don't handle displacement texture
  5759. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5760. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5761. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5762. uniforms[ "uShininess" ].value = mpars.shininess;
  5763. if ( mpars.opacity !== undefined ) {
  5764. uniforms[ "uOpacity" ].value = mpars.opacity;
  5765. }
  5766. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5767. var material = new THREE.ShaderMaterial( parameters );
  5768. if ( mpars.transparent ) {
  5769. material.transparent = true;
  5770. }
  5771. } else {
  5772. var material = new THREE[ mtype ]( mpars );
  5773. }
  5774. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5775. return material;
  5776. }
  5777. };
  5778. /**
  5779. * @author mrdoob / http://mrdoob.com/
  5780. */
  5781. THREE.ImageLoader = function () {
  5782. this.crossOrigin = null;
  5783. };
  5784. THREE.ImageLoader.prototype = {
  5785. constructor: THREE.ImageLoader,
  5786. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  5787. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  5788. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  5789. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  5790. load: function ( url, image ) {
  5791. var scope = this;
  5792. if ( image === undefined ) image = new Image();
  5793. image.addEventListener( 'load', function () {
  5794. scope.dispatchEvent( { type: 'load', content: image } );
  5795. }, false );
  5796. image.addEventListener( 'error', function () {
  5797. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5798. }, false );
  5799. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5800. image.src = url;
  5801. }
  5802. }
  5803. /**
  5804. * @author mrdoob / http://mrdoob.com/
  5805. * @author alteredq / http://alteredqualia.com/
  5806. */
  5807. THREE.JSONLoader = function ( showStatus ) {
  5808. THREE.Loader.call( this, showStatus );
  5809. this.withCredentials = false;
  5810. };
  5811. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5812. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5813. var scope = this;
  5814. // todo: unify load API to for easier SceneLoader use
  5815. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5816. this.onLoadStart();
  5817. this.loadAjaxJSON( this, url, callback, texturePath );
  5818. };
  5819. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5820. var xhr = new XMLHttpRequest();
  5821. var length = 0;
  5822. xhr.onreadystatechange = function () {
  5823. if ( xhr.readyState === xhr.DONE ) {
  5824. if ( xhr.status === 200 || xhr.status === 0 ) {
  5825. if ( xhr.responseText ) {
  5826. var json = JSON.parse( xhr.responseText );
  5827. var result = context.parse( json, texturePath );
  5828. callback( result.geometry, result.materials );
  5829. } else {
  5830. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5831. }
  5832. // in context of more complex asset initialization
  5833. // do not block on single failed file
  5834. // maybe should go even one more level up
  5835. context.onLoadComplete();
  5836. } else {
  5837. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5838. }
  5839. } else if ( xhr.readyState === xhr.LOADING ) {
  5840. if ( callbackProgress ) {
  5841. if ( length === 0 ) {
  5842. length = xhr.getResponseHeader( "Content-Length" );
  5843. }
  5844. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5845. }
  5846. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5847. if ( callbackProgress !== undefined ) {
  5848. length = xhr.getResponseHeader( "Content-Length" );
  5849. }
  5850. }
  5851. };
  5852. xhr.open( "GET", url, true );
  5853. xhr.withCredentials = this.withCredentials;
  5854. xhr.send( null );
  5855. };
  5856. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  5857. var scope = this,
  5858. geometry = new THREE.Geometry(),
  5859. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5860. parseModel( scale );
  5861. parseSkin();
  5862. parseMorphing( scale );
  5863. geometry.computeCentroids();
  5864. geometry.computeFaceNormals();
  5865. function parseModel( scale ) {
  5866. function isBitSet( value, position ) {
  5867. return value & ( 1 << position );
  5868. }
  5869. var i, j, fi,
  5870. offset, zLength, nVertices,
  5871. colorIndex, normalIndex, uvIndex, materialIndex,
  5872. type,
  5873. isQuad,
  5874. hasMaterial,
  5875. hasFaceUv, hasFaceVertexUv,
  5876. hasFaceNormal, hasFaceVertexNormal,
  5877. hasFaceColor, hasFaceVertexColor,
  5878. vertex, face, color, normal,
  5879. uvLayer, uvs, u, v,
  5880. faces = json.faces,
  5881. vertices = json.vertices,
  5882. normals = json.normals,
  5883. colors = json.colors,
  5884. nUvLayers = 0;
  5885. // disregard empty arrays
  5886. for ( i = 0; i < json.uvs.length; i++ ) {
  5887. if ( json.uvs[ i ].length ) nUvLayers ++;
  5888. }
  5889. for ( i = 0; i < nUvLayers; i++ ) {
  5890. geometry.faceUvs[ i ] = [];
  5891. geometry.faceVertexUvs[ i ] = [];
  5892. }
  5893. offset = 0;
  5894. zLength = vertices.length;
  5895. while ( offset < zLength ) {
  5896. vertex = new THREE.Vector3();
  5897. vertex.x = vertices[ offset ++ ] * scale;
  5898. vertex.y = vertices[ offset ++ ] * scale;
  5899. vertex.z = vertices[ offset ++ ] * scale;
  5900. geometry.vertices.push( vertex );
  5901. }
  5902. offset = 0;
  5903. zLength = faces.length;
  5904. while ( offset < zLength ) {
  5905. type = faces[ offset ++ ];
  5906. isQuad = isBitSet( type, 0 );
  5907. hasMaterial = isBitSet( type, 1 );
  5908. hasFaceUv = isBitSet( type, 2 );
  5909. hasFaceVertexUv = isBitSet( type, 3 );
  5910. hasFaceNormal = isBitSet( type, 4 );
  5911. hasFaceVertexNormal = isBitSet( type, 5 );
  5912. hasFaceColor = isBitSet( type, 6 );
  5913. hasFaceVertexColor = isBitSet( type, 7 );
  5914. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5915. if ( isQuad ) {
  5916. face = new THREE.Face4();
  5917. face.a = faces[ offset ++ ];
  5918. face.b = faces[ offset ++ ];
  5919. face.c = faces[ offset ++ ];
  5920. face.d = faces[ offset ++ ];
  5921. nVertices = 4;
  5922. } else {
  5923. face = new THREE.Face3();
  5924. face.a = faces[ offset ++ ];
  5925. face.b = faces[ offset ++ ];
  5926. face.c = faces[ offset ++ ];
  5927. nVertices = 3;
  5928. }
  5929. if ( hasMaterial ) {
  5930. materialIndex = faces[ offset ++ ];
  5931. face.materialIndex = materialIndex;
  5932. }
  5933. // to get face <=> uv index correspondence
  5934. fi = geometry.faces.length;
  5935. if ( hasFaceUv ) {
  5936. for ( i = 0; i < nUvLayers; i++ ) {
  5937. uvLayer = json.uvs[ i ];
  5938. uvIndex = faces[ offset ++ ];
  5939. u = uvLayer[ uvIndex * 2 ];
  5940. v = uvLayer[ uvIndex * 2 + 1 ];
  5941. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5942. }
  5943. }
  5944. if ( hasFaceVertexUv ) {
  5945. for ( i = 0; i < nUvLayers; i++ ) {
  5946. uvLayer = json.uvs[ i ];
  5947. uvs = [];
  5948. for ( j = 0; j < nVertices; j ++ ) {
  5949. uvIndex = faces[ offset ++ ];
  5950. u = uvLayer[ uvIndex * 2 ];
  5951. v = uvLayer[ uvIndex * 2 + 1 ];
  5952. uvs[ j ] = new THREE.Vector2( u, v );
  5953. }
  5954. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5955. }
  5956. }
  5957. if ( hasFaceNormal ) {
  5958. normalIndex = faces[ offset ++ ] * 3;
  5959. normal = new THREE.Vector3();
  5960. normal.x = normals[ normalIndex ++ ];
  5961. normal.y = normals[ normalIndex ++ ];
  5962. normal.z = normals[ normalIndex ];
  5963. face.normal = normal;
  5964. }
  5965. if ( hasFaceVertexNormal ) {
  5966. for ( i = 0; i < nVertices; i++ ) {
  5967. normalIndex = faces[ offset ++ ] * 3;
  5968. normal = new THREE.Vector3();
  5969. normal.x = normals[ normalIndex ++ ];
  5970. normal.y = normals[ normalIndex ++ ];
  5971. normal.z = normals[ normalIndex ];
  5972. face.vertexNormals.push( normal );
  5973. }
  5974. }
  5975. if ( hasFaceColor ) {
  5976. colorIndex = faces[ offset ++ ];
  5977. color = new THREE.Color( colors[ colorIndex ] );
  5978. face.color = color;
  5979. }
  5980. if ( hasFaceVertexColor ) {
  5981. for ( i = 0; i < nVertices; i++ ) {
  5982. colorIndex = faces[ offset ++ ];
  5983. color = new THREE.Color( colors[ colorIndex ] );
  5984. face.vertexColors.push( color );
  5985. }
  5986. }
  5987. geometry.faces.push( face );
  5988. }
  5989. };
  5990. function parseSkin() {
  5991. var i, l, x, y, z, w, a, b, c, d;
  5992. if ( json.skinWeights ) {
  5993. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5994. x = json.skinWeights[ i ];
  5995. y = json.skinWeights[ i + 1 ];
  5996. z = 0;
  5997. w = 0;
  5998. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5999. }
  6000. }
  6001. if ( json.skinIndices ) {
  6002. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6003. a = json.skinIndices[ i ];
  6004. b = json.skinIndices[ i + 1 ];
  6005. c = 0;
  6006. d = 0;
  6007. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6008. }
  6009. }
  6010. geometry.bones = json.bones;
  6011. geometry.animation = json.animation;
  6012. };
  6013. function parseMorphing( scale ) {
  6014. if ( json.morphTargets !== undefined ) {
  6015. var i, l, v, vl, dstVertices, srcVertices;
  6016. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6017. geometry.morphTargets[ i ] = {};
  6018. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6019. geometry.morphTargets[ i ].vertices = [];
  6020. dstVertices = geometry.morphTargets[ i ].vertices;
  6021. srcVertices = json.morphTargets [ i ].vertices;
  6022. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6023. var vertex = new THREE.Vector3();
  6024. vertex.x = srcVertices[ v ] * scale;
  6025. vertex.y = srcVertices[ v + 1 ] * scale;
  6026. vertex.z = srcVertices[ v + 2 ] * scale;
  6027. dstVertices.push( vertex );
  6028. }
  6029. }
  6030. }
  6031. if ( json.morphColors !== undefined ) {
  6032. var i, l, c, cl, dstColors, srcColors, color;
  6033. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6034. geometry.morphColors[ i ] = {};
  6035. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6036. geometry.morphColors[ i ].colors = [];
  6037. dstColors = geometry.morphColors[ i ].colors;
  6038. srcColors = json.morphColors [ i ].colors;
  6039. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6040. color = new THREE.Color( 0xffaa00 );
  6041. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6042. dstColors.push( color );
  6043. }
  6044. }
  6045. }
  6046. };
  6047. if ( json.materials === undefined ) {
  6048. return { geometry: geometry };
  6049. } else {
  6050. var materials = this.initMaterials( json.materials, texturePath );
  6051. if ( this.needsTangents( materials ) ) {
  6052. geometry.computeTangents();
  6053. }
  6054. return { geometry: geometry, materials: materials };
  6055. }
  6056. };
  6057. /**
  6058. * @author mrdoob / http://mrdoob.com/
  6059. */
  6060. THREE.LoadingMonitor = function () {
  6061. var scope = this;
  6062. var loaded = 0;
  6063. var total = 0;
  6064. var onLoad = function ( event ) {
  6065. loaded ++;
  6066. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  6067. if ( loaded === total ) {
  6068. scope.dispatchEvent( { type: 'load' } );
  6069. }
  6070. };
  6071. this.add = function ( loader ) {
  6072. total ++;
  6073. loader.addEventListener( 'load', onLoad, false );
  6074. };
  6075. };
  6076. THREE.LoadingMonitor.prototype = {
  6077. constructor: THREE.LoadingMonitor,
  6078. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6079. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6080. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6081. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent
  6082. };
  6083. /**
  6084. * @author mrdoob / http://mrdoob.com/
  6085. */
  6086. THREE.GeometryLoader = function () {};
  6087. THREE.GeometryLoader.prototype = {
  6088. constructor: THREE.GeometryLoader,
  6089. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6090. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6091. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6092. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  6093. load: function ( url ) {
  6094. var scope = this;
  6095. var request = new XMLHttpRequest();
  6096. request.addEventListener( 'load', function ( event ) {
  6097. var response = scope.parse( JSON.parse( event.target.responseText ) );
  6098. scope.dispatchEvent( { type: 'load', content: response } );
  6099. }, false );
  6100. request.addEventListener( 'progress', function ( event ) {
  6101. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  6102. }, false );
  6103. request.addEventListener( 'error', function () {
  6104. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6105. }, false );
  6106. request.open( 'GET', url, true );
  6107. request.send( null );
  6108. },
  6109. parse: function ( json ) {
  6110. }
  6111. };
  6112. /**
  6113. * @author mrdoob / http://mrdoob.com/
  6114. */
  6115. THREE.MaterialLoader = function () {};
  6116. THREE.MaterialLoader.prototype = {
  6117. constructor: THREE.MaterialLoader,
  6118. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6119. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6120. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6121. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  6122. load: function ( url ) {
  6123. var scope = this;
  6124. var request = new XMLHttpRequest();
  6125. request.addEventListener( 'load', function ( event ) {
  6126. var response = scope.parse( JSON.parse( event.target.responseText ) );
  6127. scope.dispatchEvent( { type: 'load', content: response } );
  6128. }, false );
  6129. request.addEventListener( 'progress', function ( event ) {
  6130. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  6131. }, false );
  6132. request.addEventListener( 'error', function () {
  6133. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6134. }, false );
  6135. request.open( 'GET', url, true );
  6136. request.send( null );
  6137. },
  6138. parse: function ( json ) {
  6139. var material;
  6140. switch ( json.type ) {
  6141. case 'MeshBasicMaterial':
  6142. material = new THREE.MeshBasicMaterial( {
  6143. color: json.color,
  6144. opacity: json.opacity,
  6145. transparent: json.transparent,
  6146. wireframe: json.wireframe
  6147. } );
  6148. break;
  6149. case 'MeshLambertMaterial':
  6150. material = new THREE.MeshLambertMaterial( {
  6151. color: json.color,
  6152. ambient: json.ambient,
  6153. emissive: json.emissive,
  6154. opacity: json.opacity,
  6155. transparent: json.transparent,
  6156. wireframe: json.wireframe
  6157. } );
  6158. break;
  6159. case 'MeshPhongMaterial':
  6160. material = new THREE.MeshPhongMaterial( {
  6161. color: json.color,
  6162. ambient: json.ambient,
  6163. emissive: json.emissive,
  6164. specular: json.specular,
  6165. shininess: json.shininess,
  6166. opacity: json.opacity,
  6167. transparent: json.transparent,
  6168. wireframe: json.wireframe
  6169. } );
  6170. break;
  6171. case 'MeshNormalMaterial':
  6172. material = new THREE.MeshNormalMaterial( {
  6173. opacity: json.opacity,
  6174. transparent: json.transparent,
  6175. wireframe: json.wireframe
  6176. } );
  6177. break;
  6178. case 'MeshDepthMaterial':
  6179. material = new THREE.MeshDepthMaterial( {
  6180. opacity: json.opacity,
  6181. transparent: json.transparent,
  6182. wireframe: json.wireframe
  6183. } );
  6184. break;
  6185. }
  6186. return material;
  6187. }
  6188. };
  6189. /**
  6190. * @author alteredq / http://alteredqualia.com/
  6191. */
  6192. THREE.SceneLoader = function () {
  6193. this.onLoadStart = function () {};
  6194. this.onLoadProgress = function() {};
  6195. this.onLoadComplete = function () {};
  6196. this.callbackSync = function () {};
  6197. this.callbackProgress = function () {};
  6198. this.geometryHandlerMap = {};
  6199. this.hierarchyHandlerMap = {};
  6200. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6201. };
  6202. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  6203. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  6204. var scope = this;
  6205. var xhr = new XMLHttpRequest();
  6206. xhr.onreadystatechange = function () {
  6207. if ( xhr.readyState === 4 ) {
  6208. if ( xhr.status === 200 || xhr.status === 0 ) {
  6209. var json = JSON.parse( xhr.responseText );
  6210. scope.parse( json, callbackFinished, url );
  6211. } else {
  6212. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6213. }
  6214. }
  6215. };
  6216. xhr.open( "GET", url, true );
  6217. xhr.send( null );
  6218. };
  6219. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  6220. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  6221. };
  6222. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  6223. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  6224. };
  6225. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  6226. var scope = this;
  6227. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6228. var geometry, material, camera, fog,
  6229. texture, images, color,
  6230. light, hex, intensity,
  6231. counter_models, counter_textures,
  6232. total_models, total_textures,
  6233. result;
  6234. var target_array = [];
  6235. var data = json;
  6236. // async geometry loaders
  6237. for ( var typeID in this.geometryHandlerMap ) {
  6238. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  6239. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6240. }
  6241. // async hierachy loaders
  6242. for ( var typeID in this.hierarchyHandlerMap ) {
  6243. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  6244. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6245. }
  6246. counter_models = 0;
  6247. counter_textures = 0;
  6248. result = {
  6249. scene: new THREE.Scene(),
  6250. geometries: {},
  6251. face_materials: {},
  6252. materials: {},
  6253. textures: {},
  6254. objects: {},
  6255. cameras: {},
  6256. lights: {},
  6257. fogs: {},
  6258. empties: {},
  6259. groups: {}
  6260. };
  6261. if ( data.transform ) {
  6262. var position = data.transform.position,
  6263. rotation = data.transform.rotation,
  6264. scale = data.transform.scale;
  6265. if ( position )
  6266. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  6267. if ( rotation )
  6268. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  6269. if ( scale )
  6270. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  6271. if ( position || rotation || scale ) {
  6272. result.scene.updateMatrix();
  6273. result.scene.updateMatrixWorld();
  6274. }
  6275. }
  6276. function get_url( source_url, url_type ) {
  6277. if ( url_type == "relativeToHTML" ) {
  6278. return source_url;
  6279. } else {
  6280. return urlBase + "/" + source_url;
  6281. }
  6282. };
  6283. // toplevel loader function, delegates to handle_children
  6284. function handle_objects() {
  6285. handle_children( result.scene, data.objects );
  6286. }
  6287. // handle all the children from the loaded json and attach them to given parent
  6288. function handle_children( parent, children ) {
  6289. var mat, dst, pos, rot, scl, quat;
  6290. for ( var objID in children ) {
  6291. // check by id if child has already been handled,
  6292. // if not, create new object
  6293. if ( result.objects[ objID ] === undefined ) {
  6294. var objJSON = children[ objID ];
  6295. var object = null;
  6296. // meshes
  6297. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  6298. if ( objJSON.loading === undefined ) {
  6299. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  6300. "position": 1, "rotation": 1, "scale" : 1,
  6301. "visible": 1, "children": 1, "userData": 1,
  6302. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  6303. var loaderParameters = {};
  6304. for ( var parType in objJSON ) {
  6305. if ( ! ( parType in reservedTypes ) ) {
  6306. loaderParameters[ parType ] = objJSON[ parType ];
  6307. }
  6308. }
  6309. material = result.materials[ objJSON.material ];
  6310. objJSON.loading = true;
  6311. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6312. // ColladaLoader
  6313. if ( loader.options ) {
  6314. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6315. // UTF8Loader
  6316. // OBJLoader
  6317. } else {
  6318. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6319. }
  6320. }
  6321. } else if ( objJSON.geometry !== undefined ) {
  6322. geometry = result.geometries[ objJSON.geometry ];
  6323. // geometry already loaded
  6324. if ( geometry ) {
  6325. var needsTangents = false;
  6326. material = result.materials[ objJSON.material ];
  6327. needsTangents = material instanceof THREE.ShaderMaterial;
  6328. pos = objJSON.position;
  6329. rot = objJSON.rotation;
  6330. scl = objJSON.scale;
  6331. mat = objJSON.matrix;
  6332. quat = objJSON.quaternion;
  6333. // use materials from the model file
  6334. // if there is no material specified in the object
  6335. if ( ! objJSON.material ) {
  6336. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6337. }
  6338. // use materials from the model file
  6339. // if there is just empty face material
  6340. // (must create new material as each model has its own face material)
  6341. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6342. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6343. }
  6344. if ( material instanceof THREE.MeshFaceMaterial ) {
  6345. for ( var i = 0; i < material.materials.length; i ++ ) {
  6346. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6347. }
  6348. }
  6349. if ( needsTangents ) {
  6350. geometry.computeTangents();
  6351. }
  6352. if ( objJSON.skin ) {
  6353. object = new THREE.SkinnedMesh( geometry, material );
  6354. } else if ( objJSON.morph ) {
  6355. object = new THREE.MorphAnimMesh( geometry, material );
  6356. if ( objJSON.duration !== undefined ) {
  6357. object.duration = objJSON.duration;
  6358. }
  6359. if ( objJSON.time !== undefined ) {
  6360. object.time = objJSON.time;
  6361. }
  6362. if ( objJSON.mirroredLoop !== undefined ) {
  6363. object.mirroredLoop = objJSON.mirroredLoop;
  6364. }
  6365. if ( material.morphNormals ) {
  6366. geometry.computeMorphNormals();
  6367. }
  6368. } else {
  6369. object = new THREE.Mesh( geometry, material );
  6370. }
  6371. object.name = objID;
  6372. if ( mat ) {
  6373. object.matrixAutoUpdate = false;
  6374. object.matrix.set(
  6375. mat[0], mat[1], mat[2], mat[3],
  6376. mat[4], mat[5], mat[6], mat[7],
  6377. mat[8], mat[9], mat[10], mat[11],
  6378. mat[12], mat[13], mat[14], mat[15]
  6379. );
  6380. } else {
  6381. object.position.set( pos[0], pos[1], pos[2] );
  6382. if ( quat ) {
  6383. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6384. object.useQuaternion = true;
  6385. } else {
  6386. object.rotation.set( rot[0], rot[1], rot[2] );
  6387. }
  6388. object.scale.set( scl[0], scl[1], scl[2] );
  6389. }
  6390. object.visible = objJSON.visible;
  6391. object.castShadow = objJSON.castShadow;
  6392. object.receiveShadow = objJSON.receiveShadow;
  6393. parent.add( object );
  6394. result.objects[ objID ] = object;
  6395. }
  6396. // lights
  6397. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6398. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6399. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6400. if ( objJSON.type === "DirectionalLight" ) {
  6401. pos = objJSON.direction;
  6402. light = new THREE.DirectionalLight( hex, intensity );
  6403. light.position.set( pos[0], pos[1], pos[2] );
  6404. if ( objJSON.target ) {
  6405. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6406. // kill existing default target
  6407. // otherwise it gets added to scene when parent gets added
  6408. light.target = null;
  6409. }
  6410. } else if ( objJSON.type === "PointLight" ) {
  6411. pos = objJSON.position;
  6412. dst = objJSON.distance;
  6413. light = new THREE.PointLight( hex, intensity, dst );
  6414. light.position.set( pos[0], pos[1], pos[2] );
  6415. } else if ( objJSON.type === "AmbientLight" ) {
  6416. light = new THREE.AmbientLight( hex );
  6417. }
  6418. parent.add( light );
  6419. light.name = objID;
  6420. result.lights[ objID ] = light;
  6421. result.objects[ objID ] = light;
  6422. // cameras
  6423. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6424. pos = objJSON.position;
  6425. rot = objJSON.rotation;
  6426. quat = objJSON.quaternion;
  6427. if ( objJSON.type === "PerspectiveCamera" ) {
  6428. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6429. } else if ( objJSON.type === "OrthographicCamera" ) {
  6430. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6431. }
  6432. camera.name = objID;
  6433. camera.position.set( pos[0], pos[1], pos[2] );
  6434. if ( quat !== undefined ) {
  6435. camera.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6436. camera.useQuaternion = true;
  6437. } else if ( rot !== undefined ) {
  6438. camera.rotation.set( rot[0], rot[1], rot[2] );
  6439. }
  6440. parent.add( camera );
  6441. result.cameras[ objID ] = camera;
  6442. result.objects[ objID ] = camera;
  6443. // pure Object3D
  6444. } else {
  6445. pos = objJSON.position;
  6446. rot = objJSON.rotation;
  6447. scl = objJSON.scale;
  6448. quat = objJSON.quaternion;
  6449. object = new THREE.Object3D();
  6450. object.name = objID;
  6451. object.position.set( pos[0], pos[1], pos[2] );
  6452. if ( quat ) {
  6453. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6454. object.useQuaternion = true;
  6455. } else {
  6456. object.rotation.set( rot[0], rot[1], rot[2] );
  6457. }
  6458. object.scale.set( scl[0], scl[1], scl[2] );
  6459. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6460. parent.add( object );
  6461. result.objects[ objID ] = object;
  6462. result.empties[ objID ] = object;
  6463. }
  6464. if ( object ) {
  6465. if ( objJSON.userData !== undefined ) {
  6466. for ( var key in objJSON.userData ) {
  6467. var value = objJSON.userData[ key ];
  6468. object.userData[ key ] = value;
  6469. }
  6470. }
  6471. if ( objJSON.groups !== undefined ) {
  6472. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6473. var groupID = objJSON.groups[ i ];
  6474. if ( result.groups[ groupID ] === undefined ) {
  6475. result.groups[ groupID ] = [];
  6476. }
  6477. result.groups[ groupID ].push( objID );
  6478. }
  6479. }
  6480. if ( objJSON.children !== undefined ) {
  6481. handle_children( object, objJSON.children );
  6482. }
  6483. }
  6484. }
  6485. }
  6486. };
  6487. function handle_mesh( geo, mat, id ) {
  6488. result.geometries[ id ] = geo;
  6489. result.face_materials[ id ] = mat;
  6490. handle_objects();
  6491. };
  6492. function handle_hierarchy( node, id, parent, material, obj ) {
  6493. var p = obj.position;
  6494. var r = obj.rotation;
  6495. var q = obj.quaternion;
  6496. var s = obj.scale;
  6497. node.position.set( p[0], p[1], p[2] );
  6498. if ( q ) {
  6499. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6500. node.useQuaternion = true;
  6501. } else {
  6502. node.rotation.set( r[0], r[1], r[2] );
  6503. }
  6504. node.scale.set( s[0], s[1], s[2] );
  6505. // override children materials
  6506. // if object material was specified in JSON explicitly
  6507. if ( material ) {
  6508. node.traverse( function ( child ) {
  6509. child.material = material;
  6510. } );
  6511. }
  6512. // override children visibility
  6513. // with root node visibility as specified in JSON
  6514. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6515. node.traverse( function ( child ) {
  6516. child.visible = visible;
  6517. } );
  6518. parent.add( node );
  6519. node.name = id;
  6520. result.objects[ id ] = node;
  6521. handle_objects();
  6522. };
  6523. function create_callback_geometry( id ) {
  6524. return function ( geo, mat ) {
  6525. geo.name = id;
  6526. handle_mesh( geo, mat, id );
  6527. counter_models -= 1;
  6528. scope.onLoadComplete();
  6529. async_callback_gate();
  6530. }
  6531. };
  6532. function create_callback_hierachy( id, parent, material, obj ) {
  6533. return function ( event ) {
  6534. var result;
  6535. // loaders which use EventDispatcher
  6536. if ( event.content ) {
  6537. result = event.content;
  6538. // ColladaLoader
  6539. } else if ( event.dae ) {
  6540. result = event.scene;
  6541. // UTF8Loader
  6542. } else {
  6543. result = event;
  6544. }
  6545. handle_hierarchy( result, id, parent, material, obj );
  6546. counter_models -= 1;
  6547. scope.onLoadComplete();
  6548. async_callback_gate();
  6549. }
  6550. };
  6551. function create_callback_embed( id ) {
  6552. return function ( geo, mat ) {
  6553. geo.name = id;
  6554. result.geometries[ id ] = geo;
  6555. result.face_materials[ id ] = mat;
  6556. }
  6557. };
  6558. function async_callback_gate() {
  6559. var progress = {
  6560. totalModels : total_models,
  6561. totalTextures : total_textures,
  6562. loadedModels : total_models - counter_models,
  6563. loadedTextures : total_textures - counter_textures
  6564. };
  6565. scope.callbackProgress( progress, result );
  6566. scope.onLoadProgress();
  6567. if ( counter_models === 0 && counter_textures === 0 ) {
  6568. finalize();
  6569. callbackFinished( result );
  6570. }
  6571. };
  6572. function finalize() {
  6573. // take care of targets which could be asynchronously loaded objects
  6574. for ( var i = 0; i < target_array.length; i ++ ) {
  6575. var ta = target_array[ i ];
  6576. var target = result.objects[ ta.targetName ];
  6577. if ( target ) {
  6578. ta.object.target = target;
  6579. } else {
  6580. // if there was error and target of specified name doesn't exist in the scene file
  6581. // create instead dummy target
  6582. // (target must be added to scene explicitly as parent is already added)
  6583. ta.object.target = new THREE.Object3D();
  6584. result.scene.add( ta.object.target );
  6585. }
  6586. ta.object.target.userData.targetInverse = ta.object;
  6587. }
  6588. };
  6589. var callbackTexture = function ( count ) {
  6590. counter_textures -= count;
  6591. async_callback_gate();
  6592. scope.onLoadComplete();
  6593. };
  6594. // must use this instead of just directly calling callbackTexture
  6595. // because of closure in the calling context loop
  6596. var generateTextureCallback = function ( count ) {
  6597. return function () {
  6598. callbackTexture( count );
  6599. };
  6600. };
  6601. // first go synchronous elements
  6602. // fogs
  6603. var fogID, fogJSON;
  6604. for ( fogID in data.fogs ) {
  6605. fogJSON = data.fogs[ fogID ];
  6606. if ( fogJSON.type === "linear" ) {
  6607. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6608. } else if ( fogJSON.type === "exp2" ) {
  6609. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6610. }
  6611. color = fogJSON.color;
  6612. fog.color.setRGB( color[0], color[1], color[2] );
  6613. result.fogs[ fogID ] = fog;
  6614. }
  6615. // now come potentially asynchronous elements
  6616. // geometries
  6617. // count how many geometries will be loaded asynchronously
  6618. var geoID, geoJSON;
  6619. for ( geoID in data.geometries ) {
  6620. geoJSON = data.geometries[ geoID ];
  6621. if ( geoJSON.type in this.geometryHandlerMap ) {
  6622. counter_models += 1;
  6623. scope.onLoadStart();
  6624. }
  6625. }
  6626. // count how many hierarchies will be loaded asynchronously
  6627. var objID, objJSON;
  6628. for ( objID in data.objects ) {
  6629. objJSON = data.objects[ objID ];
  6630. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6631. counter_models += 1;
  6632. scope.onLoadStart();
  6633. }
  6634. }
  6635. total_models = counter_models;
  6636. for ( geoID in data.geometries ) {
  6637. geoJSON = data.geometries[ geoID ];
  6638. if ( geoJSON.type === "cube" ) {
  6639. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6640. geometry.name = geoID;
  6641. result.geometries[ geoID ] = geometry;
  6642. } else if ( geoJSON.type === "plane" ) {
  6643. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6644. geometry.name = geoID;
  6645. result.geometries[ geoID ] = geometry;
  6646. } else if ( geoJSON.type === "sphere" ) {
  6647. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6648. geometry.name = geoID;
  6649. result.geometries[ geoID ] = geometry;
  6650. } else if ( geoJSON.type === "cylinder" ) {
  6651. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6652. geometry.name = geoID;
  6653. result.geometries[ geoID ] = geometry;
  6654. } else if ( geoJSON.type === "torus" ) {
  6655. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6656. geometry.name = geoID;
  6657. result.geometries[ geoID ] = geometry;
  6658. } else if ( geoJSON.type === "icosahedron" ) {
  6659. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6660. geometry.name = geoID;
  6661. result.geometries[ geoID ] = geometry;
  6662. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6663. var loaderParameters = {};
  6664. for ( var parType in geoJSON ) {
  6665. if ( parType !== "type" && parType !== "url" ) {
  6666. loaderParameters[ parType ] = geoJSON[ parType ];
  6667. }
  6668. }
  6669. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6670. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6671. } else if ( geoJSON.type === "embedded" ) {
  6672. var modelJson = data.embeds[ geoJSON.id ],
  6673. texture_path = "";
  6674. // pass metadata along to jsonLoader so it knows the format version
  6675. modelJson.metadata = data.metadata;
  6676. if ( modelJson ) {
  6677. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6678. var model = jsonLoader.parse( modelJson, texture_path );
  6679. create_callback_embed( geoID )( model.geometry, model.materials );
  6680. }
  6681. }
  6682. }
  6683. // textures
  6684. // count how many textures will be loaded asynchronously
  6685. var textureID, textureJSON;
  6686. for ( textureID in data.textures ) {
  6687. textureJSON = data.textures[ textureID ];
  6688. if ( textureJSON.url instanceof Array ) {
  6689. counter_textures += textureJSON.url.length;
  6690. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6691. scope.onLoadStart();
  6692. }
  6693. } else {
  6694. counter_textures += 1;
  6695. scope.onLoadStart();
  6696. }
  6697. }
  6698. total_textures = counter_textures;
  6699. for ( textureID in data.textures ) {
  6700. textureJSON = data.textures[ textureID ];
  6701. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6702. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6703. }
  6704. if ( textureJSON.url instanceof Array ) {
  6705. var count = textureJSON.url.length;
  6706. var url_array = [];
  6707. for( var i = 0; i < count; i ++ ) {
  6708. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6709. }
  6710. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  6711. if ( isCompressed ) {
  6712. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6713. } else {
  6714. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6715. }
  6716. } else {
  6717. var isCompressed = /\.dds$/i.test( textureJSON.url );
  6718. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6719. var textureCallback = generateTextureCallback( 1 );
  6720. if ( isCompressed ) {
  6721. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6722. } else {
  6723. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6724. }
  6725. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6726. texture.minFilter = THREE[ textureJSON.minFilter ];
  6727. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6728. texture.magFilter = THREE[ textureJSON.magFilter ];
  6729. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6730. if ( textureJSON.repeat ) {
  6731. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6732. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6733. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6734. }
  6735. if ( textureJSON.offset ) {
  6736. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6737. }
  6738. // handle wrap after repeat so that default repeat can be overriden
  6739. if ( textureJSON.wrap ) {
  6740. var wrapMap = {
  6741. "repeat" : THREE.RepeatWrapping,
  6742. "mirror" : THREE.MirroredRepeatWrapping
  6743. }
  6744. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6745. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6746. }
  6747. }
  6748. result.textures[ textureID ] = texture;
  6749. }
  6750. // materials
  6751. var matID, matJSON;
  6752. var parID;
  6753. for ( matID in data.materials ) {
  6754. matJSON = data.materials[ matID ];
  6755. for ( parID in matJSON.parameters ) {
  6756. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6757. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6758. } else if ( parID === "shading" ) {
  6759. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6760. } else if ( parID === "side" ) {
  6761. if ( matJSON.parameters[ parID ] == "double" ) {
  6762. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6763. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6764. matJSON.parameters[ parID ] = THREE.BackSide;
  6765. } else {
  6766. matJSON.parameters[ parID ] = THREE.FrontSide;
  6767. }
  6768. } else if ( parID === "blending" ) {
  6769. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6770. } else if ( parID === "combine" ) {
  6771. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6772. } else if ( parID === "vertexColors" ) {
  6773. if ( matJSON.parameters[ parID ] == "face" ) {
  6774. matJSON.parameters[ parID ] = THREE.FaceColors;
  6775. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6776. } else if ( matJSON.parameters[ parID ] ) {
  6777. matJSON.parameters[ parID ] = THREE.VertexColors;
  6778. }
  6779. } else if ( parID === "wrapRGB" ) {
  6780. var v3 = matJSON.parameters[ parID ];
  6781. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6782. }
  6783. }
  6784. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6785. matJSON.parameters.transparent = true;
  6786. }
  6787. if ( matJSON.parameters.normalMap ) {
  6788. var shader = THREE.ShaderLib[ "normalmap" ];
  6789. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6790. var diffuse = matJSON.parameters.color;
  6791. var specular = matJSON.parameters.specular;
  6792. var ambient = matJSON.parameters.ambient;
  6793. var shininess = matJSON.parameters.shininess;
  6794. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6795. if ( matJSON.parameters.normalScale ) {
  6796. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6797. }
  6798. if ( matJSON.parameters.map ) {
  6799. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6800. uniforms[ "enableDiffuse" ].value = true;
  6801. }
  6802. if ( matJSON.parameters.envMap ) {
  6803. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6804. uniforms[ "enableReflection" ].value = true;
  6805. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6806. }
  6807. if ( matJSON.parameters.lightMap ) {
  6808. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6809. uniforms[ "enableAO" ].value = true;
  6810. }
  6811. if ( matJSON.parameters.specularMap ) {
  6812. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6813. uniforms[ "enableSpecular" ].value = true;
  6814. }
  6815. if ( matJSON.parameters.displacementMap ) {
  6816. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6817. uniforms[ "enableDisplacement" ].value = true;
  6818. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6819. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6820. }
  6821. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6822. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6823. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6824. uniforms[ "uShininess" ].value = shininess;
  6825. if ( matJSON.parameters.opacity ) {
  6826. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6827. }
  6828. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6829. material = new THREE.ShaderMaterial( parameters );
  6830. } else {
  6831. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6832. }
  6833. material.name = matID;
  6834. result.materials[ matID ] = material;
  6835. }
  6836. // second pass through all materials to initialize MeshFaceMaterials
  6837. // that could be referring to other materials out of order
  6838. for ( matID in data.materials ) {
  6839. matJSON = data.materials[ matID ];
  6840. if ( matJSON.parameters.materials ) {
  6841. var materialArray = [];
  6842. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6843. var label = matJSON.parameters.materials[ i ];
  6844. materialArray.push( result.materials[ label ] );
  6845. }
  6846. result.materials[ matID ].materials = materialArray;
  6847. }
  6848. }
  6849. // objects ( synchronous init of procedural primitives )
  6850. handle_objects();
  6851. // defaults
  6852. if ( result.cameras && data.defaults.camera ) {
  6853. result.currentCamera = result.cameras[ data.defaults.camera ];
  6854. }
  6855. if ( result.fogs && data.defaults.fog ) {
  6856. result.scene.fog = result.fogs[ data.defaults.fog ];
  6857. }
  6858. // synchronous callback
  6859. scope.callbackSync( result );
  6860. // just in case there are no async elements
  6861. async_callback_gate();
  6862. };
  6863. /**
  6864. * @author mrdoob / http://mrdoob.com/
  6865. */
  6866. THREE.TextureLoader = function () {
  6867. this.crossOrigin = null;
  6868. };
  6869. THREE.TextureLoader.prototype = {
  6870. constructor: THREE.TextureLoader,
  6871. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6872. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6873. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6874. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  6875. load: function ( url ) {
  6876. var scope = this;
  6877. var image = new Image();
  6878. image.addEventListener( 'load', function () {
  6879. var texture = new THREE.Texture( image );
  6880. texture.needsUpdate = true;
  6881. scope.dispatchEvent( { type: 'load', content: texture } );
  6882. }, false );
  6883. image.addEventListener( 'error', function () {
  6884. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6885. }, false );
  6886. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6887. image.src = url;
  6888. }
  6889. };
  6890. /**
  6891. * @author mrdoob / http://mrdoob.com/
  6892. * @author alteredq / http://alteredqualia.com/
  6893. */
  6894. THREE.Material = function () {
  6895. this.id = THREE.MaterialIdCount ++;
  6896. this.name = '';
  6897. this.side = THREE.FrontSide;
  6898. this.opacity = 1;
  6899. this.transparent = false;
  6900. this.blending = THREE.NormalBlending;
  6901. this.blendSrc = THREE.SrcAlphaFactor;
  6902. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6903. this.blendEquation = THREE.AddEquation;
  6904. this.depthTest = true;
  6905. this.depthWrite = true;
  6906. this.polygonOffset = false;
  6907. this.polygonOffsetFactor = 0;
  6908. this.polygonOffsetUnits = 0;
  6909. this.alphaTest = 0;
  6910. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6911. this.visible = true;
  6912. this.needsUpdate = true;
  6913. };
  6914. THREE.Material.prototype = {
  6915. constructor: THREE.Material,
  6916. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6917. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6918. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6919. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  6920. setValues: function ( values ) {
  6921. if ( values === undefined ) return;
  6922. for ( var key in values ) {
  6923. var newValue = values[ key ];
  6924. if ( newValue === undefined ) {
  6925. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6926. continue;
  6927. }
  6928. if ( key in this ) {
  6929. var currentValue = this[ key ];
  6930. if ( currentValue instanceof THREE.Color ) {
  6931. currentValue.set( newValue );
  6932. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6933. currentValue.copy( newValue );
  6934. } else {
  6935. this[ key ] = newValue;
  6936. }
  6937. }
  6938. }
  6939. },
  6940. clone: function ( material ) {
  6941. if ( material === undefined ) material = new THREE.Material();
  6942. material.name = this.name;
  6943. material.side = this.side;
  6944. material.opacity = this.opacity;
  6945. material.transparent = this.transparent;
  6946. material.blending = this.blending;
  6947. material.blendSrc = this.blendSrc;
  6948. material.blendDst = this.blendDst;
  6949. material.blendEquation = this.blendEquation;
  6950. material.depthTest = this.depthTest;
  6951. material.depthWrite = this.depthWrite;
  6952. material.polygonOffset = this.polygonOffset;
  6953. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6954. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6955. material.alphaTest = this.alphaTest;
  6956. material.overdraw = this.overdraw;
  6957. material.visible = this.visible;
  6958. return material;
  6959. },
  6960. dispose: function () {
  6961. this.dispatchEvent( { type: 'dispose' } );
  6962. }
  6963. };
  6964. THREE.MaterialIdCount = 0;
  6965. /**
  6966. * @author mrdoob / http://mrdoob.com/
  6967. * @author alteredq / http://alteredqualia.com/
  6968. *
  6969. * parameters = {
  6970. * color: <hex>,
  6971. * opacity: <float>,
  6972. *
  6973. * blending: THREE.NormalBlending,
  6974. * depthTest: <bool>,
  6975. * depthWrite: <bool>,
  6976. *
  6977. * linewidth: <float>,
  6978. * linecap: "round",
  6979. * linejoin: "round",
  6980. *
  6981. * vertexColors: <bool>
  6982. *
  6983. * fog: <bool>
  6984. * }
  6985. */
  6986. THREE.LineBasicMaterial = function ( parameters ) {
  6987. THREE.Material.call( this );
  6988. this.color = new THREE.Color( 0xffffff );
  6989. this.linewidth = 1;
  6990. this.linecap = 'round';
  6991. this.linejoin = 'round';
  6992. this.vertexColors = false;
  6993. this.fog = true;
  6994. this.setValues( parameters );
  6995. };
  6996. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6997. THREE.LineBasicMaterial.prototype.clone = function () {
  6998. var material = new THREE.LineBasicMaterial();
  6999. THREE.Material.prototype.clone.call( this, material );
  7000. material.color.copy( this.color );
  7001. material.linewidth = this.linewidth;
  7002. material.linecap = this.linecap;
  7003. material.linejoin = this.linejoin;
  7004. material.vertexColors = this.vertexColors;
  7005. material.fog = this.fog;
  7006. return material;
  7007. };
  7008. /**
  7009. * @author alteredq / http://alteredqualia.com/
  7010. *
  7011. * parameters = {
  7012. * color: <hex>,
  7013. * opacity: <float>,
  7014. *
  7015. * blending: THREE.NormalBlending,
  7016. * depthTest: <bool>,
  7017. * depthWrite: <bool>,
  7018. *
  7019. * linewidth: <float>,
  7020. *
  7021. * scale: <float>,
  7022. * dashSize: <float>,
  7023. * gapSize: <float>,
  7024. *
  7025. * vertexColors: <bool>
  7026. *
  7027. * fog: <bool>
  7028. * }
  7029. */
  7030. THREE.LineDashedMaterial = function ( parameters ) {
  7031. THREE.Material.call( this );
  7032. this.color = new THREE.Color( 0xffffff );
  7033. this.linewidth = 1;
  7034. this.scale = 1;
  7035. this.dashSize = 3;
  7036. this.gapSize = 1;
  7037. this.vertexColors = false;
  7038. this.fog = true;
  7039. this.setValues( parameters );
  7040. };
  7041. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7042. THREE.LineDashedMaterial.prototype.clone = function () {
  7043. var material = new THREE.LineDashedMaterial();
  7044. THREE.Material.prototype.clone.call( this, material );
  7045. material.color.copy( this.color );
  7046. material.linewidth = this.linewidth;
  7047. material.scale = this.scale;
  7048. material.dashSize = this.dashSize;
  7049. material.gapSize = this.gapSize;
  7050. material.vertexColors = this.vertexColors;
  7051. material.fog = this.fog;
  7052. return material;
  7053. };
  7054. /**
  7055. * @author mrdoob / http://mrdoob.com/
  7056. * @author alteredq / http://alteredqualia.com/
  7057. *
  7058. * parameters = {
  7059. * color: <hex>,
  7060. * opacity: <float>,
  7061. * map: new THREE.Texture( <Image> ),
  7062. *
  7063. * lightMap: new THREE.Texture( <Image> ),
  7064. *
  7065. * specularMap: new THREE.Texture( <Image> ),
  7066. *
  7067. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7068. * combine: THREE.Multiply,
  7069. * reflectivity: <float>,
  7070. * refractionRatio: <float>,
  7071. *
  7072. * shading: THREE.SmoothShading,
  7073. * blending: THREE.NormalBlending,
  7074. * depthTest: <bool>,
  7075. * depthWrite: <bool>,
  7076. *
  7077. * wireframe: <boolean>,
  7078. * wireframeLinewidth: <float>,
  7079. *
  7080. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7081. *
  7082. * skinning: <bool>,
  7083. * morphTargets: <bool>,
  7084. *
  7085. * fog: <bool>
  7086. * }
  7087. */
  7088. THREE.MeshBasicMaterial = function ( parameters ) {
  7089. THREE.Material.call( this );
  7090. this.color = new THREE.Color( 0xffffff ); // emissive
  7091. this.map = null;
  7092. this.lightMap = null;
  7093. this.specularMap = null;
  7094. this.envMap = null;
  7095. this.combine = THREE.MultiplyOperation;
  7096. this.reflectivity = 1;
  7097. this.refractionRatio = 0.98;
  7098. this.fog = true;
  7099. this.shading = THREE.SmoothShading;
  7100. this.wireframe = false;
  7101. this.wireframeLinewidth = 1;
  7102. this.wireframeLinecap = 'round';
  7103. this.wireframeLinejoin = 'round';
  7104. this.vertexColors = THREE.NoColors;
  7105. this.skinning = false;
  7106. this.morphTargets = false;
  7107. this.setValues( parameters );
  7108. };
  7109. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7110. THREE.MeshBasicMaterial.prototype.clone = function () {
  7111. var material = new THREE.MeshBasicMaterial();
  7112. THREE.Material.prototype.clone.call( this, material );
  7113. material.color.copy( this.color );
  7114. material.map = this.map;
  7115. material.lightMap = this.lightMap;
  7116. material.specularMap = this.specularMap;
  7117. material.envMap = this.envMap;
  7118. material.combine = this.combine;
  7119. material.reflectivity = this.reflectivity;
  7120. material.refractionRatio = this.refractionRatio;
  7121. material.fog = this.fog;
  7122. material.shading = this.shading;
  7123. material.wireframe = this.wireframe;
  7124. material.wireframeLinewidth = this.wireframeLinewidth;
  7125. material.wireframeLinecap = this.wireframeLinecap;
  7126. material.wireframeLinejoin = this.wireframeLinejoin;
  7127. material.vertexColors = this.vertexColors;
  7128. material.skinning = this.skinning;
  7129. material.morphTargets = this.morphTargets;
  7130. return material;
  7131. };
  7132. /**
  7133. * @author mrdoob / http://mrdoob.com/
  7134. * @author alteredq / http://alteredqualia.com/
  7135. *
  7136. * parameters = {
  7137. * color: <hex>,
  7138. * ambient: <hex>,
  7139. * emissive: <hex>,
  7140. * opacity: <float>,
  7141. *
  7142. * map: new THREE.Texture( <Image> ),
  7143. *
  7144. * lightMap: new THREE.Texture( <Image> ),
  7145. *
  7146. * specularMap: new THREE.Texture( <Image> ),
  7147. *
  7148. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7149. * combine: THREE.Multiply,
  7150. * reflectivity: <float>,
  7151. * refractionRatio: <float>,
  7152. *
  7153. * shading: THREE.SmoothShading,
  7154. * blending: THREE.NormalBlending,
  7155. * depthTest: <bool>,
  7156. * depthWrite: <bool>,
  7157. *
  7158. * wireframe: <boolean>,
  7159. * wireframeLinewidth: <float>,
  7160. *
  7161. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7162. *
  7163. * skinning: <bool>,
  7164. * morphTargets: <bool>,
  7165. * morphNormals: <bool>,
  7166. *
  7167. * fog: <bool>
  7168. * }
  7169. */
  7170. THREE.MeshLambertMaterial = function ( parameters ) {
  7171. THREE.Material.call( this );
  7172. this.color = new THREE.Color( 0xffffff ); // diffuse
  7173. this.ambient = new THREE.Color( 0xffffff );
  7174. this.emissive = new THREE.Color( 0x000000 );
  7175. this.wrapAround = false;
  7176. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7177. this.map = null;
  7178. this.lightMap = null;
  7179. this.specularMap = null;
  7180. this.envMap = null;
  7181. this.combine = THREE.MultiplyOperation;
  7182. this.reflectivity = 1;
  7183. this.refractionRatio = 0.98;
  7184. this.fog = true;
  7185. this.shading = THREE.SmoothShading;
  7186. this.wireframe = false;
  7187. this.wireframeLinewidth = 1;
  7188. this.wireframeLinecap = 'round';
  7189. this.wireframeLinejoin = 'round';
  7190. this.vertexColors = THREE.NoColors;
  7191. this.skinning = false;
  7192. this.morphTargets = false;
  7193. this.morphNormals = false;
  7194. this.setValues( parameters );
  7195. };
  7196. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7197. THREE.MeshLambertMaterial.prototype.clone = function () {
  7198. var material = new THREE.MeshLambertMaterial();
  7199. THREE.Material.prototype.clone.call( this, material );
  7200. material.color.copy( this.color );
  7201. material.ambient.copy( this.ambient );
  7202. material.emissive.copy( this.emissive );
  7203. material.wrapAround = this.wrapAround;
  7204. material.wrapRGB.copy( this.wrapRGB );
  7205. material.map = this.map;
  7206. material.lightMap = this.lightMap;
  7207. material.specularMap = this.specularMap;
  7208. material.envMap = this.envMap;
  7209. material.combine = this.combine;
  7210. material.reflectivity = this.reflectivity;
  7211. material.refractionRatio = this.refractionRatio;
  7212. material.fog = this.fog;
  7213. material.shading = this.shading;
  7214. material.wireframe = this.wireframe;
  7215. material.wireframeLinewidth = this.wireframeLinewidth;
  7216. material.wireframeLinecap = this.wireframeLinecap;
  7217. material.wireframeLinejoin = this.wireframeLinejoin;
  7218. material.vertexColors = this.vertexColors;
  7219. material.skinning = this.skinning;
  7220. material.morphTargets = this.morphTargets;
  7221. material.morphNormals = this.morphNormals;
  7222. return material;
  7223. };
  7224. /**
  7225. * @author mrdoob / http://mrdoob.com/
  7226. * @author alteredq / http://alteredqualia.com/
  7227. *
  7228. * parameters = {
  7229. * color: <hex>,
  7230. * ambient: <hex>,
  7231. * emissive: <hex>,
  7232. * specular: <hex>,
  7233. * shininess: <float>,
  7234. * opacity: <float>,
  7235. *
  7236. * map: new THREE.Texture( <Image> ),
  7237. *
  7238. * lightMap: new THREE.Texture( <Image> ),
  7239. *
  7240. * bumpMap: new THREE.Texture( <Image> ),
  7241. * bumpScale: <float>,
  7242. *
  7243. * normalMap: new THREE.Texture( <Image> ),
  7244. * normalScale: <Vector2>,
  7245. *
  7246. * specularMap: new THREE.Texture( <Image> ),
  7247. *
  7248. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7249. * combine: THREE.Multiply,
  7250. * reflectivity: <float>,
  7251. * refractionRatio: <float>,
  7252. *
  7253. * shading: THREE.SmoothShading,
  7254. * blending: THREE.NormalBlending,
  7255. * depthTest: <bool>,
  7256. * depthWrite: <bool>,
  7257. *
  7258. * wireframe: <boolean>,
  7259. * wireframeLinewidth: <float>,
  7260. *
  7261. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7262. *
  7263. * skinning: <bool>,
  7264. * morphTargets: <bool>,
  7265. * morphNormals: <bool>,
  7266. *
  7267. * fog: <bool>
  7268. * }
  7269. */
  7270. THREE.MeshPhongMaterial = function ( parameters ) {
  7271. THREE.Material.call( this );
  7272. this.color = new THREE.Color( 0xffffff ); // diffuse
  7273. this.ambient = new THREE.Color( 0xffffff );
  7274. this.emissive = new THREE.Color( 0x000000 );
  7275. this.specular = new THREE.Color( 0x111111 );
  7276. this.shininess = 30;
  7277. this.metal = false;
  7278. this.perPixel = true;
  7279. this.wrapAround = false;
  7280. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7281. this.map = null;
  7282. this.lightMap = null;
  7283. this.bumpMap = null;
  7284. this.bumpScale = 1;
  7285. this.normalMap = null;
  7286. this.normalScale = new THREE.Vector2( 1, 1 );
  7287. this.specularMap = null;
  7288. this.envMap = null;
  7289. this.combine = THREE.MultiplyOperation;
  7290. this.reflectivity = 1;
  7291. this.refractionRatio = 0.98;
  7292. this.fog = true;
  7293. this.shading = THREE.SmoothShading;
  7294. this.wireframe = false;
  7295. this.wireframeLinewidth = 1;
  7296. this.wireframeLinecap = 'round';
  7297. this.wireframeLinejoin = 'round';
  7298. this.vertexColors = THREE.NoColors;
  7299. this.skinning = false;
  7300. this.morphTargets = false;
  7301. this.morphNormals = false;
  7302. this.setValues( parameters );
  7303. };
  7304. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7305. THREE.MeshPhongMaterial.prototype.clone = function () {
  7306. var material = new THREE.MeshPhongMaterial();
  7307. THREE.Material.prototype.clone.call( this, material );
  7308. material.color.copy( this.color );
  7309. material.ambient.copy( this.ambient );
  7310. material.emissive.copy( this.emissive );
  7311. material.specular.copy( this.specular );
  7312. material.shininess = this.shininess;
  7313. material.metal = this.metal;
  7314. material.perPixel = this.perPixel;
  7315. material.wrapAround = this.wrapAround;
  7316. material.wrapRGB.copy( this.wrapRGB );
  7317. material.map = this.map;
  7318. material.lightMap = this.lightMap;
  7319. material.bumpMap = this.bumpMap;
  7320. material.bumpScale = this.bumpScale;
  7321. material.normalMap = this.normalMap;
  7322. material.normalScale.copy( this.normalScale );
  7323. material.specularMap = this.specularMap;
  7324. material.envMap = this.envMap;
  7325. material.combine = this.combine;
  7326. material.reflectivity = this.reflectivity;
  7327. material.refractionRatio = this.refractionRatio;
  7328. material.fog = this.fog;
  7329. material.shading = this.shading;
  7330. material.wireframe = this.wireframe;
  7331. material.wireframeLinewidth = this.wireframeLinewidth;
  7332. material.wireframeLinecap = this.wireframeLinecap;
  7333. material.wireframeLinejoin = this.wireframeLinejoin;
  7334. material.vertexColors = this.vertexColors;
  7335. material.skinning = this.skinning;
  7336. material.morphTargets = this.morphTargets;
  7337. material.morphNormals = this.morphNormals;
  7338. return material;
  7339. };
  7340. /**
  7341. * @author mrdoob / http://mrdoob.com/
  7342. * @author alteredq / http://alteredqualia.com/
  7343. *
  7344. * parameters = {
  7345. * opacity: <float>,
  7346. *
  7347. * blending: THREE.NormalBlending,
  7348. * depthTest: <bool>,
  7349. * depthWrite: <bool>,
  7350. *
  7351. * wireframe: <boolean>,
  7352. * wireframeLinewidth: <float>
  7353. * }
  7354. */
  7355. THREE.MeshDepthMaterial = function ( parameters ) {
  7356. THREE.Material.call( this );
  7357. this.wireframe = false;
  7358. this.wireframeLinewidth = 1;
  7359. this.setValues( parameters );
  7360. };
  7361. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7362. THREE.MeshDepthMaterial.prototype.clone = function () {
  7363. var material = new THREE.MeshDepthMaterial();
  7364. THREE.Material.prototype.clone.call( this, material );
  7365. material.wireframe = this.wireframe;
  7366. material.wireframeLinewidth = this.wireframeLinewidth;
  7367. return material;
  7368. };
  7369. /**
  7370. * @author mrdoob / http://mrdoob.com/
  7371. *
  7372. * parameters = {
  7373. * opacity: <float>,
  7374. *
  7375. * shading: THREE.FlatShading,
  7376. * blending: THREE.NormalBlending,
  7377. * depthTest: <bool>,
  7378. * depthWrite: <bool>,
  7379. *
  7380. * wireframe: <boolean>,
  7381. * wireframeLinewidth: <float>
  7382. * }
  7383. */
  7384. THREE.MeshNormalMaterial = function ( parameters ) {
  7385. THREE.Material.call( this, parameters );
  7386. this.shading = THREE.FlatShading;
  7387. this.wireframe = false;
  7388. this.wireframeLinewidth = 1;
  7389. this.morphTargets = false;
  7390. this.setValues( parameters );
  7391. };
  7392. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7393. THREE.MeshNormalMaterial.prototype.clone = function () {
  7394. var material = new THREE.MeshNormalMaterial();
  7395. THREE.Material.prototype.clone.call( this, material );
  7396. material.shading = this.shading;
  7397. material.wireframe = this.wireframe;
  7398. material.wireframeLinewidth = this.wireframeLinewidth;
  7399. return material;
  7400. };
  7401. /**
  7402. * @author mrdoob / http://mrdoob.com/
  7403. */
  7404. THREE.MeshFaceMaterial = function ( materials ) {
  7405. this.materials = materials instanceof Array ? materials : [];
  7406. };
  7407. THREE.MeshFaceMaterial.prototype.clone = function () {
  7408. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7409. };
  7410. /**
  7411. * @author mrdoob / http://mrdoob.com/
  7412. * @author alteredq / http://alteredqualia.com/
  7413. *
  7414. * parameters = {
  7415. * color: <hex>,
  7416. * opacity: <float>,
  7417. * map: new THREE.Texture( <Image> ),
  7418. *
  7419. * size: <float>,
  7420. *
  7421. * blending: THREE.NormalBlending,
  7422. * depthTest: <bool>,
  7423. * depthWrite: <bool>,
  7424. *
  7425. * vertexColors: <bool>,
  7426. *
  7427. * fog: <bool>
  7428. * }
  7429. */
  7430. THREE.ParticleBasicMaterial = function ( parameters ) {
  7431. THREE.Material.call( this );
  7432. this.color = new THREE.Color( 0xffffff );
  7433. this.map = null;
  7434. this.size = 1;
  7435. this.sizeAttenuation = true;
  7436. this.vertexColors = false;
  7437. this.fog = true;
  7438. this.setValues( parameters );
  7439. };
  7440. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7441. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7442. var material = new THREE.ParticleBasicMaterial();
  7443. THREE.Material.prototype.clone.call( this, material );
  7444. material.color.copy( this.color );
  7445. material.map = this.map;
  7446. material.size = this.size;
  7447. material.sizeAttenuation = this.sizeAttenuation;
  7448. material.vertexColors = this.vertexColors;
  7449. material.fog = this.fog;
  7450. return material;
  7451. };
  7452. /**
  7453. * @author mrdoob / http://mrdoob.com/
  7454. *
  7455. * parameters = {
  7456. * color: <hex>,
  7457. * program: <function>,
  7458. * opacity: <float>,
  7459. * blending: THREE.NormalBlending
  7460. * }
  7461. */
  7462. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7463. THREE.Material.call( this );
  7464. this.color = new THREE.Color( 0xffffff );
  7465. this.program = function ( context, color ) {};
  7466. this.setValues( parameters );
  7467. };
  7468. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7469. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7470. var material = new THREE.ParticleCanvasMaterial();
  7471. THREE.Material.prototype.clone.call( this, material );
  7472. material.color.copy( this.color );
  7473. material.program = this.program;
  7474. return material;
  7475. };
  7476. /**
  7477. * @author alteredq / http://alteredqualia.com/
  7478. *
  7479. * parameters = {
  7480. * fragmentShader: <string>,
  7481. * vertexShader: <string>,
  7482. *
  7483. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7484. *
  7485. * defines: { "label" : "value" },
  7486. *
  7487. * shading: THREE.SmoothShading,
  7488. * blending: THREE.NormalBlending,
  7489. * depthTest: <bool>,
  7490. * depthWrite: <bool>,
  7491. *
  7492. * wireframe: <boolean>,
  7493. * wireframeLinewidth: <float>,
  7494. *
  7495. * lights: <bool>,
  7496. *
  7497. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7498. *
  7499. * skinning: <bool>,
  7500. * morphTargets: <bool>,
  7501. * morphNormals: <bool>,
  7502. *
  7503. * fog: <bool>
  7504. * }
  7505. */
  7506. THREE.ShaderMaterial = function ( parameters ) {
  7507. THREE.Material.call( this );
  7508. this.fragmentShader = "void main() {}";
  7509. this.vertexShader = "void main() {}";
  7510. this.uniforms = {};
  7511. this.defines = {};
  7512. this.attributes = null;
  7513. this.shading = THREE.SmoothShading;
  7514. this.linewidth = 1;
  7515. this.wireframe = false;
  7516. this.wireframeLinewidth = 1;
  7517. this.fog = false; // set to use scene fog
  7518. this.lights = false; // set to use scene lights
  7519. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7520. this.skinning = false; // set to use skinning attribute streams
  7521. this.morphTargets = false; // set to use morph targets
  7522. this.morphNormals = false; // set to use morph normals
  7523. this.setValues( parameters );
  7524. };
  7525. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7526. THREE.ShaderMaterial.prototype.clone = function () {
  7527. var material = new THREE.ShaderMaterial();
  7528. THREE.Material.prototype.clone.call( this, material );
  7529. material.fragmentShader = this.fragmentShader;
  7530. material.vertexShader = this.vertexShader;
  7531. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7532. material.attributes = this.attributes;
  7533. material.defines = this.defines;
  7534. material.shading = this.shading;
  7535. material.wireframe = this.wireframe;
  7536. material.wireframeLinewidth = this.wireframeLinewidth;
  7537. material.fog = this.fog;
  7538. material.lights = this.lights;
  7539. material.vertexColors = this.vertexColors;
  7540. material.skinning = this.skinning;
  7541. material.morphTargets = this.morphTargets;
  7542. material.morphNormals = this.morphNormals;
  7543. return material;
  7544. };
  7545. /**
  7546. * @author alteredq / http://alteredqualia.com/
  7547. *
  7548. * parameters = {
  7549. * color: <hex>,
  7550. * opacity: <float>,
  7551. * map: new THREE.Texture( <Image> ),
  7552. *
  7553. * blending: THREE.NormalBlending,
  7554. * depthTest: <bool>,
  7555. * depthWrite: <bool>,
  7556. *
  7557. * useScreenCoordinates: <bool>,
  7558. * sizeAttenuation: <bool>,
  7559. * scaleByViewport: <bool>,
  7560. * alignment: THREE.SpriteAlignment.center,
  7561. *
  7562. * uvOffset: new THREE.Vector2(),
  7563. * uvScale: new THREE.Vector2(),
  7564. *
  7565. * fog: <bool>
  7566. * }
  7567. */
  7568. THREE.SpriteMaterial = function ( parameters ) {
  7569. THREE.Material.call( this );
  7570. // defaults
  7571. this.color = new THREE.Color( 0xffffff );
  7572. this.map = new THREE.Texture();
  7573. this.useScreenCoordinates = true;
  7574. this.depthTest = !this.useScreenCoordinates;
  7575. this.sizeAttenuation = !this.useScreenCoordinates;
  7576. this.scaleByViewport = !this.sizeAttenuation;
  7577. this.alignment = THREE.SpriteAlignment.center.clone();
  7578. this.fog = false;
  7579. this.uvOffset = new THREE.Vector2( 0, 0 );
  7580. this.uvScale = new THREE.Vector2( 1, 1 );
  7581. // set parameters
  7582. this.setValues( parameters );
  7583. // override coupled defaults if not specified explicitly by parameters
  7584. parameters = parameters || {};
  7585. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7586. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7587. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7588. };
  7589. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7590. THREE.SpriteMaterial.prototype.clone = function () {
  7591. var material = new THREE.SpriteMaterial();
  7592. THREE.Material.prototype.clone.call( this, material );
  7593. material.color.copy( this.color );
  7594. material.map = this.map;
  7595. material.useScreenCoordinates = this.useScreenCoordinates;
  7596. material.sizeAttenuation = this.sizeAttenuation;
  7597. material.scaleByViewport = this.scaleByViewport;
  7598. material.alignment.copy( this.alignment );
  7599. material.uvOffset.copy( this.uvOffset );
  7600. material.uvScale.copy( this.uvScale );
  7601. material.fog = this.fog;
  7602. return material;
  7603. };
  7604. // Alignment enums
  7605. THREE.SpriteAlignment = {};
  7606. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7607. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7608. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7609. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7610. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7611. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7612. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7613. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7614. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7615. /**
  7616. * @author mrdoob / http://mrdoob.com/
  7617. * @author alteredq / http://alteredqualia.com/
  7618. * @author szimek / https://github.com/szimek/
  7619. */
  7620. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7621. this.id = THREE.TextureIdCount ++;
  7622. this.name = '';
  7623. this.image = image;
  7624. this.mipmaps = [];
  7625. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7626. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7627. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7628. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7629. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7630. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7631. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7632. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7633. this.offset = new THREE.Vector2( 0, 0 );
  7634. this.repeat = new THREE.Vector2( 1, 1 );
  7635. this.generateMipmaps = true;
  7636. this.premultiplyAlpha = false;
  7637. this.flipY = true;
  7638. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7639. this.needsUpdate = false;
  7640. this.onUpdate = null;
  7641. };
  7642. THREE.Texture.prototype = {
  7643. constructor: THREE.Texture,
  7644. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  7645. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  7646. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  7647. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  7648. clone: function ( texture ) {
  7649. if ( texture === undefined ) texture = new THREE.Texture();
  7650. texture.image = this.image;
  7651. texture.mipmaps = this.mipmaps.slice(0);
  7652. texture.mapping = this.mapping;
  7653. texture.wrapS = this.wrapS;
  7654. texture.wrapT = this.wrapT;
  7655. texture.magFilter = this.magFilter;
  7656. texture.minFilter = this.minFilter;
  7657. texture.anisotropy = this.anisotropy;
  7658. texture.format = this.format;
  7659. texture.type = this.type;
  7660. texture.offset.copy( this.offset );
  7661. texture.repeat.copy( this.repeat );
  7662. texture.generateMipmaps = this.generateMipmaps;
  7663. texture.premultiplyAlpha = this.premultiplyAlpha;
  7664. texture.flipY = this.flipY;
  7665. texture.unpackAlignment = this.unpackAlignment;
  7666. return texture;
  7667. },
  7668. dispose: function () {
  7669. this.dispatchEvent( { type: 'dispose' } );
  7670. }
  7671. };
  7672. THREE.TextureIdCount = 0;
  7673. /**
  7674. * @author alteredq / http://alteredqualia.com/
  7675. */
  7676. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7677. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7678. this.image = { width: width, height: height };
  7679. this.mipmaps = mipmaps;
  7680. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7681. };
  7682. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7683. THREE.CompressedTexture.prototype.clone = function () {
  7684. var texture = new THREE.CompressedTexture();
  7685. THREE.Texture.prototype.clone.call( this, texture );
  7686. return texture;
  7687. };
  7688. /**
  7689. * @author alteredq / http://alteredqualia.com/
  7690. */
  7691. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7692. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7693. this.image = { data: data, width: width, height: height };
  7694. };
  7695. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7696. THREE.DataTexture.prototype.clone = function () {
  7697. var texture = new THREE.DataTexture();
  7698. THREE.Texture.prototype.clone.call( this, texture );
  7699. return texture;
  7700. };
  7701. /**
  7702. * @author mrdoob / http://mrdoob.com/
  7703. */
  7704. THREE.Particle = function ( material ) {
  7705. THREE.Object3D.call( this );
  7706. this.material = material;
  7707. };
  7708. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7709. THREE.Particle.prototype.clone = function ( object ) {
  7710. if ( object === undefined ) object = new THREE.Particle( this.material );
  7711. THREE.Object3D.prototype.clone.call( this, object );
  7712. return object;
  7713. };
  7714. /**
  7715. * @author alteredq / http://alteredqualia.com/
  7716. */
  7717. THREE.ParticleSystem = function ( geometry, material ) {
  7718. THREE.Object3D.call( this );
  7719. this.geometry = geometry;
  7720. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7721. this.sortParticles = false;
  7722. if ( this.geometry ) {
  7723. // calc bound radius
  7724. if( this.geometry.boundingSphere === null ) {
  7725. this.geometry.computeBoundingSphere();
  7726. }
  7727. }
  7728. this.frustumCulled = false;
  7729. };
  7730. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7731. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7732. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7733. object.sortParticles = this.sortParticles;
  7734. THREE.Object3D.prototype.clone.call( this, object );
  7735. return object;
  7736. };
  7737. /**
  7738. * @author mrdoob / http://mrdoob.com/
  7739. */
  7740. THREE.Line = function ( geometry, material, type ) {
  7741. THREE.Object3D.call( this );
  7742. this.geometry = geometry;
  7743. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7744. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7745. if ( this.geometry ) {
  7746. if ( ! this.geometry.boundingSphere ) {
  7747. this.geometry.computeBoundingSphere();
  7748. }
  7749. }
  7750. };
  7751. THREE.LineStrip = 0;
  7752. THREE.LinePieces = 1;
  7753. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7754. THREE.Line.prototype.clone = function ( object ) {
  7755. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7756. THREE.Object3D.prototype.clone.call( this, object );
  7757. return object;
  7758. };
  7759. /**
  7760. * @author mrdoob / http://mrdoob.com/
  7761. * @author alteredq / http://alteredqualia.com/
  7762. * @author mikael emtinger / http://gomo.se/
  7763. * @author jonobr1 / http://jonobr1.com/
  7764. */
  7765. THREE.Mesh = function ( geometry, material ) {
  7766. THREE.Object3D.call( this );
  7767. this.geometry = null;
  7768. this.material = null;
  7769. this.setGeometry( geometry );
  7770. this.setMaterial( material );
  7771. };
  7772. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7773. THREE.Mesh.prototype.setGeometry = function ( geometry ) {
  7774. if ( geometry !== undefined ) {
  7775. this.geometry = geometry;
  7776. if ( this.geometry.boundingSphere === null ) {
  7777. this.geometry.computeBoundingSphere();
  7778. }
  7779. this.updateMorphTargets();
  7780. }
  7781. };
  7782. THREE.Mesh.prototype.setMaterial = function ( material ) {
  7783. if ( material !== undefined ) {
  7784. this.material = material;
  7785. } else {
  7786. this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7787. }
  7788. };
  7789. THREE.Mesh.prototype.updateMorphTargets = function () {
  7790. if ( this.geometry.morphTargets.length > 0 ) {
  7791. this.morphTargetBase = -1;
  7792. this.morphTargetForcedOrder = [];
  7793. this.morphTargetInfluences = [];
  7794. this.morphTargetDictionary = {};
  7795. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  7796. this.morphTargetInfluences.push( 0 );
  7797. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7798. }
  7799. }
  7800. };
  7801. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7802. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7803. return this.morphTargetDictionary[ name ];
  7804. }
  7805. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7806. return 0;
  7807. };
  7808. THREE.Mesh.prototype.clone = function ( object ) {
  7809. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7810. THREE.Object3D.prototype.clone.call( this, object );
  7811. return object;
  7812. };
  7813. /**
  7814. * @author mikael emtinger / http://gomo.se/
  7815. * @author alteredq / http://alteredqualia.com/
  7816. */
  7817. THREE.Bone = function( belongsToSkin ) {
  7818. THREE.Object3D.call( this );
  7819. this.skin = belongsToSkin;
  7820. this.skinMatrix = new THREE.Matrix4();
  7821. };
  7822. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7823. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7824. // update local
  7825. if ( this.matrixAutoUpdate ) {
  7826. forceUpdate |= this.updateMatrix();
  7827. }
  7828. // update skin matrix
  7829. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7830. if( parentSkinMatrix ) {
  7831. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7832. } else {
  7833. this.skinMatrix.copy( this.matrix );
  7834. }
  7835. this.matrixWorldNeedsUpdate = false;
  7836. forceUpdate = true;
  7837. }
  7838. // update children
  7839. var child, i, l = this.children.length;
  7840. for ( i = 0; i < l; i ++ ) {
  7841. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7842. }
  7843. };
  7844. /**
  7845. * @author mikael emtinger / http://gomo.se/
  7846. * @author alteredq / http://alteredqualia.com/
  7847. */
  7848. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7849. THREE.Mesh.call( this, geometry, material );
  7850. //
  7851. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7852. // init bones
  7853. this.identityMatrix = new THREE.Matrix4();
  7854. this.bones = [];
  7855. this.boneMatrices = [];
  7856. var b, bone, gbone, p, q, s;
  7857. if ( this.geometry && this.geometry.bones !== undefined ) {
  7858. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7859. gbone = this.geometry.bones[ b ];
  7860. p = gbone.pos;
  7861. q = gbone.rotq;
  7862. s = gbone.scl;
  7863. bone = this.addBone();
  7864. bone.name = gbone.name;
  7865. bone.position.set( p[0], p[1], p[2] );
  7866. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7867. bone.useQuaternion = true;
  7868. if ( s !== undefined ) {
  7869. bone.scale.set( s[0], s[1], s[2] );
  7870. } else {
  7871. bone.scale.set( 1, 1, 1 );
  7872. }
  7873. }
  7874. for ( b = 0; b < this.bones.length; b ++ ) {
  7875. gbone = this.geometry.bones[ b ];
  7876. bone = this.bones[ b ];
  7877. if ( gbone.parent === -1 ) {
  7878. this.add( bone );
  7879. } else {
  7880. this.bones[ gbone.parent ].add( bone );
  7881. }
  7882. }
  7883. //
  7884. var nBones = this.bones.length;
  7885. if ( this.useVertexTexture ) {
  7886. // layout (1 matrix = 4 pixels)
  7887. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7888. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7889. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7890. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7891. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7892. var size;
  7893. if ( nBones > 256 )
  7894. size = 64;
  7895. else if ( nBones > 64 )
  7896. size = 32;
  7897. else if ( nBones > 16 )
  7898. size = 16;
  7899. else
  7900. size = 8;
  7901. this.boneTextureWidth = size;
  7902. this.boneTextureHeight = size;
  7903. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7904. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7905. this.boneTexture.minFilter = THREE.NearestFilter;
  7906. this.boneTexture.magFilter = THREE.NearestFilter;
  7907. this.boneTexture.generateMipmaps = false;
  7908. this.boneTexture.flipY = false;
  7909. } else {
  7910. this.boneMatrices = new Float32Array( 16 * nBones );
  7911. }
  7912. this.pose();
  7913. }
  7914. };
  7915. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7916. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7917. if ( bone === undefined ) {
  7918. bone = new THREE.Bone( this );
  7919. }
  7920. this.bones.push( bone );
  7921. return bone;
  7922. };
  7923. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7924. this.matrixAutoUpdate && this.updateMatrix();
  7925. // update matrixWorld
  7926. if ( this.matrixWorldNeedsUpdate || force ) {
  7927. if ( this.parent ) {
  7928. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  7929. } else {
  7930. this.matrixWorld.copy( this.matrix );
  7931. }
  7932. this.matrixWorldNeedsUpdate = false;
  7933. force = true;
  7934. }
  7935. // update children
  7936. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7937. var child = this.children[ i ];
  7938. if ( child instanceof THREE.Bone ) {
  7939. child.update( this.identityMatrix, false );
  7940. } else {
  7941. child.updateMatrixWorld( true );
  7942. }
  7943. }
  7944. // make a snapshot of the bones' rest position
  7945. if ( this.boneInverses == undefined ) {
  7946. this.boneInverses = [];
  7947. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7948. var inverse = new THREE.Matrix4();
  7949. inverse.getInverse( this.bones[ b ].skinMatrix );
  7950. this.boneInverses.push( inverse );
  7951. }
  7952. }
  7953. // flatten bone matrices to array
  7954. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7955. // compute the offset between the current and the original transform;
  7956. //TODO: we could get rid of this multiplication step if the skinMatrix
  7957. // was already representing the offset; however, this requires some
  7958. // major changes to the animation system
  7959. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7960. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7961. }
  7962. if ( this.useVertexTexture ) {
  7963. this.boneTexture.needsUpdate = true;
  7964. }
  7965. };
  7966. THREE.SkinnedMesh.prototype.pose = function () {
  7967. this.updateMatrixWorld( true );
  7968. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7969. // normalize weights
  7970. var sw = this.geometry.skinWeights[ i ];
  7971. var scale = 1.0 / sw.lengthManhattan();
  7972. if ( scale !== Infinity ) {
  7973. sw.multiplyScalar( scale );
  7974. } else {
  7975. sw.set( 1 ); // this will be normalized by the shader anyway
  7976. }
  7977. }
  7978. };
  7979. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7980. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7981. THREE.Mesh.prototype.clone.call( this, object );
  7982. return object;
  7983. };
  7984. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7985. /**
  7986. * @author alteredq / http://alteredqualia.com/
  7987. */
  7988. THREE.MorphAnimMesh = function ( geometry, material ) {
  7989. THREE.Mesh.call( this, geometry, material );
  7990. // API
  7991. this.duration = 1000; // milliseconds
  7992. this.mirroredLoop = false;
  7993. this.time = 0;
  7994. // internals
  7995. this.lastKeyframe = 0;
  7996. this.currentKeyframe = 0;
  7997. this.direction = 1;
  7998. this.directionBackwards = false;
  7999. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8000. };
  8001. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8002. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8003. this.startKeyframe = start;
  8004. this.endKeyframe = end;
  8005. this.length = this.endKeyframe - this.startKeyframe + 1;
  8006. };
  8007. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8008. this.direction = 1;
  8009. this.directionBackwards = false;
  8010. };
  8011. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8012. this.direction = -1;
  8013. this.directionBackwards = true;
  8014. };
  8015. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8016. var geometry = this.geometry;
  8017. if ( ! geometry.animations ) geometry.animations = {};
  8018. var firstAnimation, animations = geometry.animations;
  8019. var pattern = /([a-z]+)(\d+)/;
  8020. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8021. var morph = geometry.morphTargets[ i ];
  8022. var parts = morph.name.match( pattern );
  8023. if ( parts && parts.length > 1 ) {
  8024. var label = parts[ 1 ];
  8025. var num = parts[ 2 ];
  8026. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8027. var animation = animations[ label ];
  8028. if ( i < animation.start ) animation.start = i;
  8029. if ( i > animation.end ) animation.end = i;
  8030. if ( ! firstAnimation ) firstAnimation = label;
  8031. }
  8032. }
  8033. geometry.firstAnimation = firstAnimation;
  8034. };
  8035. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8036. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8037. this.geometry.animations[ label ] = { start: start, end: end };
  8038. };
  8039. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8040. var animation = this.geometry.animations[ label ];
  8041. if ( animation ) {
  8042. this.setFrameRange( animation.start, animation.end );
  8043. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8044. this.time = 0;
  8045. } else {
  8046. console.warn( "animation[" + label + "] undefined" );
  8047. }
  8048. };
  8049. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8050. var frameTime = this.duration / this.length;
  8051. this.time += this.direction * delta;
  8052. if ( this.mirroredLoop ) {
  8053. if ( this.time > this.duration || this.time < 0 ) {
  8054. this.direction *= -1;
  8055. if ( this.time > this.duration ) {
  8056. this.time = this.duration;
  8057. this.directionBackwards = true;
  8058. }
  8059. if ( this.time < 0 ) {
  8060. this.time = 0;
  8061. this.directionBackwards = false;
  8062. }
  8063. }
  8064. } else {
  8065. this.time = this.time % this.duration;
  8066. if ( this.time < 0 ) this.time += this.duration;
  8067. }
  8068. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8069. if ( keyframe !== this.currentKeyframe ) {
  8070. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8071. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8072. this.morphTargetInfluences[ keyframe ] = 0;
  8073. this.lastKeyframe = this.currentKeyframe;
  8074. this.currentKeyframe = keyframe;
  8075. }
  8076. var mix = ( this.time % frameTime ) / frameTime;
  8077. if ( this.directionBackwards ) {
  8078. mix = 1 - mix;
  8079. }
  8080. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8081. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8082. };
  8083. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8084. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8085. object.duration = this.duration;
  8086. object.mirroredLoop = this.mirroredLoop;
  8087. object.time = this.time;
  8088. object.lastKeyframe = this.lastKeyframe;
  8089. object.currentKeyframe = this.currentKeyframe;
  8090. object.direction = this.direction;
  8091. object.directionBackwards = this.directionBackwards;
  8092. THREE.Mesh.prototype.clone.call( this, object );
  8093. return object;
  8094. };
  8095. /**
  8096. * @author alteredq / http://alteredqualia.com/
  8097. */
  8098. THREE.Ribbon = function ( geometry, material ) {
  8099. THREE.Object3D.call( this );
  8100. this.geometry = geometry;
  8101. this.material = material;
  8102. };
  8103. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  8104. THREE.Ribbon.prototype.clone = function ( object ) {
  8105. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  8106. THREE.Object3D.prototype.clone.call( this, object );
  8107. return object;
  8108. };
  8109. /**
  8110. * @author mikael emtinger / http://gomo.se/
  8111. * @author alteredq / http://alteredqualia.com/
  8112. * @author mrdoob / http://mrdoob.com/
  8113. */
  8114. THREE.LOD = function () {
  8115. THREE.Object3D.call( this );
  8116. this.objects = [];
  8117. };
  8118. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8119. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8120. if ( distance === undefined ) distance = 0;
  8121. distance = Math.abs( distance );
  8122. for ( var l = 0; l < this.objects.length; l ++ ) {
  8123. if ( distance < this.objects[ l ].distance ) {
  8124. break;
  8125. }
  8126. }
  8127. this.objects.splice( l, 0, { distance: distance, object: object } );
  8128. this.add( object );
  8129. };
  8130. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8131. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8132. if ( distance < this.objects[ i ].distance ) {
  8133. break;
  8134. }
  8135. }
  8136. return this.objects[ i - 1 ].object;
  8137. };
  8138. THREE.LOD.prototype.update = function () {
  8139. var v1 = new THREE.Vector3();
  8140. var v2 = new THREE.Vector3();
  8141. return function ( camera ) {
  8142. if ( this.objects.length > 1 ) {
  8143. v1.getPositionFromMatrix( camera.matrixWorld );
  8144. v2.getPositionFromMatrix( this.matrixWorld );
  8145. var distance = v1.distanceTo( v2 );
  8146. this.objects[ 0 ].object.visible = true;
  8147. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8148. if ( distance >= this.objects[ i ].distance ) {
  8149. this.objects[ i - 1 ].object.visible = false;
  8150. this.objects[ i ].object.visible = true;
  8151. } else {
  8152. break;
  8153. }
  8154. }
  8155. for( ; i < l; i ++ ) {
  8156. this.objects[ i ].object.visible = false;
  8157. }
  8158. }
  8159. };
  8160. }();
  8161. THREE.LOD.prototype.clone = function () {
  8162. // TODO
  8163. };
  8164. /**
  8165. * @author mikael emtinger / http://gomo.se/
  8166. * @author alteredq / http://alteredqualia.com/
  8167. */
  8168. THREE.Sprite = function ( material ) {
  8169. THREE.Object3D.call( this );
  8170. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8171. this.rotation3d = this.rotation;
  8172. this.rotation = 0;
  8173. };
  8174. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8175. /*
  8176. * Custom update matrix
  8177. */
  8178. THREE.Sprite.prototype.updateMatrix = function () {
  8179. this.rotation3d.set( 0, 0, this.rotation );
  8180. this.quaternion.setFromEuler( this.rotation3d, this.eulerOrder );
  8181. this.matrix.makeFromPositionQuaternionScale( this.position, this.quaternion, this.scale );
  8182. this.matrixWorldNeedsUpdate = true;
  8183. };
  8184. THREE.Sprite.prototype.clone = function ( object ) {
  8185. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8186. THREE.Object3D.prototype.clone.call( this, object );
  8187. return object;
  8188. };
  8189. /**
  8190. * @author mrdoob / http://mrdoob.com/
  8191. */
  8192. THREE.Scene = function () {
  8193. THREE.Object3D.call( this );
  8194. this.fog = null;
  8195. this.overrideMaterial = null;
  8196. this.autoUpdate = true; // checked by the renderer
  8197. this.matrixAutoUpdate = false;
  8198. this.__objects = [];
  8199. this.__lights = [];
  8200. this.__objectsAdded = [];
  8201. this.__objectsRemoved = [];
  8202. };
  8203. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8204. THREE.Scene.prototype.__addObject = function ( object ) {
  8205. if ( object instanceof THREE.Light ) {
  8206. if ( this.__lights.indexOf( object ) === - 1 ) {
  8207. this.__lights.push( object );
  8208. }
  8209. if ( object.target && object.target.parent === undefined ) {
  8210. this.add( object.target );
  8211. }
  8212. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8213. if ( this.__objects.indexOf( object ) === - 1 ) {
  8214. this.__objects.push( object );
  8215. this.__objectsAdded.push( object );
  8216. // check if previously removed
  8217. var i = this.__objectsRemoved.indexOf( object );
  8218. if ( i !== -1 ) {
  8219. this.__objectsRemoved.splice( i, 1 );
  8220. }
  8221. }
  8222. }
  8223. for ( var c = 0; c < object.children.length; c ++ ) {
  8224. this.__addObject( object.children[ c ] );
  8225. }
  8226. };
  8227. THREE.Scene.prototype.__removeObject = function ( object ) {
  8228. if ( object instanceof THREE.Light ) {
  8229. var i = this.__lights.indexOf( object );
  8230. if ( i !== -1 ) {
  8231. this.__lights.splice( i, 1 );
  8232. }
  8233. } else if ( !( object instanceof THREE.Camera ) ) {
  8234. var i = this.__objects.indexOf( object );
  8235. if( i !== -1 ) {
  8236. this.__objects.splice( i, 1 );
  8237. this.__objectsRemoved.push( object );
  8238. // check if previously added
  8239. var ai = this.__objectsAdded.indexOf( object );
  8240. if ( ai !== -1 ) {
  8241. this.__objectsAdded.splice( ai, 1 );
  8242. }
  8243. }
  8244. }
  8245. for ( var c = 0; c < object.children.length; c ++ ) {
  8246. this.__removeObject( object.children[ c ] );
  8247. }
  8248. };
  8249. /**
  8250. * @author mrdoob / http://mrdoob.com/
  8251. * @author alteredq / http://alteredqualia.com/
  8252. */
  8253. THREE.Fog = function ( hex, near, far ) {
  8254. this.name = '';
  8255. this.color = new THREE.Color( hex );
  8256. this.near = ( near !== undefined ) ? near : 1;
  8257. this.far = ( far !== undefined ) ? far : 1000;
  8258. };
  8259. THREE.Fog.prototype.clone = function () {
  8260. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8261. };
  8262. /**
  8263. * @author mrdoob / http://mrdoob.com/
  8264. * @author alteredq / http://alteredqualia.com/
  8265. */
  8266. THREE.FogExp2 = function ( hex, density ) {
  8267. this.name = '';
  8268. this.color = new THREE.Color( hex );
  8269. this.density = ( density !== undefined ) ? density : 0.00025;
  8270. };
  8271. THREE.FogExp2.prototype.clone = function () {
  8272. return new THREE.FogExp2( this.color.getHex(), this.density );
  8273. };
  8274. /**
  8275. * @author mrdoob / http://mrdoob.com/
  8276. */
  8277. THREE.CanvasRenderer = function ( parameters ) {
  8278. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8279. var smoothstep = THREE.Math.smoothstep;
  8280. parameters = parameters || {};
  8281. var _this = this,
  8282. _renderData, _elements, _lights,
  8283. _projector = new THREE.Projector(),
  8284. _canvas = parameters.canvas !== undefined
  8285. ? parameters.canvas
  8286. : document.createElement( 'canvas' ),
  8287. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8288. _context = _canvas.getContext( '2d' ),
  8289. _clearColor = new THREE.Color( 0x000000 ),
  8290. _clearAlpha = 0,
  8291. _contextGlobalAlpha = 1,
  8292. _contextGlobalCompositeOperation = 0,
  8293. _contextStrokeStyle = null,
  8294. _contextFillStyle = null,
  8295. _contextLineWidth = null,
  8296. _contextLineCap = null,
  8297. _contextLineJoin = null,
  8298. _contextDashSize = null,
  8299. _contextGapSize = 0,
  8300. _v1, _v2, _v3, _v4,
  8301. _v5 = new THREE.RenderableVertex(),
  8302. _v6 = new THREE.RenderableVertex(),
  8303. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8304. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8305. _color = new THREE.Color(),
  8306. _color1 = new THREE.Color(),
  8307. _color2 = new THREE.Color(),
  8308. _color3 = new THREE.Color(),
  8309. _color4 = new THREE.Color(),
  8310. _diffuseColor = new THREE.Color(),
  8311. _emissiveColor = new THREE.Color(),
  8312. _lightColor = new THREE.Color(),
  8313. _patterns = {}, _imagedatas = {},
  8314. _near, _far,
  8315. _image, _uvs,
  8316. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8317. _clipBox = new THREE.Box2(),
  8318. _clearBox = new THREE.Box2(),
  8319. _elemBox = new THREE.Box2(),
  8320. _ambientLight = new THREE.Color(),
  8321. _directionalLights = new THREE.Color(),
  8322. _pointLights = new THREE.Color(),
  8323. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8324. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8325. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8326. _pixelMap = document.createElement( 'canvas' );
  8327. _pixelMap.width = _pixelMap.height = 2;
  8328. _pixelMapContext = _pixelMap.getContext( '2d' );
  8329. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8330. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8331. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8332. _pixelMapData = _pixelMapImage.data;
  8333. _gradientMap = document.createElement( 'canvas' );
  8334. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8335. _gradientMapContext = _gradientMap.getContext( '2d' );
  8336. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8337. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8338. _gradientMapQuality --; // Fix UVs
  8339. // dash+gap fallbacks for Firefox and everything else
  8340. if ( _context.setLineDash === undefined ) {
  8341. if ( _context.mozDash !== undefined ) {
  8342. _context.setLineDash = function ( values ) {
  8343. _context.mozDash = values[ 0 ] !== null ? values : null;
  8344. }
  8345. } else {
  8346. _context.setLineDash = function () {}
  8347. }
  8348. }
  8349. this.domElement = _canvas;
  8350. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8351. ? parameters.devicePixelRatio
  8352. : window.devicePixelRatio !== undefined
  8353. ? window.devicePixelRatio
  8354. : 1;
  8355. this.autoClear = true;
  8356. this.sortObjects = true;
  8357. this.sortElements = true;
  8358. this.info = {
  8359. render: {
  8360. vertices: 0,
  8361. faces: 0
  8362. }
  8363. }
  8364. // WebGLRenderer compatibility
  8365. this.supportsVertexTextures = function () {};
  8366. this.setFaceCulling = function () {};
  8367. this.setSize = function ( width, height, updateStyle ) {
  8368. _canvasWidth = width * this.devicePixelRatio;
  8369. _canvasHeight = height * this.devicePixelRatio;
  8370. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8371. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8372. _canvas.width = _canvasWidth;
  8373. _canvas.height = _canvasHeight;
  8374. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  8375. _canvas.style.width = width + 'px';
  8376. _canvas.style.height = height + 'px';
  8377. }
  8378. _clipBox.set(
  8379. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8380. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8381. );
  8382. _clearBox.set(
  8383. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8384. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8385. );
  8386. _contextGlobalAlpha = 1;
  8387. _contextGlobalCompositeOperation = 0;
  8388. _contextStrokeStyle = null;
  8389. _contextFillStyle = null;
  8390. _contextLineWidth = null;
  8391. _contextLineCap = null;
  8392. _contextLineJoin = null;
  8393. };
  8394. this.setClearColor = function ( color, alpha ) {
  8395. _clearColor.set( color );
  8396. _clearAlpha = alpha !== undefined ? alpha : 1;
  8397. _clearBox.set(
  8398. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8399. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8400. );
  8401. };
  8402. this.setClearColorHex = function ( hex, alpha ) {
  8403. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  8404. this.setClearColor( hex, alpha );
  8405. };
  8406. this.getMaxAnisotropy = function () {
  8407. return 0;
  8408. };
  8409. this.clear = function () {
  8410. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8411. if ( _clearBox.empty() === false ) {
  8412. _clearBox.intersect( _clipBox );
  8413. _clearBox.expandByScalar( 2 );
  8414. if ( _clearAlpha < 1 ) {
  8415. _context.clearRect(
  8416. _clearBox.min.x | 0,
  8417. _clearBox.min.y | 0,
  8418. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8419. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8420. );
  8421. }
  8422. if ( _clearAlpha > 0 ) {
  8423. setBlending( THREE.NormalBlending );
  8424. setOpacity( 1 );
  8425. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  8426. _context.fillRect(
  8427. _clearBox.min.x | 0,
  8428. _clearBox.min.y | 0,
  8429. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8430. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8431. );
  8432. }
  8433. _clearBox.makeEmpty();
  8434. }
  8435. };
  8436. this.render = function ( scene, camera ) {
  8437. if ( camera instanceof THREE.Camera === false ) {
  8438. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8439. return;
  8440. }
  8441. if ( this.autoClear === true ) this.clear();
  8442. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8443. _this.info.render.vertices = 0;
  8444. _this.info.render.faces = 0;
  8445. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8446. _elements = _renderData.elements;
  8447. _lights = _renderData.lights;
  8448. /* DEBUG
  8449. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8450. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8451. */
  8452. calculateLights();
  8453. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8454. var element = _elements[ e ];
  8455. var material = element.material;
  8456. if ( material === undefined || material.visible === false ) continue;
  8457. _elemBox.makeEmpty();
  8458. if ( element instanceof THREE.RenderableParticle ) {
  8459. _v1 = element;
  8460. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8461. renderParticle( _v1, element, material );
  8462. } else if ( element instanceof THREE.RenderableLine ) {
  8463. _v1 = element.v1; _v2 = element.v2;
  8464. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8465. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8466. _elemBox.setFromPoints( [
  8467. _v1.positionScreen,
  8468. _v2.positionScreen
  8469. ] );
  8470. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8471. renderLine( _v1, _v2, element, material );
  8472. }
  8473. } else if ( element instanceof THREE.RenderableFace3 ) {
  8474. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8475. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8476. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8477. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8478. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8479. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8480. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8481. if ( material.overdraw === true ) {
  8482. expand( _v1.positionScreen, _v2.positionScreen );
  8483. expand( _v2.positionScreen, _v3.positionScreen );
  8484. expand( _v3.positionScreen, _v1.positionScreen );
  8485. }
  8486. _elemBox.setFromPoints( [
  8487. _v1.positionScreen,
  8488. _v2.positionScreen,
  8489. _v3.positionScreen
  8490. ] );
  8491. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8492. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  8493. }
  8494. } else if ( element instanceof THREE.RenderableFace4 ) {
  8495. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8496. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8497. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8498. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8499. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8500. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8501. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8502. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8503. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8504. _v5.positionScreen.copy( _v2.positionScreen );
  8505. _v6.positionScreen.copy( _v4.positionScreen );
  8506. if ( material.overdraw === true ) {
  8507. expand( _v1.positionScreen, _v2.positionScreen );
  8508. expand( _v2.positionScreen, _v4.positionScreen );
  8509. expand( _v4.positionScreen, _v1.positionScreen );
  8510. expand( _v3.positionScreen, _v5.positionScreen );
  8511. expand( _v3.positionScreen, _v6.positionScreen );
  8512. }
  8513. _elemBox.setFromPoints( [
  8514. _v1.positionScreen,
  8515. _v2.positionScreen,
  8516. _v3.positionScreen,
  8517. _v4.positionScreen
  8518. ] );
  8519. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8520. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material );
  8521. }
  8522. }
  8523. /* DEBUG
  8524. setLineWidth( 1 );
  8525. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  8526. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8527. */
  8528. _clearBox.union( _elemBox );
  8529. }
  8530. /* DEBUG
  8531. setLineWidth( 1 );
  8532. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  8533. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8534. */
  8535. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8536. //
  8537. function calculateLights() {
  8538. _ambientLight.setRGB( 0, 0, 0 );
  8539. _directionalLights.setRGB( 0, 0, 0 );
  8540. _pointLights.setRGB( 0, 0, 0 );
  8541. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8542. var light = _lights[ l ];
  8543. var lightColor = light.color;
  8544. if ( light instanceof THREE.AmbientLight ) {
  8545. _ambientLight.add( lightColor );
  8546. } else if ( light instanceof THREE.DirectionalLight ) {
  8547. // for particles
  8548. _directionalLights.add( lightColor );
  8549. } else if ( light instanceof THREE.PointLight ) {
  8550. // for particles
  8551. _pointLights.add( lightColor );
  8552. }
  8553. }
  8554. }
  8555. function calculateLight( position, normal, color ) {
  8556. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8557. var light = _lights[ l ];
  8558. _lightColor.copy( light.color );
  8559. if ( light instanceof THREE.DirectionalLight ) {
  8560. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  8561. var amount = normal.dot( lightPosition );
  8562. if ( amount <= 0 ) continue;
  8563. amount *= light.intensity;
  8564. color.add( _lightColor.multiplyScalar( amount ) );
  8565. } else if ( light instanceof THREE.PointLight ) {
  8566. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  8567. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8568. if ( amount <= 0 ) continue;
  8569. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8570. if ( amount == 0 ) continue;
  8571. amount *= light.intensity;
  8572. color.add( _lightColor.multiplyScalar( amount ) );
  8573. }
  8574. }
  8575. }
  8576. function renderParticle( v1, element, material ) {
  8577. setOpacity( material.opacity );
  8578. setBlending( material.blending );
  8579. var width, height, scaleX, scaleY,
  8580. bitmap, bitmapWidth, bitmapHeight;
  8581. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8582. if ( material.map === null ) {
  8583. scaleX = element.object.scale.x;
  8584. scaleY = element.object.scale.y;
  8585. // TODO: Be able to disable this
  8586. scaleX *= element.scale.x * _canvasWidthHalf;
  8587. scaleY *= element.scale.y * _canvasHeightHalf;
  8588. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8589. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8590. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8591. _elemBox.makeEmpty();
  8592. return;
  8593. }
  8594. setFillStyle( material.color.getStyle() );
  8595. _context.save();
  8596. _context.translate( v1.x, v1.y );
  8597. _context.rotate( - element.rotation );
  8598. _context.scale( scaleX, scaleY );
  8599. _context.fillRect( -1, -1, 2, 2 );
  8600. _context.restore();
  8601. } else {
  8602. bitmap = material.map.image;
  8603. bitmapWidth = bitmap.width >> 1;
  8604. bitmapHeight = bitmap.height >> 1;
  8605. scaleX = element.scale.x * _canvasWidthHalf;
  8606. scaleY = element.scale.y * _canvasHeightHalf;
  8607. width = scaleX * bitmapWidth;
  8608. height = scaleY * bitmapHeight;
  8609. // TODO: Rotations break this...
  8610. _elemBox.min.set( v1.x - width, v1.y - height );
  8611. _elemBox.max.set( v1.x + width, v1.y + height );
  8612. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8613. _elemBox.makeEmpty();
  8614. return;
  8615. }
  8616. _context.save();
  8617. _context.translate( v1.x, v1.y );
  8618. _context.rotate( - element.rotation );
  8619. _context.scale( scaleX, - scaleY );
  8620. _context.translate( - bitmapWidth, - bitmapHeight );
  8621. _context.drawImage( bitmap, 0, 0 );
  8622. _context.restore();
  8623. }
  8624. /* DEBUG
  8625. setStrokeStyle( 'rgb(255,255,0)' );
  8626. _context.beginPath();
  8627. _context.moveTo( v1.x - 10, v1.y );
  8628. _context.lineTo( v1.x + 10, v1.y );
  8629. _context.moveTo( v1.x, v1.y - 10 );
  8630. _context.lineTo( v1.x, v1.y + 10 );
  8631. _context.stroke();
  8632. */
  8633. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8634. width = element.scale.x * _canvasWidthHalf;
  8635. height = element.scale.y * _canvasHeightHalf;
  8636. _elemBox.min.set( v1.x - width, v1.y - height );
  8637. _elemBox.max.set( v1.x + width, v1.y + height );
  8638. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8639. _elemBox.makeEmpty();
  8640. return;
  8641. }
  8642. setStrokeStyle( material.color.getStyle() );
  8643. setFillStyle( material.color.getStyle() );
  8644. _context.save();
  8645. _context.translate( v1.x, v1.y );
  8646. _context.rotate( - element.rotation );
  8647. _context.scale( width, height );
  8648. material.program( _context );
  8649. _context.restore();
  8650. }
  8651. }
  8652. function renderLine( v1, v2, element, material ) {
  8653. setOpacity( material.opacity );
  8654. setBlending( material.blending );
  8655. _context.beginPath();
  8656. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8657. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8658. if ( material instanceof THREE.LineBasicMaterial ) {
  8659. setLineWidth( material.linewidth );
  8660. setLineCap( material.linecap );
  8661. setLineJoin( material.linejoin );
  8662. if ( material.vertexColors !== THREE.VertexColors ) {
  8663. setStrokeStyle( material.color.getStyle() );
  8664. } else {
  8665. var colorStyle1 = element.vertexColors[0].getStyle();
  8666. var colorStyle2 = element.vertexColors[1].getStyle();
  8667. if ( colorStyle1 === colorStyle2 ) {
  8668. setStrokeStyle( colorStyle1 );
  8669. } else {
  8670. try {
  8671. var grad = _context.createLinearGradient(
  8672. v1.positionScreen.x,
  8673. v1.positionScreen.y,
  8674. v2.positionScreen.x,
  8675. v2.positionScreen.y
  8676. );
  8677. grad.addColorStop( 0, colorStyle1 );
  8678. grad.addColorStop( 1, colorStyle2 );
  8679. } catch ( exception ) {
  8680. grad = colorStyle1;
  8681. }
  8682. setStrokeStyle( grad );
  8683. }
  8684. }
  8685. _context.stroke();
  8686. _elemBox.expandByScalar( material.linewidth * 2 );
  8687. } else if ( material instanceof THREE.LineDashedMaterial ) {
  8688. setLineWidth( material.linewidth );
  8689. setLineCap( material.linecap );
  8690. setLineJoin( material.linejoin );
  8691. setStrokeStyle( material.color.getStyle() );
  8692. setDashAndGap( material.dashSize, material.gapSize );
  8693. _context.stroke();
  8694. _elemBox.expandByScalar( material.linewidth * 2 );
  8695. setDashAndGap( null, null );
  8696. }
  8697. }
  8698. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  8699. _this.info.render.vertices += 3;
  8700. _this.info.render.faces ++;
  8701. setOpacity( material.opacity );
  8702. setBlending( material.blending );
  8703. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8704. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8705. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8706. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8707. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  8708. _diffuseColor.copy( material.color );
  8709. _emissiveColor.copy( material.emissive );
  8710. if ( material.vertexColors === THREE.FaceColors ) {
  8711. _diffuseColor.multiply( element.color );
  8712. }
  8713. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8714. _color1.copy( _ambientLight );
  8715. _color2.copy( _ambientLight );
  8716. _color3.copy( _ambientLight );
  8717. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8718. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8719. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8720. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8721. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8722. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8723. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8724. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8725. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8726. } else {
  8727. _color.copy( _ambientLight );
  8728. calculateLight( element.centroidModel, element.normalModel, _color );
  8729. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8730. material.wireframe === true
  8731. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8732. : fillPath( _color );
  8733. }
  8734. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8735. if ( material.map !== null ) {
  8736. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8737. _uvs = element.uvs[ 0 ];
  8738. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].x, _uvs[ uv1 ].y, _uvs[ uv2 ].x, _uvs[ uv2 ].y, _uvs[ uv3 ].x, _uvs[ uv3 ].y, material.map );
  8739. }
  8740. } else if ( material.envMap !== null ) {
  8741. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8742. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8743. _uv1x = 0.5 * _vector3.x + 0.5;
  8744. _uv1y = 0.5 * _vector3.y + 0.5;
  8745. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8746. _uv2x = 0.5 * _vector3.x + 0.5;
  8747. _uv2y = 0.5 * _vector3.y + 0.5;
  8748. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8749. _uv3x = 0.5 * _vector3.x + 0.5;
  8750. _uv3y = 0.5 * _vector3.y + 0.5;
  8751. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8752. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8753. }*/
  8754. } else {
  8755. _color.copy( material.color );
  8756. if ( material.vertexColors === THREE.FaceColors ) {
  8757. _color.multiply( element.color );
  8758. }
  8759. material.wireframe === true
  8760. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8761. : fillPath( _color );
  8762. }
  8763. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8764. _near = camera.near;
  8765. _far = camera.far;
  8766. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8767. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8768. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8769. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8770. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8771. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8772. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8773. var normal;
  8774. if ( material.shading == THREE.FlatShading ) {
  8775. normal = element.normalModelView;
  8776. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8777. material.wireframe === true
  8778. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8779. : fillPath( _color );
  8780. } else if ( material.shading == THREE.SmoothShading ) {
  8781. normal = element.vertexNormalsModelView[ uv1 ];
  8782. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8783. normal = element.vertexNormalsModelView[ uv2 ];
  8784. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8785. normal = element.vertexNormalsModelView[ uv3 ];
  8786. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8787. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8788. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8789. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8790. }
  8791. }
  8792. }
  8793. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  8794. _this.info.render.vertices += 4;
  8795. _this.info.render.faces ++;
  8796. setOpacity( material.opacity );
  8797. setBlending( material.blending );
  8798. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8799. // Let renderFace3() handle this
  8800. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  8801. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  8802. return;
  8803. }
  8804. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8805. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8806. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8807. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8808. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8809. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8810. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8811. _diffuseColor.copy( material.color );
  8812. _emissiveColor.copy( material.emissive );
  8813. if ( material.vertexColors === THREE.FaceColors ) {
  8814. _diffuseColor.multiply( element.color );
  8815. }
  8816. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8817. _color1.copy( _ambientLight );
  8818. _color2.copy( _ambientLight );
  8819. _color3.copy( _ambientLight );
  8820. _color4.copy( _ambientLight );
  8821. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8822. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8823. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8824. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8825. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8826. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8827. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8828. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8829. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8830. // TODO: UVs are incorrect, v4->v3?
  8831. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8832. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8833. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8834. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8835. } else {
  8836. _color.copy( _ambientLight );
  8837. calculateLight( element.centroidModel, element.normalModel, _color );
  8838. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8839. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8840. material.wireframe === true
  8841. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8842. : fillPath( _color );
  8843. }
  8844. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8845. _color.copy( material.color );
  8846. if ( material.vertexColors === THREE.FaceColors ) {
  8847. _color.multiply( element.color );
  8848. }
  8849. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8850. material.wireframe === true
  8851. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8852. : fillPath( _color );
  8853. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8854. var normal;
  8855. if ( material.shading == THREE.FlatShading ) {
  8856. normal = element.normalModelView;
  8857. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8858. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8859. material.wireframe === true
  8860. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8861. : fillPath( _color );
  8862. } else if ( material.shading == THREE.SmoothShading ) {
  8863. normal = element.vertexNormalsModelView[ 0 ];
  8864. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8865. normal = element.vertexNormalsModelView[ 1 ];
  8866. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8867. normal = element.vertexNormalsModelView[ 3 ];
  8868. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8869. normal = element.vertexNormalsModelView[ 2 ];
  8870. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8871. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8872. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8873. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8874. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8875. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8876. }
  8877. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8878. _near = camera.near;
  8879. _far = camera.far;
  8880. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8881. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8882. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  8883. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8884. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8885. // TODO: UVs are incorrect, v4->v3?
  8886. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8887. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8888. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8889. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8890. }
  8891. }
  8892. //
  8893. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8894. _context.beginPath();
  8895. _context.moveTo( x0, y0 );
  8896. _context.lineTo( x1, y1 );
  8897. _context.lineTo( x2, y2 );
  8898. _context.closePath();
  8899. }
  8900. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8901. _context.beginPath();
  8902. _context.moveTo( x0, y0 );
  8903. _context.lineTo( x1, y1 );
  8904. _context.lineTo( x2, y2 );
  8905. _context.lineTo( x3, y3 );
  8906. _context.closePath();
  8907. }
  8908. function strokePath( color, linewidth, linecap, linejoin ) {
  8909. setLineWidth( linewidth );
  8910. setLineCap( linecap );
  8911. setLineJoin( linejoin );
  8912. setStrokeStyle( color.getStyle() );
  8913. _context.stroke();
  8914. _elemBox.expandByScalar( linewidth * 2 );
  8915. }
  8916. function fillPath( color ) {
  8917. setFillStyle( color.getStyle() );
  8918. _context.fill();
  8919. }
  8920. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8921. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8922. if ( texture.needsUpdate === true ) {
  8923. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8924. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8925. _patterns[ texture.id ] = _context.createPattern(
  8926. texture.image, repeatX === true && repeatY === true
  8927. ? 'repeat'
  8928. : repeatX === true && repeatY === false
  8929. ? 'repeat-x'
  8930. : repeatX === false && repeatY === true
  8931. ? 'repeat-y'
  8932. : 'no-repeat'
  8933. );
  8934. texture.needsUpdate = false;
  8935. }
  8936. _patterns[ texture.id ] === undefined
  8937. ? setFillStyle( 'rgba(0,0,0,1)' )
  8938. : setFillStyle( _patterns[ texture.id ] );
  8939. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8940. var a, b, c, d, e, f, det, idet,
  8941. offsetX = texture.offset.x / texture.repeat.x,
  8942. offsetY = texture.offset.y / texture.repeat.y,
  8943. width = texture.image.width * texture.repeat.x,
  8944. height = texture.image.height * texture.repeat.y;
  8945. u0 = ( u0 + offsetX ) * width;
  8946. v0 = ( 1.0 - v0 + offsetY ) * height;
  8947. u1 = ( u1 + offsetX ) * width;
  8948. v1 = ( 1.0 - v1 + offsetY ) * height;
  8949. u2 = ( u2 + offsetX ) * width;
  8950. v2 = ( 1.0 - v2 + offsetY ) * height;
  8951. x1 -= x0; y1 -= y0;
  8952. x2 -= x0; y2 -= y0;
  8953. u1 -= u0; v1 -= v0;
  8954. u2 -= u0; v2 -= v0;
  8955. det = u1 * v2 - u2 * v1;
  8956. if ( det === 0 ) {
  8957. if ( _imagedatas[ texture.id ] === undefined ) {
  8958. var canvas = document.createElement( 'canvas' )
  8959. canvas.width = texture.image.width;
  8960. canvas.height = texture.image.height;
  8961. var context = canvas.getContext( '2d' );
  8962. context.drawImage( texture.image, 0, 0 );
  8963. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8964. }
  8965. var data = _imagedatas[ texture.id ];
  8966. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8967. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8968. fillPath( _color );
  8969. return;
  8970. }
  8971. idet = 1 / det;
  8972. a = ( v2 * x1 - v1 * x2 ) * idet;
  8973. b = ( v2 * y1 - v1 * y2 ) * idet;
  8974. c = ( u1 * x2 - u2 * x1 ) * idet;
  8975. d = ( u1 * y2 - u2 * y1 ) * idet;
  8976. e = x0 - a * u0 - c * v0;
  8977. f = y0 - b * u0 - d * v0;
  8978. _context.save();
  8979. _context.transform( a, b, c, d, e, f );
  8980. _context.fill();
  8981. _context.restore();
  8982. }
  8983. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8984. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8985. var a, b, c, d, e, f, det, idet,
  8986. width = image.width - 1,
  8987. height = image.height - 1;
  8988. u0 *= width; v0 *= height;
  8989. u1 *= width; v1 *= height;
  8990. u2 *= width; v2 *= height;
  8991. x1 -= x0; y1 -= y0;
  8992. x2 -= x0; y2 -= y0;
  8993. u1 -= u0; v1 -= v0;
  8994. u2 -= u0; v2 -= v0;
  8995. det = u1 * v2 - u2 * v1;
  8996. idet = 1 / det;
  8997. a = ( v2 * x1 - v1 * x2 ) * idet;
  8998. b = ( v2 * y1 - v1 * y2 ) * idet;
  8999. c = ( u1 * x2 - u2 * x1 ) * idet;
  9000. d = ( u1 * y2 - u2 * y1 ) * idet;
  9001. e = x0 - a * u0 - c * v0;
  9002. f = y0 - b * u0 - d * v0;
  9003. _context.save();
  9004. _context.transform( a, b, c, d, e, f );
  9005. _context.clip();
  9006. _context.drawImage( image, 0, 0 );
  9007. _context.restore();
  9008. }
  9009. function getGradientTexture( color1, color2, color3, color4 ) {
  9010. // http://mrdoob.com/blog/post/710
  9011. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9012. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9013. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9014. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9015. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9016. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9017. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9018. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9019. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9020. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9021. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9022. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9023. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9024. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9025. return _gradientMap;
  9026. }
  9027. // Hide anti-alias gaps
  9028. function expand( v1, v2 ) {
  9029. var x = v2.x - v1.x, y = v2.y - v1.y,
  9030. det = x * x + y * y, idet;
  9031. if ( det === 0 ) return;
  9032. idet = 1 / Math.sqrt( det );
  9033. x *= idet; y *= idet;
  9034. v2.x += x; v2.y += y;
  9035. v1.x -= x; v1.y -= y;
  9036. }
  9037. };
  9038. // Context cached methods.
  9039. function setOpacity( value ) {
  9040. if ( _contextGlobalAlpha !== value ) {
  9041. _context.globalAlpha = value;
  9042. _contextGlobalAlpha = value;
  9043. }
  9044. }
  9045. function setBlending( value ) {
  9046. if ( _contextGlobalCompositeOperation !== value ) {
  9047. if ( value === THREE.NormalBlending ) {
  9048. _context.globalCompositeOperation = 'source-over';
  9049. } else if ( value === THREE.AdditiveBlending ) {
  9050. _context.globalCompositeOperation = 'lighter';
  9051. } else if ( value === THREE.SubtractiveBlending ) {
  9052. _context.globalCompositeOperation = 'darker';
  9053. }
  9054. _contextGlobalCompositeOperation = value;
  9055. }
  9056. }
  9057. function setLineWidth( value ) {
  9058. if ( _contextLineWidth !== value ) {
  9059. _context.lineWidth = value;
  9060. _contextLineWidth = value;
  9061. }
  9062. }
  9063. function setLineCap( value ) {
  9064. // "butt", "round", "square"
  9065. if ( _contextLineCap !== value ) {
  9066. _context.lineCap = value;
  9067. _contextLineCap = value;
  9068. }
  9069. }
  9070. function setLineJoin( value ) {
  9071. // "round", "bevel", "miter"
  9072. if ( _contextLineJoin !== value ) {
  9073. _context.lineJoin = value;
  9074. _contextLineJoin = value;
  9075. }
  9076. }
  9077. function setStrokeStyle( value ) {
  9078. if ( _contextStrokeStyle !== value ) {
  9079. _context.strokeStyle = value;
  9080. _contextStrokeStyle = value;
  9081. }
  9082. }
  9083. function setFillStyle( value ) {
  9084. if ( _contextFillStyle !== value ) {
  9085. _context.fillStyle = value;
  9086. _contextFillStyle = value;
  9087. }
  9088. }
  9089. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9090. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9091. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9092. _contextDashSize = dashSizeValue;
  9093. _contextGapSize = gapSizeValue;
  9094. }
  9095. }
  9096. };
  9097. /**
  9098. * @author alteredq / http://alteredqualia.com/
  9099. * @author mrdoob / http://mrdoob.com/
  9100. * @author mikael emtinger / http://gomo.se/
  9101. */
  9102. THREE.ShaderChunk = {
  9103. // FOG
  9104. fog_pars_fragment: [
  9105. "#ifdef USE_FOG",
  9106. "uniform vec3 fogColor;",
  9107. "#ifdef FOG_EXP2",
  9108. "uniform float fogDensity;",
  9109. "#else",
  9110. "uniform float fogNear;",
  9111. "uniform float fogFar;",
  9112. "#endif",
  9113. "#endif"
  9114. ].join("\n"),
  9115. fog_fragment: [
  9116. "#ifdef USE_FOG",
  9117. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9118. "#ifdef FOG_EXP2",
  9119. "const float LOG2 = 1.442695;",
  9120. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9121. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9122. "#else",
  9123. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9124. "#endif",
  9125. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9126. "#endif"
  9127. ].join("\n"),
  9128. // ENVIRONMENT MAP
  9129. envmap_pars_fragment: [
  9130. "#ifdef USE_ENVMAP",
  9131. "uniform float reflectivity;",
  9132. "uniform samplerCube envMap;",
  9133. "uniform float flipEnvMap;",
  9134. "uniform int combine;",
  9135. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9136. "uniform bool useRefract;",
  9137. "uniform float refractionRatio;",
  9138. "#else",
  9139. "varying vec3 vReflect;",
  9140. "#endif",
  9141. "#endif"
  9142. ].join("\n"),
  9143. envmap_fragment: [
  9144. "#ifdef USE_ENVMAP",
  9145. "vec3 reflectVec;",
  9146. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9147. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9148. "if ( useRefract ) {",
  9149. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9150. "} else { ",
  9151. "reflectVec = reflect( cameraToVertex, normal );",
  9152. "}",
  9153. "#else",
  9154. "reflectVec = vReflect;",
  9155. "#endif",
  9156. "#ifdef DOUBLE_SIDED",
  9157. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9158. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9159. "#else",
  9160. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9161. "#endif",
  9162. "#ifdef GAMMA_INPUT",
  9163. "cubeColor.xyz *= cubeColor.xyz;",
  9164. "#endif",
  9165. "if ( combine == 1 ) {",
  9166. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9167. "} else if ( combine == 2 ) {",
  9168. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9169. "} else {",
  9170. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9171. "}",
  9172. "#endif"
  9173. ].join("\n"),
  9174. envmap_pars_vertex: [
  9175. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9176. "varying vec3 vReflect;",
  9177. "uniform float refractionRatio;",
  9178. "uniform bool useRefract;",
  9179. "#endif"
  9180. ].join("\n"),
  9181. worldpos_vertex : [
  9182. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9183. "#ifdef USE_SKINNING",
  9184. "vec4 worldPosition = modelMatrix * skinned;",
  9185. "#endif",
  9186. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9187. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9188. "#endif",
  9189. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9190. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9191. "#endif",
  9192. "#endif"
  9193. ].join("\n"),
  9194. envmap_vertex : [
  9195. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9196. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9197. "worldNormal = normalize( worldNormal );",
  9198. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9199. "if ( useRefract ) {",
  9200. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9201. "} else {",
  9202. "vReflect = reflect( cameraToVertex, worldNormal );",
  9203. "}",
  9204. "#endif"
  9205. ].join("\n"),
  9206. // COLOR MAP (particles)
  9207. map_particle_pars_fragment: [
  9208. "#ifdef USE_MAP",
  9209. "uniform sampler2D map;",
  9210. "#endif"
  9211. ].join("\n"),
  9212. map_particle_fragment: [
  9213. "#ifdef USE_MAP",
  9214. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9215. "#endif"
  9216. ].join("\n"),
  9217. // COLOR MAP (triangles)
  9218. map_pars_vertex: [
  9219. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9220. "varying vec2 vUv;",
  9221. "uniform vec4 offsetRepeat;",
  9222. "#endif"
  9223. ].join("\n"),
  9224. map_pars_fragment: [
  9225. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9226. "varying vec2 vUv;",
  9227. "#endif",
  9228. "#ifdef USE_MAP",
  9229. "uniform sampler2D map;",
  9230. "#endif"
  9231. ].join("\n"),
  9232. map_vertex: [
  9233. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9234. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9235. "#endif"
  9236. ].join("\n"),
  9237. map_fragment: [
  9238. "#ifdef USE_MAP",
  9239. "vec4 texelColor = texture2D( map, vUv );",
  9240. "#ifdef GAMMA_INPUT",
  9241. "texelColor.xyz *= texelColor.xyz;",
  9242. "#endif",
  9243. "gl_FragColor = gl_FragColor * texelColor;",
  9244. "#endif"
  9245. ].join("\n"),
  9246. // LIGHT MAP
  9247. lightmap_pars_fragment: [
  9248. "#ifdef USE_LIGHTMAP",
  9249. "varying vec2 vUv2;",
  9250. "uniform sampler2D lightMap;",
  9251. "#endif"
  9252. ].join("\n"),
  9253. lightmap_pars_vertex: [
  9254. "#ifdef USE_LIGHTMAP",
  9255. "varying vec2 vUv2;",
  9256. "#endif"
  9257. ].join("\n"),
  9258. lightmap_fragment: [
  9259. "#ifdef USE_LIGHTMAP",
  9260. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9261. "#endif"
  9262. ].join("\n"),
  9263. lightmap_vertex: [
  9264. "#ifdef USE_LIGHTMAP",
  9265. "vUv2 = uv2;",
  9266. "#endif"
  9267. ].join("\n"),
  9268. // BUMP MAP
  9269. bumpmap_pars_fragment: [
  9270. "#ifdef USE_BUMPMAP",
  9271. "uniform sampler2D bumpMap;",
  9272. "uniform float bumpScale;",
  9273. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9274. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9275. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9276. "vec2 dHdxy_fwd() {",
  9277. "vec2 dSTdx = dFdx( vUv );",
  9278. "vec2 dSTdy = dFdy( vUv );",
  9279. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9280. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9281. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9282. "return vec2( dBx, dBy );",
  9283. "}",
  9284. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9285. "vec3 vSigmaX = dFdx( surf_pos );",
  9286. "vec3 vSigmaY = dFdy( surf_pos );",
  9287. "vec3 vN = surf_norm;", // normalized
  9288. "vec3 R1 = cross( vSigmaY, vN );",
  9289. "vec3 R2 = cross( vN, vSigmaX );",
  9290. "float fDet = dot( vSigmaX, R1 );",
  9291. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9292. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9293. "}",
  9294. "#endif"
  9295. ].join("\n"),
  9296. // NORMAL MAP
  9297. normalmap_pars_fragment: [
  9298. "#ifdef USE_NORMALMAP",
  9299. "uniform sampler2D normalMap;",
  9300. "uniform vec2 normalScale;",
  9301. // Per-Pixel Tangent Space Normal Mapping
  9302. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9303. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9304. "vec3 q0 = dFdx( eye_pos.xyz );",
  9305. "vec3 q1 = dFdy( eye_pos.xyz );",
  9306. "vec2 st0 = dFdx( vUv.st );",
  9307. "vec2 st1 = dFdy( vUv.st );",
  9308. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9309. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9310. "vec3 N = normalize( surf_norm );",
  9311. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9312. "mapN.xy = normalScale * mapN.xy;",
  9313. "mat3 tsn = mat3( S, T, N );",
  9314. "return normalize( tsn * mapN );",
  9315. "}",
  9316. "#endif"
  9317. ].join("\n"),
  9318. // SPECULAR MAP
  9319. specularmap_pars_fragment: [
  9320. "#ifdef USE_SPECULARMAP",
  9321. "uniform sampler2D specularMap;",
  9322. "#endif"
  9323. ].join("\n"),
  9324. specularmap_fragment: [
  9325. "float specularStrength;",
  9326. "#ifdef USE_SPECULARMAP",
  9327. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9328. "specularStrength = texelSpecular.r;",
  9329. "#else",
  9330. "specularStrength = 1.0;",
  9331. "#endif"
  9332. ].join("\n"),
  9333. // LIGHTS LAMBERT
  9334. lights_lambert_pars_vertex: [
  9335. "uniform vec3 ambient;",
  9336. "uniform vec3 diffuse;",
  9337. "uniform vec3 emissive;",
  9338. "uniform vec3 ambientLightColor;",
  9339. "#if MAX_DIR_LIGHTS > 0",
  9340. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9341. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9342. "#endif",
  9343. "#if MAX_HEMI_LIGHTS > 0",
  9344. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9345. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9346. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9347. "#endif",
  9348. "#if MAX_POINT_LIGHTS > 0",
  9349. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9350. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9351. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9352. "#endif",
  9353. "#if MAX_SPOT_LIGHTS > 0",
  9354. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9355. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9356. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9357. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9358. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9359. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9360. "#endif",
  9361. "#ifdef WRAP_AROUND",
  9362. "uniform vec3 wrapRGB;",
  9363. "#endif"
  9364. ].join("\n"),
  9365. lights_lambert_vertex: [
  9366. "vLightFront = vec3( 0.0 );",
  9367. "#ifdef DOUBLE_SIDED",
  9368. "vLightBack = vec3( 0.0 );",
  9369. "#endif",
  9370. "transformedNormal = normalize( transformedNormal );",
  9371. "#if MAX_DIR_LIGHTS > 0",
  9372. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9373. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9374. "vec3 dirVector = normalize( lDirection.xyz );",
  9375. "float dotProduct = dot( transformedNormal, dirVector );",
  9376. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9377. "#ifdef DOUBLE_SIDED",
  9378. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9379. "#ifdef WRAP_AROUND",
  9380. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9381. "#endif",
  9382. "#endif",
  9383. "#ifdef WRAP_AROUND",
  9384. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9385. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9386. "#ifdef DOUBLE_SIDED",
  9387. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9388. "#endif",
  9389. "#endif",
  9390. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9391. "#ifdef DOUBLE_SIDED",
  9392. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9393. "#endif",
  9394. "}",
  9395. "#endif",
  9396. "#if MAX_POINT_LIGHTS > 0",
  9397. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9398. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9399. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9400. "float lDistance = 1.0;",
  9401. "if ( pointLightDistance[ i ] > 0.0 )",
  9402. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9403. "lVector = normalize( lVector );",
  9404. "float dotProduct = dot( transformedNormal, lVector );",
  9405. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9406. "#ifdef DOUBLE_SIDED",
  9407. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9408. "#ifdef WRAP_AROUND",
  9409. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9410. "#endif",
  9411. "#endif",
  9412. "#ifdef WRAP_AROUND",
  9413. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9414. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9415. "#ifdef DOUBLE_SIDED",
  9416. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9417. "#endif",
  9418. "#endif",
  9419. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9420. "#ifdef DOUBLE_SIDED",
  9421. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9422. "#endif",
  9423. "}",
  9424. "#endif",
  9425. "#if MAX_SPOT_LIGHTS > 0",
  9426. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9427. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9428. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9429. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9430. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9431. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9432. "float lDistance = 1.0;",
  9433. "if ( spotLightDistance[ i ] > 0.0 )",
  9434. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9435. "lVector = normalize( lVector );",
  9436. "float dotProduct = dot( transformedNormal, lVector );",
  9437. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9438. "#ifdef DOUBLE_SIDED",
  9439. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9440. "#ifdef WRAP_AROUND",
  9441. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9442. "#endif",
  9443. "#endif",
  9444. "#ifdef WRAP_AROUND",
  9445. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9446. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9447. "#ifdef DOUBLE_SIDED",
  9448. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9449. "#endif",
  9450. "#endif",
  9451. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9452. "#ifdef DOUBLE_SIDED",
  9453. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9454. "#endif",
  9455. "}",
  9456. "}",
  9457. "#endif",
  9458. "#if MAX_HEMI_LIGHTS > 0",
  9459. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9460. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9461. "vec3 lVector = normalize( lDirection.xyz );",
  9462. "float dotProduct = dot( transformedNormal, lVector );",
  9463. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9464. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9465. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9466. "#ifdef DOUBLE_SIDED",
  9467. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9468. "#endif",
  9469. "}",
  9470. "#endif",
  9471. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9472. "#ifdef DOUBLE_SIDED",
  9473. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9474. "#endif"
  9475. ].join("\n"),
  9476. // LIGHTS PHONG
  9477. lights_phong_pars_vertex: [
  9478. "#ifndef PHONG_PER_PIXEL",
  9479. "#if MAX_POINT_LIGHTS > 0",
  9480. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9481. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9482. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9483. "#endif",
  9484. "#if MAX_SPOT_LIGHTS > 0",
  9485. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9486. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9487. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9488. "#endif",
  9489. "#endif",
  9490. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9491. "varying vec3 vWorldPosition;",
  9492. "#endif"
  9493. ].join("\n"),
  9494. lights_phong_vertex: [
  9495. "#ifndef PHONG_PER_PIXEL",
  9496. "#if MAX_POINT_LIGHTS > 0",
  9497. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9498. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9499. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9500. "float lDistance = 1.0;",
  9501. "if ( pointLightDistance[ i ] > 0.0 )",
  9502. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9503. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9504. "}",
  9505. "#endif",
  9506. "#if MAX_SPOT_LIGHTS > 0",
  9507. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9508. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9509. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9510. "float lDistance = 1.0;",
  9511. "if ( spotLightDistance[ i ] > 0.0 )",
  9512. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9513. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9514. "}",
  9515. "#endif",
  9516. "#endif",
  9517. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9518. "vWorldPosition = worldPosition.xyz;",
  9519. "#endif"
  9520. ].join("\n"),
  9521. lights_phong_pars_fragment: [
  9522. "uniform vec3 ambientLightColor;",
  9523. "#if MAX_DIR_LIGHTS > 0",
  9524. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9525. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9526. "#endif",
  9527. "#if MAX_HEMI_LIGHTS > 0",
  9528. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9529. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9530. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9531. "#endif",
  9532. "#if MAX_POINT_LIGHTS > 0",
  9533. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9534. "#ifdef PHONG_PER_PIXEL",
  9535. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9536. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9537. "#else",
  9538. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9539. "#endif",
  9540. "#endif",
  9541. "#if MAX_SPOT_LIGHTS > 0",
  9542. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9543. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9544. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9545. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9546. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9547. "#ifdef PHONG_PER_PIXEL",
  9548. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9549. "#else",
  9550. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9551. "#endif",
  9552. "#endif",
  9553. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9554. "varying vec3 vWorldPosition;",
  9555. "#endif",
  9556. "#ifdef WRAP_AROUND",
  9557. "uniform vec3 wrapRGB;",
  9558. "#endif",
  9559. "varying vec3 vViewPosition;",
  9560. "varying vec3 vNormal;"
  9561. ].join("\n"),
  9562. lights_phong_fragment: [
  9563. "vec3 normal = normalize( vNormal );",
  9564. "vec3 viewPosition = normalize( vViewPosition );",
  9565. "#ifdef DOUBLE_SIDED",
  9566. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9567. "#endif",
  9568. "#ifdef USE_NORMALMAP",
  9569. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  9570. "#elif defined( USE_BUMPMAP )",
  9571. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9572. "#endif",
  9573. "#if MAX_POINT_LIGHTS > 0",
  9574. "vec3 pointDiffuse = vec3( 0.0 );",
  9575. "vec3 pointSpecular = vec3( 0.0 );",
  9576. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9577. "#ifdef PHONG_PER_PIXEL",
  9578. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9579. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9580. "float lDistance = 1.0;",
  9581. "if ( pointLightDistance[ i ] > 0.0 )",
  9582. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9583. "lVector = normalize( lVector );",
  9584. "#else",
  9585. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9586. "float lDistance = vPointLight[ i ].w;",
  9587. "#endif",
  9588. // diffuse
  9589. "float dotProduct = dot( normal, lVector );",
  9590. "#ifdef WRAP_AROUND",
  9591. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9592. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9593. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9594. "#else",
  9595. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9596. "#endif",
  9597. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9598. // specular
  9599. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9600. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9601. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9602. "#ifdef PHYSICALLY_BASED_SHADING",
  9603. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9604. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9605. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9606. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9607. "#else",
  9608. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9609. "#endif",
  9610. "}",
  9611. "#endif",
  9612. "#if MAX_SPOT_LIGHTS > 0",
  9613. "vec3 spotDiffuse = vec3( 0.0 );",
  9614. "vec3 spotSpecular = vec3( 0.0 );",
  9615. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9616. "#ifdef PHONG_PER_PIXEL",
  9617. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9618. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9619. "float lDistance = 1.0;",
  9620. "if ( spotLightDistance[ i ] > 0.0 )",
  9621. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9622. "lVector = normalize( lVector );",
  9623. "#else",
  9624. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9625. "float lDistance = vSpotLight[ i ].w;",
  9626. "#endif",
  9627. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9628. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9629. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9630. // diffuse
  9631. "float dotProduct = dot( normal, lVector );",
  9632. "#ifdef WRAP_AROUND",
  9633. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9634. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9635. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9636. "#else",
  9637. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9638. "#endif",
  9639. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9640. // specular
  9641. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9642. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9643. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9644. "#ifdef PHYSICALLY_BASED_SHADING",
  9645. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9646. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9647. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9648. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9649. "#else",
  9650. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9651. "#endif",
  9652. "}",
  9653. "}",
  9654. "#endif",
  9655. "#if MAX_DIR_LIGHTS > 0",
  9656. "vec3 dirDiffuse = vec3( 0.0 );",
  9657. "vec3 dirSpecular = vec3( 0.0 );" ,
  9658. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9659. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9660. "vec3 dirVector = normalize( lDirection.xyz );",
  9661. // diffuse
  9662. "float dotProduct = dot( normal, dirVector );",
  9663. "#ifdef WRAP_AROUND",
  9664. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9665. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9666. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9667. "#else",
  9668. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9669. "#endif",
  9670. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9671. // specular
  9672. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9673. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9674. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9675. "#ifdef PHYSICALLY_BASED_SHADING",
  9676. /*
  9677. // fresnel term from skin shader
  9678. "const float F0 = 0.128;",
  9679. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9680. "float exponential = pow( base, 5.0 );",
  9681. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9682. */
  9683. /*
  9684. // fresnel term from fresnel shader
  9685. "const float mFresnelBias = 0.08;",
  9686. "const float mFresnelScale = 0.3;",
  9687. "const float mFresnelPower = 5.0;",
  9688. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9689. */
  9690. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9691. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9692. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9693. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9694. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9695. "#else",
  9696. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9697. "#endif",
  9698. "}",
  9699. "#endif",
  9700. "#if MAX_HEMI_LIGHTS > 0",
  9701. "vec3 hemiDiffuse = vec3( 0.0 );",
  9702. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9703. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9704. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9705. "vec3 lVector = normalize( lDirection.xyz );",
  9706. // diffuse
  9707. "float dotProduct = dot( normal, lVector );",
  9708. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9709. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9710. "hemiDiffuse += diffuse * hemiColor;",
  9711. // specular (sky light)
  9712. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9713. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9714. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9715. // specular (ground light)
  9716. "vec3 lVectorGround = -lVector;",
  9717. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9718. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9719. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9720. "#ifdef PHYSICALLY_BASED_SHADING",
  9721. "float dotProductGround = dot( normal, lVectorGround );",
  9722. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9723. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9724. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9725. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9726. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9727. "#else",
  9728. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9729. "#endif",
  9730. "}",
  9731. "#endif",
  9732. "vec3 totalDiffuse = vec3( 0.0 );",
  9733. "vec3 totalSpecular = vec3( 0.0 );",
  9734. "#if MAX_DIR_LIGHTS > 0",
  9735. "totalDiffuse += dirDiffuse;",
  9736. "totalSpecular += dirSpecular;",
  9737. "#endif",
  9738. "#if MAX_HEMI_LIGHTS > 0",
  9739. "totalDiffuse += hemiDiffuse;",
  9740. "totalSpecular += hemiSpecular;",
  9741. "#endif",
  9742. "#if MAX_POINT_LIGHTS > 0",
  9743. "totalDiffuse += pointDiffuse;",
  9744. "totalSpecular += pointSpecular;",
  9745. "#endif",
  9746. "#if MAX_SPOT_LIGHTS > 0",
  9747. "totalDiffuse += spotDiffuse;",
  9748. "totalSpecular += spotSpecular;",
  9749. "#endif",
  9750. "#ifdef METAL",
  9751. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9752. "#else",
  9753. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9754. "#endif"
  9755. ].join("\n"),
  9756. // VERTEX COLORS
  9757. color_pars_fragment: [
  9758. "#ifdef USE_COLOR",
  9759. "varying vec3 vColor;",
  9760. "#endif"
  9761. ].join("\n"),
  9762. color_fragment: [
  9763. "#ifdef USE_COLOR",
  9764. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9765. "#endif"
  9766. ].join("\n"),
  9767. color_pars_vertex: [
  9768. "#ifdef USE_COLOR",
  9769. "varying vec3 vColor;",
  9770. "#endif"
  9771. ].join("\n"),
  9772. color_vertex: [
  9773. "#ifdef USE_COLOR",
  9774. "#ifdef GAMMA_INPUT",
  9775. "vColor = color * color;",
  9776. "#else",
  9777. "vColor = color;",
  9778. "#endif",
  9779. "#endif"
  9780. ].join("\n"),
  9781. // SKINNING
  9782. skinning_pars_vertex: [
  9783. "#ifdef USE_SKINNING",
  9784. "#ifdef BONE_TEXTURE",
  9785. "uniform sampler2D boneTexture;",
  9786. "mat4 getBoneMatrix( const in float i ) {",
  9787. "float j = i * 4.0;",
  9788. "float x = mod( j, N_BONE_PIXEL_X );",
  9789. "float y = floor( j / N_BONE_PIXEL_X );",
  9790. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9791. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9792. "y = dy * ( y + 0.5 );",
  9793. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9794. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9795. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9796. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9797. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9798. "return bone;",
  9799. "}",
  9800. "#else",
  9801. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9802. "mat4 getBoneMatrix( const in float i ) {",
  9803. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9804. "return bone;",
  9805. "}",
  9806. "#endif",
  9807. "#endif"
  9808. ].join("\n"),
  9809. skinbase_vertex: [
  9810. "#ifdef USE_SKINNING",
  9811. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9812. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9813. "#endif"
  9814. ].join("\n"),
  9815. skinning_vertex: [
  9816. "#ifdef USE_SKINNING",
  9817. "#ifdef USE_MORPHTARGETS",
  9818. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9819. "#else",
  9820. "vec4 skinVertex = vec4( position, 1.0 );",
  9821. "#endif",
  9822. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9823. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9824. "#endif"
  9825. ].join("\n"),
  9826. // MORPHING
  9827. morphtarget_pars_vertex: [
  9828. "#ifdef USE_MORPHTARGETS",
  9829. "#ifndef USE_MORPHNORMALS",
  9830. "uniform float morphTargetInfluences[ 8 ];",
  9831. "#else",
  9832. "uniform float morphTargetInfluences[ 4 ];",
  9833. "#endif",
  9834. "#endif"
  9835. ].join("\n"),
  9836. morphtarget_vertex: [
  9837. "#ifdef USE_MORPHTARGETS",
  9838. "vec3 morphed = vec3( 0.0 );",
  9839. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9840. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9841. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9842. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9843. "#ifndef USE_MORPHNORMALS",
  9844. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9845. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9846. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9847. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9848. "#endif",
  9849. "morphed += position;",
  9850. "#endif"
  9851. ].join("\n"),
  9852. default_vertex : [
  9853. "vec4 mvPosition;",
  9854. "#ifdef USE_SKINNING",
  9855. "mvPosition = modelViewMatrix * skinned;",
  9856. "#endif",
  9857. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9858. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9859. "#endif",
  9860. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9861. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9862. "#endif",
  9863. "gl_Position = projectionMatrix * mvPosition;"
  9864. ].join("\n"),
  9865. morphnormal_vertex: [
  9866. "#ifdef USE_MORPHNORMALS",
  9867. "vec3 morphedNormal = vec3( 0.0 );",
  9868. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9869. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9870. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9871. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9872. "morphedNormal += normal;",
  9873. "#endif"
  9874. ].join("\n"),
  9875. skinnormal_vertex: [
  9876. "#ifdef USE_SKINNING",
  9877. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9878. "skinMatrix += skinWeight.y * boneMatY;",
  9879. "#ifdef USE_MORPHNORMALS",
  9880. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9881. "#else",
  9882. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9883. "#endif",
  9884. "#endif"
  9885. ].join("\n"),
  9886. defaultnormal_vertex: [
  9887. "vec3 objectNormal;",
  9888. "#ifdef USE_SKINNING",
  9889. "objectNormal = skinnedNormal.xyz;",
  9890. "#endif",
  9891. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9892. "objectNormal = morphedNormal;",
  9893. "#endif",
  9894. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9895. "objectNormal = normal;",
  9896. "#endif",
  9897. "#ifdef FLIP_SIDED",
  9898. "objectNormal = -objectNormal;",
  9899. "#endif",
  9900. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9901. ].join("\n"),
  9902. // SHADOW MAP
  9903. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9904. // http://spidergl.org/example.php?id=6
  9905. // http://fabiensanglard.net/shadowmapping
  9906. shadowmap_pars_fragment: [
  9907. "#ifdef USE_SHADOWMAP",
  9908. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9909. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9910. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9911. "uniform float shadowBias[ MAX_SHADOWS ];",
  9912. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9913. "float unpackDepth( const in vec4 rgba_depth ) {",
  9914. "const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );",
  9915. "float depth = dot( rgba_depth, bit_shift );",
  9916. "return depth;",
  9917. "}",
  9918. "#endif"
  9919. ].join("\n"),
  9920. shadowmap_fragment: [
  9921. "#ifdef USE_SHADOWMAP",
  9922. "#ifdef SHADOWMAP_DEBUG",
  9923. "vec3 frustumColors[3];",
  9924. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9925. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9926. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9927. "#endif",
  9928. "#ifdef SHADOWMAP_CASCADE",
  9929. "int inFrustumCount = 0;",
  9930. "#endif",
  9931. "float fDepth;",
  9932. "vec3 shadowColor = vec3( 1.0 );",
  9933. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9934. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9935. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9936. // "if ( all( something, something ) )" using this instead
  9937. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9938. "bool inFrustum = all( inFrustumVec );",
  9939. // don't shadow pixels outside of light frustum
  9940. // use just first frustum (for cascades)
  9941. // don't shadow pixels behind far plane of light frustum
  9942. "#ifdef SHADOWMAP_CASCADE",
  9943. "inFrustumCount += int( inFrustum );",
  9944. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9945. "#else",
  9946. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9947. "#endif",
  9948. "bool frustumTest = all( frustumTestVec );",
  9949. "if ( frustumTest ) {",
  9950. "shadowCoord.z += shadowBias[ i ];",
  9951. "#if defined( SHADOWMAP_TYPE_PCF )",
  9952. // Percentage-close filtering
  9953. // (9 pixel kernel)
  9954. // http://fabiensanglard.net/shadowmappingPCF/
  9955. "float shadow = 0.0;",
  9956. /*
  9957. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9958. // must enroll loop manually
  9959. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9960. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9961. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9962. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9963. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9964. "float fDepth = unpackDepth( rgbaDepth );",
  9965. "if ( fDepth < shadowCoord.z )",
  9966. "shadow += 1.0;",
  9967. "}",
  9968. "shadow /= 9.0;",
  9969. */
  9970. "const float shadowDelta = 1.0 / 9.0;",
  9971. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9972. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9973. "float dx0 = -1.25 * xPixelOffset;",
  9974. "float dy0 = -1.25 * yPixelOffset;",
  9975. "float dx1 = 1.25 * xPixelOffset;",
  9976. "float dy1 = 1.25 * yPixelOffset;",
  9977. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9978. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9979. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9980. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9981. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9982. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9983. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9984. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9985. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9986. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9987. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9988. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9989. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9990. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9991. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9992. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9993. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9994. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9995. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9996. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9997. // Percentage-close filtering
  9998. // (9 pixel kernel)
  9999. // http://fabiensanglard.net/shadowmappingPCF/
  10000. "float shadow = 0.0;",
  10001. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10002. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10003. "float dx0 = -1.0 * xPixelOffset;",
  10004. "float dy0 = -1.0 * yPixelOffset;",
  10005. "float dx1 = 1.0 * xPixelOffset;",
  10006. "float dy1 = 1.0 * yPixelOffset;",
  10007. "mat3 shadowKernel;",
  10008. "mat3 depthKernel;",
  10009. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10010. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10011. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10012. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10013. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10014. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10015. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10016. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10017. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10018. "vec3 shadowZ = vec3( shadowCoord.z );",
  10019. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10020. "shadowKernel[0] *= vec3(0.25);",
  10021. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10022. "shadowKernel[1] *= vec3(0.25);",
  10023. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10024. "shadowKernel[2] *= vec3(0.25);",
  10025. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10026. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10027. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10028. "vec4 shadowValues;",
  10029. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10030. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10031. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10032. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10033. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10034. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10035. "#else",
  10036. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10037. "float fDepth = unpackDepth( rgbaDepth );",
  10038. "if ( fDepth < shadowCoord.z )",
  10039. // spot with multiple shadows is darker
  10040. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10041. // spot with multiple shadows has the same color as single shadow spot
  10042. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10043. "#endif",
  10044. "}",
  10045. "#ifdef SHADOWMAP_DEBUG",
  10046. "#ifdef SHADOWMAP_CASCADE",
  10047. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10048. "#else",
  10049. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10050. "#endif",
  10051. "#endif",
  10052. "}",
  10053. "#ifdef GAMMA_OUTPUT",
  10054. "shadowColor *= shadowColor;",
  10055. "#endif",
  10056. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10057. "#endif"
  10058. ].join("\n"),
  10059. shadowmap_pars_vertex: [
  10060. "#ifdef USE_SHADOWMAP",
  10061. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10062. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10063. "#endif"
  10064. ].join("\n"),
  10065. shadowmap_vertex: [
  10066. "#ifdef USE_SHADOWMAP",
  10067. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10068. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10069. "}",
  10070. "#endif"
  10071. ].join("\n"),
  10072. // ALPHATEST
  10073. alphatest_fragment: [
  10074. "#ifdef ALPHATEST",
  10075. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10076. "#endif"
  10077. ].join("\n"),
  10078. // LINEAR SPACE
  10079. linear_to_gamma_fragment: [
  10080. "#ifdef GAMMA_OUTPUT",
  10081. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10082. "#endif"
  10083. ].join("\n")
  10084. };
  10085. THREE.UniformsUtils = {
  10086. merge: function ( uniforms ) {
  10087. var u, p, tmp, merged = {};
  10088. for ( u = 0; u < uniforms.length; u ++ ) {
  10089. tmp = this.clone( uniforms[ u ] );
  10090. for ( p in tmp ) {
  10091. merged[ p ] = tmp[ p ];
  10092. }
  10093. }
  10094. return merged;
  10095. },
  10096. clone: function ( uniforms_src ) {
  10097. var u, p, parameter, parameter_src, uniforms_dst = {};
  10098. for ( u in uniforms_src ) {
  10099. uniforms_dst[ u ] = {};
  10100. for ( p in uniforms_src[ u ] ) {
  10101. parameter_src = uniforms_src[ u ][ p ];
  10102. if ( parameter_src instanceof THREE.Color ||
  10103. parameter_src instanceof THREE.Vector2 ||
  10104. parameter_src instanceof THREE.Vector3 ||
  10105. parameter_src instanceof THREE.Vector4 ||
  10106. parameter_src instanceof THREE.Matrix4 ||
  10107. parameter_src instanceof THREE.Texture ) {
  10108. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10109. } else if ( parameter_src instanceof Array ) {
  10110. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10111. } else {
  10112. uniforms_dst[ u ][ p ] = parameter_src;
  10113. }
  10114. }
  10115. }
  10116. return uniforms_dst;
  10117. }
  10118. };
  10119. THREE.UniformsLib = {
  10120. common: {
  10121. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10122. "opacity" : { type: "f", value: 1.0 },
  10123. "map" : { type: "t", value: null },
  10124. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10125. "lightMap" : { type: "t", value: null },
  10126. "specularMap" : { type: "t", value: null },
  10127. "envMap" : { type: "t", value: null },
  10128. "flipEnvMap" : { type: "f", value: -1 },
  10129. "useRefract" : { type: "i", value: 0 },
  10130. "reflectivity" : { type: "f", value: 1.0 },
  10131. "refractionRatio" : { type: "f", value: 0.98 },
  10132. "combine" : { type: "i", value: 0 },
  10133. "morphTargetInfluences" : { type: "f", value: 0 }
  10134. },
  10135. bump: {
  10136. "bumpMap" : { type: "t", value: null },
  10137. "bumpScale" : { type: "f", value: 1 }
  10138. },
  10139. normalmap: {
  10140. "normalMap" : { type: "t", value: null },
  10141. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10142. },
  10143. fog : {
  10144. "fogDensity" : { type: "f", value: 0.00025 },
  10145. "fogNear" : { type: "f", value: 1 },
  10146. "fogFar" : { type: "f", value: 2000 },
  10147. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10148. },
  10149. lights: {
  10150. "ambientLightColor" : { type: "fv", value: [] },
  10151. "directionalLightDirection" : { type: "fv", value: [] },
  10152. "directionalLightColor" : { type: "fv", value: [] },
  10153. "hemisphereLightDirection" : { type: "fv", value: [] },
  10154. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10155. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10156. "pointLightColor" : { type: "fv", value: [] },
  10157. "pointLightPosition" : { type: "fv", value: [] },
  10158. "pointLightDistance" : { type: "fv1", value: [] },
  10159. "spotLightColor" : { type: "fv", value: [] },
  10160. "spotLightPosition" : { type: "fv", value: [] },
  10161. "spotLightDirection" : { type: "fv", value: [] },
  10162. "spotLightDistance" : { type: "fv1", value: [] },
  10163. "spotLightAngleCos" : { type: "fv1", value: [] },
  10164. "spotLightExponent" : { type: "fv1", value: [] }
  10165. },
  10166. particle: {
  10167. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10168. "opacity" : { type: "f", value: 1.0 },
  10169. "size" : { type: "f", value: 1.0 },
  10170. "scale" : { type: "f", value: 1.0 },
  10171. "map" : { type: "t", value: null },
  10172. "fogDensity" : { type: "f", value: 0.00025 },
  10173. "fogNear" : { type: "f", value: 1 },
  10174. "fogFar" : { type: "f", value: 2000 },
  10175. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10176. },
  10177. shadowmap: {
  10178. "shadowMap": { type: "tv", value: [] },
  10179. "shadowMapSize": { type: "v2v", value: [] },
  10180. "shadowBias" : { type: "fv1", value: [] },
  10181. "shadowDarkness": { type: "fv1", value: [] },
  10182. "shadowMatrix" : { type: "m4v", value: [] }
  10183. }
  10184. };
  10185. THREE.ShaderLib = {
  10186. 'basic': {
  10187. uniforms: THREE.UniformsUtils.merge( [
  10188. THREE.UniformsLib[ "common" ],
  10189. THREE.UniformsLib[ "fog" ],
  10190. THREE.UniformsLib[ "shadowmap" ]
  10191. ] ),
  10192. vertexShader: [
  10193. THREE.ShaderChunk[ "map_pars_vertex" ],
  10194. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10195. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10196. THREE.ShaderChunk[ "color_pars_vertex" ],
  10197. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10198. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10199. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10200. "void main() {",
  10201. THREE.ShaderChunk[ "map_vertex" ],
  10202. THREE.ShaderChunk[ "lightmap_vertex" ],
  10203. THREE.ShaderChunk[ "color_vertex" ],
  10204. THREE.ShaderChunk[ "skinbase_vertex" ],
  10205. "#ifdef USE_ENVMAP",
  10206. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10207. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10208. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10209. "#endif",
  10210. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10211. THREE.ShaderChunk[ "skinning_vertex" ],
  10212. THREE.ShaderChunk[ "default_vertex" ],
  10213. THREE.ShaderChunk[ "worldpos_vertex" ],
  10214. THREE.ShaderChunk[ "envmap_vertex" ],
  10215. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10216. "}"
  10217. ].join("\n"),
  10218. fragmentShader: [
  10219. "uniform vec3 diffuse;",
  10220. "uniform float opacity;",
  10221. THREE.ShaderChunk[ "color_pars_fragment" ],
  10222. THREE.ShaderChunk[ "map_pars_fragment" ],
  10223. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10224. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10225. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10226. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10227. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10228. "void main() {",
  10229. "gl_FragColor = vec4( diffuse, opacity );",
  10230. THREE.ShaderChunk[ "map_fragment" ],
  10231. THREE.ShaderChunk[ "alphatest_fragment" ],
  10232. THREE.ShaderChunk[ "specularmap_fragment" ],
  10233. THREE.ShaderChunk[ "lightmap_fragment" ],
  10234. THREE.ShaderChunk[ "color_fragment" ],
  10235. THREE.ShaderChunk[ "envmap_fragment" ],
  10236. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10237. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10238. THREE.ShaderChunk[ "fog_fragment" ],
  10239. "}"
  10240. ].join("\n")
  10241. },
  10242. 'lambert': {
  10243. uniforms: THREE.UniformsUtils.merge( [
  10244. THREE.UniformsLib[ "common" ],
  10245. THREE.UniformsLib[ "fog" ],
  10246. THREE.UniformsLib[ "lights" ],
  10247. THREE.UniformsLib[ "shadowmap" ],
  10248. {
  10249. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10250. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10251. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10252. }
  10253. ] ),
  10254. vertexShader: [
  10255. "#define LAMBERT",
  10256. "varying vec3 vLightFront;",
  10257. "#ifdef DOUBLE_SIDED",
  10258. "varying vec3 vLightBack;",
  10259. "#endif",
  10260. THREE.ShaderChunk[ "map_pars_vertex" ],
  10261. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10262. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10263. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10264. THREE.ShaderChunk[ "color_pars_vertex" ],
  10265. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10266. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10267. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10268. "void main() {",
  10269. THREE.ShaderChunk[ "map_vertex" ],
  10270. THREE.ShaderChunk[ "lightmap_vertex" ],
  10271. THREE.ShaderChunk[ "color_vertex" ],
  10272. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10273. THREE.ShaderChunk[ "skinbase_vertex" ],
  10274. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10275. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10276. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10277. THREE.ShaderChunk[ "skinning_vertex" ],
  10278. THREE.ShaderChunk[ "default_vertex" ],
  10279. THREE.ShaderChunk[ "worldpos_vertex" ],
  10280. THREE.ShaderChunk[ "envmap_vertex" ],
  10281. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10282. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10283. "}"
  10284. ].join("\n"),
  10285. fragmentShader: [
  10286. "uniform float opacity;",
  10287. "varying vec3 vLightFront;",
  10288. "#ifdef DOUBLE_SIDED",
  10289. "varying vec3 vLightBack;",
  10290. "#endif",
  10291. THREE.ShaderChunk[ "color_pars_fragment" ],
  10292. THREE.ShaderChunk[ "map_pars_fragment" ],
  10293. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10294. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10295. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10296. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10297. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10298. "void main() {",
  10299. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10300. THREE.ShaderChunk[ "map_fragment" ],
  10301. THREE.ShaderChunk[ "alphatest_fragment" ],
  10302. THREE.ShaderChunk[ "specularmap_fragment" ],
  10303. "#ifdef DOUBLE_SIDED",
  10304. //"float isFront = float( gl_FrontFacing );",
  10305. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10306. "if ( gl_FrontFacing )",
  10307. "gl_FragColor.xyz *= vLightFront;",
  10308. "else",
  10309. "gl_FragColor.xyz *= vLightBack;",
  10310. "#else",
  10311. "gl_FragColor.xyz *= vLightFront;",
  10312. "#endif",
  10313. THREE.ShaderChunk[ "lightmap_fragment" ],
  10314. THREE.ShaderChunk[ "color_fragment" ],
  10315. THREE.ShaderChunk[ "envmap_fragment" ],
  10316. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10317. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10318. THREE.ShaderChunk[ "fog_fragment" ],
  10319. "}"
  10320. ].join("\n")
  10321. },
  10322. 'phong': {
  10323. uniforms: THREE.UniformsUtils.merge( [
  10324. THREE.UniformsLib[ "common" ],
  10325. THREE.UniformsLib[ "bump" ],
  10326. THREE.UniformsLib[ "normalmap" ],
  10327. THREE.UniformsLib[ "fog" ],
  10328. THREE.UniformsLib[ "lights" ],
  10329. THREE.UniformsLib[ "shadowmap" ],
  10330. {
  10331. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10332. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10333. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10334. "shininess": { type: "f", value: 30 },
  10335. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10336. }
  10337. ] ),
  10338. vertexShader: [
  10339. "#define PHONG",
  10340. "varying vec3 vViewPosition;",
  10341. "varying vec3 vNormal;",
  10342. THREE.ShaderChunk[ "map_pars_vertex" ],
  10343. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10344. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10345. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10346. THREE.ShaderChunk[ "color_pars_vertex" ],
  10347. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10348. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10349. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10350. "void main() {",
  10351. THREE.ShaderChunk[ "map_vertex" ],
  10352. THREE.ShaderChunk[ "lightmap_vertex" ],
  10353. THREE.ShaderChunk[ "color_vertex" ],
  10354. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10355. THREE.ShaderChunk[ "skinbase_vertex" ],
  10356. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10357. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10358. "vNormal = normalize( transformedNormal );",
  10359. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10360. THREE.ShaderChunk[ "skinning_vertex" ],
  10361. THREE.ShaderChunk[ "default_vertex" ],
  10362. "vViewPosition = -mvPosition.xyz;",
  10363. THREE.ShaderChunk[ "worldpos_vertex" ],
  10364. THREE.ShaderChunk[ "envmap_vertex" ],
  10365. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10366. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10367. "}"
  10368. ].join("\n"),
  10369. fragmentShader: [
  10370. "uniform vec3 diffuse;",
  10371. "uniform float opacity;",
  10372. "uniform vec3 ambient;",
  10373. "uniform vec3 emissive;",
  10374. "uniform vec3 specular;",
  10375. "uniform float shininess;",
  10376. THREE.ShaderChunk[ "color_pars_fragment" ],
  10377. THREE.ShaderChunk[ "map_pars_fragment" ],
  10378. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10379. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10380. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10381. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10382. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10383. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10384. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10385. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10386. "void main() {",
  10387. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10388. THREE.ShaderChunk[ "map_fragment" ],
  10389. THREE.ShaderChunk[ "alphatest_fragment" ],
  10390. THREE.ShaderChunk[ "specularmap_fragment" ],
  10391. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10392. THREE.ShaderChunk[ "lightmap_fragment" ],
  10393. THREE.ShaderChunk[ "color_fragment" ],
  10394. THREE.ShaderChunk[ "envmap_fragment" ],
  10395. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10396. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10397. THREE.ShaderChunk[ "fog_fragment" ],
  10398. "}"
  10399. ].join("\n")
  10400. },
  10401. 'particle_basic': {
  10402. uniforms: THREE.UniformsUtils.merge( [
  10403. THREE.UniformsLib[ "particle" ],
  10404. THREE.UniformsLib[ "shadowmap" ]
  10405. ] ),
  10406. vertexShader: [
  10407. "uniform float size;",
  10408. "uniform float scale;",
  10409. THREE.ShaderChunk[ "color_pars_vertex" ],
  10410. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10411. "void main() {",
  10412. THREE.ShaderChunk[ "color_vertex" ],
  10413. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10414. "#ifdef USE_SIZEATTENUATION",
  10415. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10416. "#else",
  10417. "gl_PointSize = size;",
  10418. "#endif",
  10419. "gl_Position = projectionMatrix * mvPosition;",
  10420. THREE.ShaderChunk[ "worldpos_vertex" ],
  10421. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10422. "}"
  10423. ].join("\n"),
  10424. fragmentShader: [
  10425. "uniform vec3 psColor;",
  10426. "uniform float opacity;",
  10427. THREE.ShaderChunk[ "color_pars_fragment" ],
  10428. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10429. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10430. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10431. "void main() {",
  10432. "gl_FragColor = vec4( psColor, opacity );",
  10433. THREE.ShaderChunk[ "map_particle_fragment" ],
  10434. THREE.ShaderChunk[ "alphatest_fragment" ],
  10435. THREE.ShaderChunk[ "color_fragment" ],
  10436. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10437. THREE.ShaderChunk[ "fog_fragment" ],
  10438. "}"
  10439. ].join("\n")
  10440. },
  10441. 'dashed': {
  10442. uniforms: THREE.UniformsUtils.merge( [
  10443. THREE.UniformsLib[ "common" ],
  10444. THREE.UniformsLib[ "fog" ],
  10445. {
  10446. "scale": { type: "f", value: 1 },
  10447. "dashSize": { type: "f", value: 1 },
  10448. "totalSize": { type: "f", value: 2 }
  10449. }
  10450. ] ),
  10451. vertexShader: [
  10452. "uniform float scale;",
  10453. "attribute float lineDistance;",
  10454. "varying float vLineDistance;",
  10455. THREE.ShaderChunk[ "color_pars_vertex" ],
  10456. "void main() {",
  10457. THREE.ShaderChunk[ "color_vertex" ],
  10458. "vLineDistance = scale * lineDistance;",
  10459. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10460. "gl_Position = projectionMatrix * mvPosition;",
  10461. "}"
  10462. ].join("\n"),
  10463. fragmentShader: [
  10464. "uniform vec3 diffuse;",
  10465. "uniform float opacity;",
  10466. "uniform float dashSize;",
  10467. "uniform float totalSize;",
  10468. "varying float vLineDistance;",
  10469. THREE.ShaderChunk[ "color_pars_fragment" ],
  10470. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10471. "void main() {",
  10472. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10473. "discard;",
  10474. "}",
  10475. "gl_FragColor = vec4( diffuse, opacity );",
  10476. THREE.ShaderChunk[ "color_fragment" ],
  10477. THREE.ShaderChunk[ "fog_fragment" ],
  10478. "}"
  10479. ].join("\n")
  10480. },
  10481. 'depth': {
  10482. uniforms: {
  10483. "mNear": { type: "f", value: 1.0 },
  10484. "mFar" : { type: "f", value: 2000.0 },
  10485. "opacity" : { type: "f", value: 1.0 }
  10486. },
  10487. vertexShader: [
  10488. "void main() {",
  10489. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10490. "}"
  10491. ].join("\n"),
  10492. fragmentShader: [
  10493. "uniform float mNear;",
  10494. "uniform float mFar;",
  10495. "uniform float opacity;",
  10496. "void main() {",
  10497. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10498. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10499. "gl_FragColor = vec4( vec3( color ), opacity );",
  10500. "}"
  10501. ].join("\n")
  10502. },
  10503. 'normal': {
  10504. uniforms: {
  10505. "opacity" : { type: "f", value: 1.0 }
  10506. },
  10507. vertexShader: [
  10508. "varying vec3 vNormal;",
  10509. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10510. "void main() {",
  10511. "vNormal = normalize( normalMatrix * normal );",
  10512. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10513. THREE.ShaderChunk[ "default_vertex" ],
  10514. "}"
  10515. ].join("\n"),
  10516. fragmentShader: [
  10517. "uniform float opacity;",
  10518. "varying vec3 vNormal;",
  10519. "void main() {",
  10520. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10521. "}"
  10522. ].join("\n")
  10523. },
  10524. /* -------------------------------------------------------------------------
  10525. // Normal map shader
  10526. // - Blinn-Phong
  10527. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10528. // - point and directional lights (use with "lights: true" material option)
  10529. ------------------------------------------------------------------------- */
  10530. 'normalmap' : {
  10531. uniforms: THREE.UniformsUtils.merge( [
  10532. THREE.UniformsLib[ "fog" ],
  10533. THREE.UniformsLib[ "lights" ],
  10534. THREE.UniformsLib[ "shadowmap" ],
  10535. {
  10536. "enableAO" : { type: "i", value: 0 },
  10537. "enableDiffuse" : { type: "i", value: 0 },
  10538. "enableSpecular" : { type: "i", value: 0 },
  10539. "enableReflection": { type: "i", value: 0 },
  10540. "enableDisplacement": { type: "i", value: 0 },
  10541. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  10542. "tDiffuse" : { type: "t", value: null },
  10543. "tCube" : { type: "t", value: null },
  10544. "tNormal" : { type: "t", value: null },
  10545. "tSpecular" : { type: "t", value: null },
  10546. "tAO" : { type: "t", value: null },
  10547. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10548. "uDisplacementBias": { type: "f", value: 0.0 },
  10549. "uDisplacementScale": { type: "f", value: 1.0 },
  10550. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10551. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  10552. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10553. "uShininess": { type: "f", value: 30 },
  10554. "uOpacity": { type: "f", value: 1 },
  10555. "useRefract": { type: "i", value: 0 },
  10556. "uRefractionRatio": { type: "f", value: 0.98 },
  10557. "uReflectivity": { type: "f", value: 0.5 },
  10558. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  10559. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10560. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10561. }
  10562. ] ),
  10563. fragmentShader: [
  10564. "uniform vec3 uAmbientColor;",
  10565. "uniform vec3 uDiffuseColor;",
  10566. "uniform vec3 uSpecularColor;",
  10567. "uniform float uShininess;",
  10568. "uniform float uOpacity;",
  10569. "uniform bool enableDiffuse;",
  10570. "uniform bool enableSpecular;",
  10571. "uniform bool enableAO;",
  10572. "uniform bool enableReflection;",
  10573. "uniform sampler2D tDiffuse;",
  10574. "uniform sampler2D tNormal;",
  10575. "uniform sampler2D tSpecular;",
  10576. "uniform sampler2D tAO;",
  10577. "uniform samplerCube tCube;",
  10578. "uniform vec2 uNormalScale;",
  10579. "uniform bool useRefract;",
  10580. "uniform float uRefractionRatio;",
  10581. "uniform float uReflectivity;",
  10582. "varying vec3 vTangent;",
  10583. "varying vec3 vBinormal;",
  10584. "varying vec3 vNormal;",
  10585. "varying vec2 vUv;",
  10586. "uniform vec3 ambientLightColor;",
  10587. "#if MAX_DIR_LIGHTS > 0",
  10588. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10589. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10590. "#endif",
  10591. "#if MAX_HEMI_LIGHTS > 0",
  10592. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10593. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10594. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10595. "#endif",
  10596. "#if MAX_POINT_LIGHTS > 0",
  10597. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10598. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10599. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10600. "#endif",
  10601. "#if MAX_SPOT_LIGHTS > 0",
  10602. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10603. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10604. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10605. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10606. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10607. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10608. "#endif",
  10609. "#ifdef WRAP_AROUND",
  10610. "uniform vec3 wrapRGB;",
  10611. "#endif",
  10612. "varying vec3 vWorldPosition;",
  10613. "varying vec3 vViewPosition;",
  10614. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10615. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10616. "void main() {",
  10617. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  10618. "vec3 specularTex = vec3( 1.0 );",
  10619. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  10620. "normalTex.xy *= uNormalScale;",
  10621. "normalTex = normalize( normalTex );",
  10622. "if( enableDiffuse ) {",
  10623. "#ifdef GAMMA_INPUT",
  10624. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  10625. "texelColor.xyz *= texelColor.xyz;",
  10626. "gl_FragColor = gl_FragColor * texelColor;",
  10627. "#else",
  10628. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  10629. "#endif",
  10630. "}",
  10631. "if( enableAO ) {",
  10632. "#ifdef GAMMA_INPUT",
  10633. "vec4 aoColor = texture2D( tAO, vUv );",
  10634. "aoColor.xyz *= aoColor.xyz;",
  10635. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  10636. "#else",
  10637. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  10638. "#endif",
  10639. "}",
  10640. "if( enableSpecular )",
  10641. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  10642. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  10643. "vec3 finalNormal = tsb * normalTex;",
  10644. "#ifdef FLIP_SIDED",
  10645. "finalNormal = -finalNormal;",
  10646. "#endif",
  10647. "vec3 normal = normalize( finalNormal );",
  10648. "vec3 viewPosition = normalize( vViewPosition );",
  10649. // point lights
  10650. "#if MAX_POINT_LIGHTS > 0",
  10651. "vec3 pointDiffuse = vec3( 0.0 );",
  10652. "vec3 pointSpecular = vec3( 0.0 );",
  10653. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10654. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10655. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  10656. "float pointDistance = 1.0;",
  10657. "if ( pointLightDistance[ i ] > 0.0 )",
  10658. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  10659. "pointVector = normalize( pointVector );",
  10660. // diffuse
  10661. "#ifdef WRAP_AROUND",
  10662. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  10663. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  10664. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10665. "#else",
  10666. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  10667. "#endif",
  10668. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  10669. // specular
  10670. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  10671. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10672. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  10673. "#ifdef PHYSICALLY_BASED_SHADING",
  10674. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10675. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10676. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  10677. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  10678. "#else",
  10679. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  10680. "#endif",
  10681. "}",
  10682. "#endif",
  10683. // spot lights
  10684. "#if MAX_SPOT_LIGHTS > 0",
  10685. "vec3 spotDiffuse = vec3( 0.0 );",
  10686. "vec3 spotSpecular = vec3( 0.0 );",
  10687. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10688. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10689. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  10690. "float spotDistance = 1.0;",
  10691. "if ( spotLightDistance[ i ] > 0.0 )",
  10692. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  10693. "spotVector = normalize( spotVector );",
  10694. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10695. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10696. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10697. // diffuse
  10698. "#ifdef WRAP_AROUND",
  10699. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  10700. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  10701. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10702. "#else",
  10703. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  10704. "#endif",
  10705. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  10706. // specular
  10707. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  10708. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10709. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  10710. "#ifdef PHYSICALLY_BASED_SHADING",
  10711. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10712. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10713. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  10714. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  10715. "#else",
  10716. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  10717. "#endif",
  10718. "}",
  10719. "}",
  10720. "#endif",
  10721. // directional lights
  10722. "#if MAX_DIR_LIGHTS > 0",
  10723. "vec3 dirDiffuse = vec3( 0.0 );",
  10724. "vec3 dirSpecular = vec3( 0.0 );",
  10725. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  10726. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10727. "vec3 dirVector = normalize( lDirection.xyz );",
  10728. // diffuse
  10729. "#ifdef WRAP_AROUND",
  10730. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  10731. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  10732. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  10733. "#else",
  10734. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  10735. "#endif",
  10736. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  10737. // specular
  10738. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10739. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10740. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  10741. "#ifdef PHYSICALLY_BASED_SHADING",
  10742. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10743. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10744. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10745. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10746. "#else",
  10747. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  10748. "#endif",
  10749. "}",
  10750. "#endif",
  10751. // hemisphere lights
  10752. "#if MAX_HEMI_LIGHTS > 0",
  10753. "vec3 hemiDiffuse = vec3( 0.0 );",
  10754. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10755. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10756. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10757. "vec3 lVector = normalize( lDirection.xyz );",
  10758. // diffuse
  10759. "float dotProduct = dot( normal, lVector );",
  10760. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10761. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10762. "hemiDiffuse += uDiffuseColor * hemiColor;",
  10763. // specular (sky light)
  10764. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10765. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10766. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  10767. // specular (ground light)
  10768. "vec3 lVectorGround = -lVector;",
  10769. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10770. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10771. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  10772. "#ifdef PHYSICALLY_BASED_SHADING",
  10773. "float dotProductGround = dot( normal, lVectorGround );",
  10774. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10775. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10776. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10777. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10778. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10779. "#else",
  10780. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10781. "#endif",
  10782. "}",
  10783. "#endif",
  10784. // all lights contribution summation
  10785. "vec3 totalDiffuse = vec3( 0.0 );",
  10786. "vec3 totalSpecular = vec3( 0.0 );",
  10787. "#if MAX_DIR_LIGHTS > 0",
  10788. "totalDiffuse += dirDiffuse;",
  10789. "totalSpecular += dirSpecular;",
  10790. "#endif",
  10791. "#if MAX_HEMI_LIGHTS > 0",
  10792. "totalDiffuse += hemiDiffuse;",
  10793. "totalSpecular += hemiSpecular;",
  10794. "#endif",
  10795. "#if MAX_POINT_LIGHTS > 0",
  10796. "totalDiffuse += pointDiffuse;",
  10797. "totalSpecular += pointSpecular;",
  10798. "#endif",
  10799. "#if MAX_SPOT_LIGHTS > 0",
  10800. "totalDiffuse += spotDiffuse;",
  10801. "totalSpecular += spotSpecular;",
  10802. "#endif",
  10803. "#ifdef METAL",
  10804. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  10805. "#else",
  10806. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  10807. "#endif",
  10808. "if ( enableReflection ) {",
  10809. "vec3 vReflect;",
  10810. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10811. "if ( useRefract ) {",
  10812. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  10813. "} else {",
  10814. "vReflect = reflect( cameraToVertex, normal );",
  10815. "}",
  10816. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10817. "#ifdef GAMMA_INPUT",
  10818. "cubeColor.xyz *= cubeColor.xyz;",
  10819. "#endif",
  10820. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  10821. "}",
  10822. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10823. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10824. THREE.ShaderChunk[ "fog_fragment" ],
  10825. "}"
  10826. ].join("\n"),
  10827. vertexShader: [
  10828. "attribute vec4 tangent;",
  10829. "uniform vec2 uOffset;",
  10830. "uniform vec2 uRepeat;",
  10831. "uniform bool enableDisplacement;",
  10832. "#ifdef VERTEX_TEXTURES",
  10833. "uniform sampler2D tDisplacement;",
  10834. "uniform float uDisplacementScale;",
  10835. "uniform float uDisplacementBias;",
  10836. "#endif",
  10837. "varying vec3 vTangent;",
  10838. "varying vec3 vBinormal;",
  10839. "varying vec3 vNormal;",
  10840. "varying vec2 vUv;",
  10841. "varying vec3 vWorldPosition;",
  10842. "varying vec3 vViewPosition;",
  10843. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10844. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10845. "void main() {",
  10846. THREE.ShaderChunk[ "skinbase_vertex" ],
  10847. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10848. // normal, tangent and binormal vectors
  10849. "#ifdef USE_SKINNING",
  10850. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  10851. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  10852. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  10853. "#else",
  10854. "vNormal = normalize( normalMatrix * normal );",
  10855. "vTangent = normalize( normalMatrix * tangent.xyz );",
  10856. "#endif",
  10857. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  10858. "vUv = uv * uRepeat + uOffset;",
  10859. // displacement mapping
  10860. "vec3 displacedPosition;",
  10861. "#ifdef VERTEX_TEXTURES",
  10862. "if ( enableDisplacement ) {",
  10863. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  10864. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  10865. "displacedPosition = position + normalize( normal ) * df;",
  10866. "} else {",
  10867. "#ifdef USE_SKINNING",
  10868. "vec4 skinVertex = vec4( position, 1.0 );",
  10869. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10870. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10871. "displacedPosition = skinned.xyz;",
  10872. "#else",
  10873. "displacedPosition = position;",
  10874. "#endif",
  10875. "}",
  10876. "#else",
  10877. "#ifdef USE_SKINNING",
  10878. "vec4 skinVertex = vec4( position, 1.0 );",
  10879. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10880. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10881. "displacedPosition = skinned.xyz;",
  10882. "#else",
  10883. "displacedPosition = position;",
  10884. "#endif",
  10885. "#endif",
  10886. //
  10887. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  10888. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  10889. "gl_Position = projectionMatrix * mvPosition;",
  10890. //
  10891. "vWorldPosition = worldPosition.xyz;",
  10892. "vViewPosition = -mvPosition.xyz;",
  10893. // shadows
  10894. "#ifdef USE_SHADOWMAP",
  10895. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10896. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10897. "}",
  10898. "#endif",
  10899. "}"
  10900. ].join("\n")
  10901. },
  10902. /* -------------------------------------------------------------------------
  10903. // Cube map shader
  10904. ------------------------------------------------------------------------- */
  10905. 'cube': {
  10906. uniforms: { "tCube": { type: "t", value: null },
  10907. "tFlip": { type: "f", value: -1 } },
  10908. vertexShader: [
  10909. "varying vec3 vWorldPosition;",
  10910. "void main() {",
  10911. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10912. "vWorldPosition = worldPosition.xyz;",
  10913. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10914. "}"
  10915. ].join("\n"),
  10916. fragmentShader: [
  10917. "uniform samplerCube tCube;",
  10918. "uniform float tFlip;",
  10919. "varying vec3 vWorldPosition;",
  10920. "void main() {",
  10921. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10922. "}"
  10923. ].join("\n")
  10924. },
  10925. // Depth encoding into RGBA texture
  10926. // based on SpiderGL shadow map example
  10927. // http://spidergl.org/example.php?id=6
  10928. // originally from
  10929. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10930. // see also here:
  10931. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10932. 'depthRGBA': {
  10933. uniforms: {},
  10934. vertexShader: [
  10935. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10936. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10937. "void main() {",
  10938. THREE.ShaderChunk[ "skinbase_vertex" ],
  10939. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10940. THREE.ShaderChunk[ "skinning_vertex" ],
  10941. THREE.ShaderChunk[ "default_vertex" ],
  10942. "}"
  10943. ].join("\n"),
  10944. fragmentShader: [
  10945. "vec4 pack_depth( const in float depth ) {",
  10946. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10947. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10948. "vec4 res = fract( depth * bit_shift );",
  10949. "res -= res.xxyz * bit_mask;",
  10950. "return res;",
  10951. "}",
  10952. "void main() {",
  10953. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10954. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10955. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10956. //"gl_FragData[ 0 ] = pack_depth( z );",
  10957. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10958. "}"
  10959. ].join("\n")
  10960. }
  10961. };
  10962. /**
  10963. * @author supereggbert / http://www.paulbrunt.co.uk/
  10964. * @author mrdoob / http://mrdoob.com/
  10965. * @author alteredq / http://alteredqualia.com/
  10966. * @author szimek / https://github.com/szimek/
  10967. */
  10968. THREE.WebGLRenderer = function ( parameters ) {
  10969. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10970. parameters = parameters || {};
  10971. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10972. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10973. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10974. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10975. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10976. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10977. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10978. _clearColor = new THREE.Color( 0x000000 ),
  10979. _clearAlpha = 0;
  10980. if ( parameters.clearColor !== undefined ) {
  10981. console.warn( 'DEPRECATED: clearColor in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  10982. _clearColor.setHex( parameters.clearColor );
  10983. }
  10984. if ( parameters.clearAlpha !== undefined ) {
  10985. console.warn( 'DEPRECATED: clearAlpha in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  10986. _clearAlpha = parameters.clearAlpha;
  10987. }
  10988. // public properties
  10989. this.domElement = _canvas;
  10990. this.context = null;
  10991. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10992. ? parameters.devicePixelRatio
  10993. : window.devicePixelRatio !== undefined
  10994. ? window.devicePixelRatio
  10995. : 1;
  10996. // clearing
  10997. this.autoClear = true;
  10998. this.autoClearColor = true;
  10999. this.autoClearDepth = true;
  11000. this.autoClearStencil = true;
  11001. // scene graph
  11002. this.sortObjects = true;
  11003. this.autoUpdateObjects = true;
  11004. // physically based shading
  11005. this.gammaInput = false;
  11006. this.gammaOutput = false;
  11007. this.physicallyBasedShading = false;
  11008. // shadow map
  11009. this.shadowMapEnabled = false;
  11010. this.shadowMapAutoUpdate = true;
  11011. this.shadowMapType = THREE.PCFShadowMap;
  11012. this.shadowMapCullFace = THREE.CullFaceFront;
  11013. this.shadowMapDebug = false;
  11014. this.shadowMapCascade = false;
  11015. // morphs
  11016. this.maxMorphTargets = 8;
  11017. this.maxMorphNormals = 4;
  11018. // flags
  11019. this.autoScaleCubemaps = true;
  11020. // custom render plugins
  11021. this.renderPluginsPre = [];
  11022. this.renderPluginsPost = [];
  11023. // info
  11024. this.info = {
  11025. memory: {
  11026. programs: 0,
  11027. geometries: 0,
  11028. textures: 0
  11029. },
  11030. render: {
  11031. calls: 0,
  11032. vertices: 0,
  11033. faces: 0,
  11034. points: 0
  11035. }
  11036. };
  11037. // internal properties
  11038. var _this = this,
  11039. _programs = [],
  11040. _programs_counter = 0,
  11041. // internal state cache
  11042. _currentProgram = null,
  11043. _currentFramebuffer = null,
  11044. _currentMaterialId = -1,
  11045. _currentGeometryGroupHash = null,
  11046. _currentCamera = null,
  11047. _geometryGroupCounter = 0,
  11048. _usedTextureUnits = 0,
  11049. // GL state cache
  11050. _oldDoubleSided = -1,
  11051. _oldFlipSided = -1,
  11052. _oldBlending = -1,
  11053. _oldBlendEquation = -1,
  11054. _oldBlendSrc = -1,
  11055. _oldBlendDst = -1,
  11056. _oldDepthTest = -1,
  11057. _oldDepthWrite = -1,
  11058. _oldPolygonOffset = null,
  11059. _oldPolygonOffsetFactor = null,
  11060. _oldPolygonOffsetUnits = null,
  11061. _oldLineWidth = null,
  11062. _viewportX = 0,
  11063. _viewportY = 0,
  11064. _viewportWidth = 0,
  11065. _viewportHeight = 0,
  11066. _currentWidth = 0,
  11067. _currentHeight = 0,
  11068. _enabledAttributes = {},
  11069. // frustum
  11070. _frustum = new THREE.Frustum(),
  11071. // camera matrices cache
  11072. _projScreenMatrix = new THREE.Matrix4(),
  11073. _projScreenMatrixPS = new THREE.Matrix4(),
  11074. _vector3 = new THREE.Vector3(),
  11075. // light arrays cache
  11076. _direction = new THREE.Vector3(),
  11077. _lightsNeedUpdate = true,
  11078. _lights = {
  11079. ambient: [ 0, 0, 0 ],
  11080. directional: { length: 0, colors: new Array(), positions: new Array() },
  11081. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11082. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11083. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11084. };
  11085. // initialize
  11086. var _gl;
  11087. var _glExtensionTextureFloat;
  11088. var _glExtensionStandardDerivatives;
  11089. var _glExtensionTextureFilterAnisotropic;
  11090. var _glExtensionCompressedTextureS3TC;
  11091. initGL();
  11092. setDefaultGLState();
  11093. this.context = _gl;
  11094. // GPU capabilities
  11095. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11096. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11097. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11098. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11099. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11100. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11101. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11102. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11103. //
  11104. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11105. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11106. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11107. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11108. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11109. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11110. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11111. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11112. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11113. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11114. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11115. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11116. // clamp precision to maximum available
  11117. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11118. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11119. if ( _precision === "highp" && ! highpAvailable ) {
  11120. if ( mediumpAvailable ) {
  11121. _precision = "mediump";
  11122. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11123. } else {
  11124. _precision = "lowp";
  11125. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11126. }
  11127. }
  11128. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11129. _precision = "lowp";
  11130. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11131. }
  11132. // API
  11133. this.getContext = function () {
  11134. return _gl;
  11135. };
  11136. this.supportsVertexTextures = function () {
  11137. return _supportsVertexTextures;
  11138. };
  11139. this.supportsFloatTextures = function () {
  11140. return _glExtensionTextureFloat;
  11141. };
  11142. this.supportsStandardDerivatives = function () {
  11143. return _glExtensionStandardDerivatives;
  11144. };
  11145. this.supportsCompressedTextureS3TC = function () {
  11146. return _glExtensionCompressedTextureS3TC;
  11147. };
  11148. this.getMaxAnisotropy = function () {
  11149. return _maxAnisotropy;
  11150. };
  11151. this.getPrecision = function () {
  11152. return _precision;
  11153. };
  11154. this.setSize = function ( width, height, updateStyle ) {
  11155. _canvas.width = width * this.devicePixelRatio;
  11156. _canvas.height = height * this.devicePixelRatio;
  11157. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11158. _canvas.style.width = width + 'px';
  11159. _canvas.style.height = height + 'px';
  11160. }
  11161. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11162. };
  11163. this.setViewport = function ( x, y, width, height ) {
  11164. _viewportX = x !== undefined ? x : 0;
  11165. _viewportY = y !== undefined ? y : 0;
  11166. _viewportWidth = width !== undefined ? width : _canvas.width;
  11167. _viewportHeight = height !== undefined ? height : _canvas.height;
  11168. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11169. };
  11170. this.setScissor = function ( x, y, width, height ) {
  11171. _gl.scissor( x, y, width, height );
  11172. };
  11173. this.enableScissorTest = function ( enable ) {
  11174. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11175. };
  11176. // Clearing
  11177. this.setClearColor = function ( color, alpha ) {
  11178. _clearColor.set( color );
  11179. _clearAlpha = alpha !== undefined ? alpha : 1;
  11180. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11181. };
  11182. this.setClearColorHex = function ( hex, alpha ) {
  11183. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11184. this.setClearColor( hex, alpha );
  11185. };
  11186. this.getClearColor = function () {
  11187. return _clearColor;
  11188. };
  11189. this.getClearAlpha = function () {
  11190. return _clearAlpha;
  11191. };
  11192. this.clear = function ( color, depth, stencil ) {
  11193. var bits = 0;
  11194. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11195. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11196. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11197. _gl.clear( bits );
  11198. };
  11199. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11200. this.setRenderTarget( renderTarget );
  11201. this.clear( color, depth, stencil );
  11202. };
  11203. // Plugins
  11204. this.addPostPlugin = function ( plugin ) {
  11205. plugin.init( this );
  11206. this.renderPluginsPost.push( plugin );
  11207. };
  11208. this.addPrePlugin = function ( plugin ) {
  11209. plugin.init( this );
  11210. this.renderPluginsPre.push( plugin );
  11211. };
  11212. // Rendering
  11213. this.updateShadowMap = function ( scene, camera ) {
  11214. _currentProgram = null;
  11215. _oldBlending = -1;
  11216. _oldDepthTest = -1;
  11217. _oldDepthWrite = -1;
  11218. _currentGeometryGroupHash = -1;
  11219. _currentMaterialId = -1;
  11220. _lightsNeedUpdate = true;
  11221. _oldDoubleSided = -1;
  11222. _oldFlipSided = -1;
  11223. this.shadowMapPlugin.update( scene, camera );
  11224. };
  11225. // Internal functions
  11226. // Buffer allocation
  11227. function createParticleBuffers ( geometry ) {
  11228. geometry.__webglVertexBuffer = _gl.createBuffer();
  11229. geometry.__webglColorBuffer = _gl.createBuffer();
  11230. _this.info.memory.geometries ++;
  11231. };
  11232. function createLineBuffers ( geometry ) {
  11233. geometry.__webglVertexBuffer = _gl.createBuffer();
  11234. geometry.__webglColorBuffer = _gl.createBuffer();
  11235. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11236. _this.info.memory.geometries ++;
  11237. };
  11238. function createRibbonBuffers ( geometry ) {
  11239. geometry.__webglVertexBuffer = _gl.createBuffer();
  11240. geometry.__webglColorBuffer = _gl.createBuffer();
  11241. geometry.__webglNormalBuffer = _gl.createBuffer();
  11242. _this.info.memory.geometries ++;
  11243. };
  11244. function createMeshBuffers ( geometryGroup ) {
  11245. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11246. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11247. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11248. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11249. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11250. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11251. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11252. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11253. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11254. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11255. var m, ml;
  11256. if ( geometryGroup.numMorphTargets ) {
  11257. geometryGroup.__webglMorphTargetsBuffers = [];
  11258. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11259. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11260. }
  11261. }
  11262. if ( geometryGroup.numMorphNormals ) {
  11263. geometryGroup.__webglMorphNormalsBuffers = [];
  11264. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11265. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11266. }
  11267. }
  11268. _this.info.memory.geometries ++;
  11269. };
  11270. // Events
  11271. var onGeometryDispose = function ( event ) {
  11272. var geometry = event.target;
  11273. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11274. deallocateGeometry( geometry );
  11275. _this.info.memory.geometries --;
  11276. };
  11277. var onTextureDispose = function ( event ) {
  11278. var texture = event.target;
  11279. texture.removeEventListener( 'dispose', onTextureDispose );
  11280. deallocateTexture( texture );
  11281. _this.info.memory.textures --;
  11282. };
  11283. var onRenderTargetDispose = function ( event ) {
  11284. var renderTarget = event.target;
  11285. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11286. deallocateRenderTarget( renderTarget );
  11287. _this.info.memory.textures --;
  11288. };
  11289. var onMaterialDispose = function ( event ) {
  11290. var material = event.target;
  11291. material.removeEventListener( 'dispose', onMaterialDispose );
  11292. deallocateMaterial( material );
  11293. };
  11294. // Buffer deallocation
  11295. var deallocateGeometry = function ( geometry ) {
  11296. geometry.__webglInit = undefined;
  11297. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11298. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11299. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11300. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11301. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11302. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11303. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11304. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11305. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11306. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11307. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11308. // geometry groups
  11309. if ( geometry.geometryGroups !== undefined ) {
  11310. for ( var g in geometry.geometryGroups ) {
  11311. var geometryGroup = geometry.geometryGroups[ g ];
  11312. if ( geometryGroup.numMorphTargets !== undefined ) {
  11313. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11314. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11315. }
  11316. }
  11317. if ( geometryGroup.numMorphNormals !== undefined ) {
  11318. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11319. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11320. }
  11321. }
  11322. deleteCustomAttributesBuffers( geometryGroup );
  11323. }
  11324. }
  11325. deleteCustomAttributesBuffers( geometry );
  11326. };
  11327. var deallocateTexture = function ( texture ) {
  11328. if ( texture.image && texture.image.__webglTextureCube ) {
  11329. // cube texture
  11330. _gl.deleteTexture( texture.image.__webglTextureCube );
  11331. } else {
  11332. // 2D texture
  11333. if ( ! texture.__webglInit ) return;
  11334. texture.__webglInit = false;
  11335. _gl.deleteTexture( texture.__webglTexture );
  11336. }
  11337. };
  11338. var deallocateRenderTarget = function ( renderTarget ) {
  11339. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11340. _gl.deleteTexture( renderTarget.__webglTexture );
  11341. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11342. for ( var i = 0; i < 6; i ++ ) {
  11343. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11344. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11345. }
  11346. } else {
  11347. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11348. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11349. }
  11350. };
  11351. var deallocateMaterial = function ( material ) {
  11352. var program = material.program;
  11353. if ( program === undefined ) return;
  11354. material.program = undefined;
  11355. // only deallocate GL program if this was the last use of shared program
  11356. // assumed there is only single copy of any program in the _programs list
  11357. // (that's how it's constructed)
  11358. var i, il, programInfo;
  11359. var deleteProgram = false;
  11360. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11361. programInfo = _programs[ i ];
  11362. if ( programInfo.program === program ) {
  11363. programInfo.usedTimes --;
  11364. if ( programInfo.usedTimes === 0 ) {
  11365. deleteProgram = true;
  11366. }
  11367. break;
  11368. }
  11369. }
  11370. if ( deleteProgram === true ) {
  11371. // avoid using array.splice, this is costlier than creating new array from scratch
  11372. var newPrograms = [];
  11373. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11374. programInfo = _programs[ i ];
  11375. if ( programInfo.program !== program ) {
  11376. newPrograms.push( programInfo );
  11377. }
  11378. }
  11379. _programs = newPrograms;
  11380. _gl.deleteProgram( program );
  11381. _this.info.memory.programs --;
  11382. }
  11383. };
  11384. //
  11385. /*
  11386. function deleteParticleBuffers ( geometry ) {
  11387. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11388. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11389. deleteCustomAttributesBuffers( geometry );
  11390. _this.info.memory.geometries --;
  11391. };
  11392. function deleteLineBuffers ( geometry ) {
  11393. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11394. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11395. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11396. deleteCustomAttributesBuffers( geometry );
  11397. _this.info.memory.geometries --;
  11398. };
  11399. function deleteRibbonBuffers ( geometry ) {
  11400. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11401. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11402. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11403. deleteCustomAttributesBuffers( geometry );
  11404. _this.info.memory.geometries --;
  11405. };
  11406. function deleteMeshBuffers ( geometryGroup ) {
  11407. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  11408. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  11409. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  11410. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  11411. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  11412. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  11413. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  11414. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  11415. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  11416. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  11417. var m, ml;
  11418. if ( geometryGroup.numMorphTargets ) {
  11419. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11420. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11421. }
  11422. }
  11423. if ( geometryGroup.numMorphNormals ) {
  11424. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11425. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11426. }
  11427. }
  11428. deleteCustomAttributesBuffers( geometryGroup );
  11429. _this.info.memory.geometries --;
  11430. };
  11431. */
  11432. function deleteCustomAttributesBuffers( geometry ) {
  11433. if ( geometry.__webglCustomAttributesList ) {
  11434. for ( var id in geometry.__webglCustomAttributesList ) {
  11435. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11436. }
  11437. }
  11438. };
  11439. // Buffer initialization
  11440. function initCustomAttributes ( geometry, object ) {
  11441. var nvertices = geometry.vertices.length;
  11442. var material = object.material;
  11443. if ( material.attributes ) {
  11444. if ( geometry.__webglCustomAttributesList === undefined ) {
  11445. geometry.__webglCustomAttributesList = [];
  11446. }
  11447. for ( var a in material.attributes ) {
  11448. var attribute = material.attributes[ a ];
  11449. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11450. attribute.__webglInitialized = true;
  11451. var size = 1; // "f" and "i"
  11452. if ( attribute.type === "v2" ) size = 2;
  11453. else if ( attribute.type === "v3" ) size = 3;
  11454. else if ( attribute.type === "v4" ) size = 4;
  11455. else if ( attribute.type === "c" ) size = 3;
  11456. attribute.size = size;
  11457. attribute.array = new Float32Array( nvertices * size );
  11458. attribute.buffer = _gl.createBuffer();
  11459. attribute.buffer.belongsToAttribute = a;
  11460. attribute.needsUpdate = true;
  11461. }
  11462. geometry.__webglCustomAttributesList.push( attribute );
  11463. }
  11464. }
  11465. };
  11466. function initParticleBuffers ( geometry, object ) {
  11467. var nvertices = geometry.vertices.length;
  11468. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11469. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11470. geometry.__sortArray = [];
  11471. geometry.__webglParticleCount = nvertices;
  11472. initCustomAttributes ( geometry, object );
  11473. };
  11474. function initLineBuffers ( geometry, object ) {
  11475. var nvertices = geometry.vertices.length;
  11476. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11477. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11478. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11479. geometry.__webglLineCount = nvertices;
  11480. initCustomAttributes ( geometry, object );
  11481. };
  11482. function initRibbonBuffers ( geometry, object ) {
  11483. var nvertices = geometry.vertices.length;
  11484. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11485. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11486. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11487. geometry.__webglVertexCount = nvertices;
  11488. initCustomAttributes ( geometry, object );
  11489. };
  11490. function initMeshBuffers ( geometryGroup, object ) {
  11491. var geometry = object.geometry,
  11492. faces3 = geometryGroup.faces3,
  11493. faces4 = geometryGroup.faces4,
  11494. nvertices = faces3.length * 3 + faces4.length * 4,
  11495. ntris = faces3.length * 1 + faces4.length * 2,
  11496. nlines = faces3.length * 3 + faces4.length * 4,
  11497. material = getBufferMaterial( object, geometryGroup ),
  11498. uvType = bufferGuessUVType( material ),
  11499. normalType = bufferGuessNormalType( material ),
  11500. vertexColorType = bufferGuessVertexColorType( material );
  11501. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11502. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11503. if ( normalType ) {
  11504. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11505. }
  11506. if ( geometry.hasTangents ) {
  11507. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11508. }
  11509. if ( vertexColorType ) {
  11510. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11511. }
  11512. if ( uvType ) {
  11513. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11514. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11515. }
  11516. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11517. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11518. }
  11519. }
  11520. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11521. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11522. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11523. }
  11524. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11525. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11526. var m, ml;
  11527. if ( geometryGroup.numMorphTargets ) {
  11528. geometryGroup.__morphTargetsArrays = [];
  11529. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11530. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11531. }
  11532. }
  11533. if ( geometryGroup.numMorphNormals ) {
  11534. geometryGroup.__morphNormalsArrays = [];
  11535. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11536. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11537. }
  11538. }
  11539. geometryGroup.__webglFaceCount = ntris * 3;
  11540. geometryGroup.__webglLineCount = nlines * 2;
  11541. // custom attributes
  11542. if ( material.attributes ) {
  11543. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11544. geometryGroup.__webglCustomAttributesList = [];
  11545. }
  11546. for ( var a in material.attributes ) {
  11547. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11548. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11549. var originalAttribute = material.attributes[ a ];
  11550. var attribute = {};
  11551. for ( var property in originalAttribute ) {
  11552. attribute[ property ] = originalAttribute[ property ];
  11553. }
  11554. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11555. attribute.__webglInitialized = true;
  11556. var size = 1; // "f" and "i"
  11557. if( attribute.type === "v2" ) size = 2;
  11558. else if( attribute.type === "v3" ) size = 3;
  11559. else if( attribute.type === "v4" ) size = 4;
  11560. else if( attribute.type === "c" ) size = 3;
  11561. attribute.size = size;
  11562. attribute.array = new Float32Array( nvertices * size );
  11563. attribute.buffer = _gl.createBuffer();
  11564. attribute.buffer.belongsToAttribute = a;
  11565. originalAttribute.needsUpdate = true;
  11566. attribute.__original = originalAttribute;
  11567. }
  11568. geometryGroup.__webglCustomAttributesList.push( attribute );
  11569. }
  11570. }
  11571. geometryGroup.__inittedArrays = true;
  11572. };
  11573. function getBufferMaterial( object, geometryGroup ) {
  11574. return object.material instanceof THREE.MeshFaceMaterial
  11575. ? object.material.materials[ geometryGroup.materialIndex ]
  11576. : object.material;
  11577. };
  11578. function materialNeedsSmoothNormals ( material ) {
  11579. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  11580. };
  11581. function bufferGuessNormalType ( material ) {
  11582. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  11583. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  11584. return false;
  11585. }
  11586. if ( materialNeedsSmoothNormals( material ) ) {
  11587. return THREE.SmoothShading;
  11588. } else {
  11589. return THREE.FlatShading;
  11590. }
  11591. };
  11592. function bufferGuessVertexColorType( material ) {
  11593. if ( material.vertexColors ) {
  11594. return material.vertexColors;
  11595. }
  11596. return false;
  11597. };
  11598. function bufferGuessUVType( material ) {
  11599. // material must use some texture to require uvs
  11600. if ( material.map ||
  11601. material.lightMap ||
  11602. material.bumpMap ||
  11603. material.normalMap ||
  11604. material.specularMap ||
  11605. material instanceof THREE.ShaderMaterial ) {
  11606. return true;
  11607. }
  11608. return false;
  11609. };
  11610. //
  11611. function initDirectBuffers( geometry ) {
  11612. var a, attribute, type;
  11613. for ( a in geometry.attributes ) {
  11614. if ( a === "index" ) {
  11615. type = _gl.ELEMENT_ARRAY_BUFFER;
  11616. } else {
  11617. type = _gl.ARRAY_BUFFER;
  11618. }
  11619. attribute = geometry.attributes[ a ];
  11620. attribute.buffer = _gl.createBuffer();
  11621. _gl.bindBuffer( type, attribute.buffer );
  11622. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  11623. }
  11624. };
  11625. // Buffer setting
  11626. function setParticleBuffers ( geometry, hint, object ) {
  11627. var v, c, vertex, offset, index, color,
  11628. vertices = geometry.vertices,
  11629. vl = vertices.length,
  11630. colors = geometry.colors,
  11631. cl = colors.length,
  11632. vertexArray = geometry.__vertexArray,
  11633. colorArray = geometry.__colorArray,
  11634. sortArray = geometry.__sortArray,
  11635. dirtyVertices = geometry.verticesNeedUpdate,
  11636. dirtyElements = geometry.elementsNeedUpdate,
  11637. dirtyColors = geometry.colorsNeedUpdate,
  11638. customAttributes = geometry.__webglCustomAttributesList,
  11639. i, il,
  11640. a, ca, cal, value,
  11641. customAttribute;
  11642. if ( object.sortParticles ) {
  11643. _projScreenMatrixPS.copy( _projScreenMatrix );
  11644. _projScreenMatrixPS.multiply( object.matrixWorld );
  11645. for ( v = 0; v < vl; v ++ ) {
  11646. vertex = vertices[ v ];
  11647. _vector3.copy( vertex );
  11648. _vector3.applyProjection( _projScreenMatrixPS );
  11649. sortArray[ v ] = [ _vector3.z, v ];
  11650. }
  11651. sortArray.sort( numericalSort );
  11652. for ( v = 0; v < vl; v ++ ) {
  11653. vertex = vertices[ sortArray[v][1] ];
  11654. offset = v * 3;
  11655. vertexArray[ offset ] = vertex.x;
  11656. vertexArray[ offset + 1 ] = vertex.y;
  11657. vertexArray[ offset + 2 ] = vertex.z;
  11658. }
  11659. for ( c = 0; c < cl; c ++ ) {
  11660. offset = c * 3;
  11661. color = colors[ sortArray[c][1] ];
  11662. colorArray[ offset ] = color.r;
  11663. colorArray[ offset + 1 ] = color.g;
  11664. colorArray[ offset + 2 ] = color.b;
  11665. }
  11666. if ( customAttributes ) {
  11667. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11668. customAttribute = customAttributes[ i ];
  11669. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  11670. offset = 0;
  11671. cal = customAttribute.value.length;
  11672. if ( customAttribute.size === 1 ) {
  11673. for ( ca = 0; ca < cal; ca ++ ) {
  11674. index = sortArray[ ca ][ 1 ];
  11675. customAttribute.array[ ca ] = customAttribute.value[ index ];
  11676. }
  11677. } else if ( customAttribute.size === 2 ) {
  11678. for ( ca = 0; ca < cal; ca ++ ) {
  11679. index = sortArray[ ca ][ 1 ];
  11680. value = customAttribute.value[ index ];
  11681. customAttribute.array[ offset ] = value.x;
  11682. customAttribute.array[ offset + 1 ] = value.y;
  11683. offset += 2;
  11684. }
  11685. } else if ( customAttribute.size === 3 ) {
  11686. if ( customAttribute.type === "c" ) {
  11687. for ( ca = 0; ca < cal; ca ++ ) {
  11688. index = sortArray[ ca ][ 1 ];
  11689. value = customAttribute.value[ index ];
  11690. customAttribute.array[ offset ] = value.r;
  11691. customAttribute.array[ offset + 1 ] = value.g;
  11692. customAttribute.array[ offset + 2 ] = value.b;
  11693. offset += 3;
  11694. }
  11695. } else {
  11696. for ( ca = 0; ca < cal; ca ++ ) {
  11697. index = sortArray[ ca ][ 1 ];
  11698. value = customAttribute.value[ index ];
  11699. customAttribute.array[ offset ] = value.x;
  11700. customAttribute.array[ offset + 1 ] = value.y;
  11701. customAttribute.array[ offset + 2 ] = value.z;
  11702. offset += 3;
  11703. }
  11704. }
  11705. } else if ( customAttribute.size === 4 ) {
  11706. for ( ca = 0; ca < cal; ca ++ ) {
  11707. index = sortArray[ ca ][ 1 ];
  11708. value = customAttribute.value[ index ];
  11709. customAttribute.array[ offset ] = value.x;
  11710. customAttribute.array[ offset + 1 ] = value.y;
  11711. customAttribute.array[ offset + 2 ] = value.z;
  11712. customAttribute.array[ offset + 3 ] = value.w;
  11713. offset += 4;
  11714. }
  11715. }
  11716. }
  11717. }
  11718. } else {
  11719. if ( dirtyVertices ) {
  11720. for ( v = 0; v < vl; v ++ ) {
  11721. vertex = vertices[ v ];
  11722. offset = v * 3;
  11723. vertexArray[ offset ] = vertex.x;
  11724. vertexArray[ offset + 1 ] = vertex.y;
  11725. vertexArray[ offset + 2 ] = vertex.z;
  11726. }
  11727. }
  11728. if ( dirtyColors ) {
  11729. for ( c = 0; c < cl; c ++ ) {
  11730. color = colors[ c ];
  11731. offset = c * 3;
  11732. colorArray[ offset ] = color.r;
  11733. colorArray[ offset + 1 ] = color.g;
  11734. colorArray[ offset + 2 ] = color.b;
  11735. }
  11736. }
  11737. if ( customAttributes ) {
  11738. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11739. customAttribute = customAttributes[ i ];
  11740. if ( customAttribute.needsUpdate &&
  11741. ( customAttribute.boundTo === undefined ||
  11742. customAttribute.boundTo === "vertices") ) {
  11743. cal = customAttribute.value.length;
  11744. offset = 0;
  11745. if ( customAttribute.size === 1 ) {
  11746. for ( ca = 0; ca < cal; ca ++ ) {
  11747. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11748. }
  11749. } else if ( customAttribute.size === 2 ) {
  11750. for ( ca = 0; ca < cal; ca ++ ) {
  11751. value = customAttribute.value[ ca ];
  11752. customAttribute.array[ offset ] = value.x;
  11753. customAttribute.array[ offset + 1 ] = value.y;
  11754. offset += 2;
  11755. }
  11756. } else if ( customAttribute.size === 3 ) {
  11757. if ( customAttribute.type === "c" ) {
  11758. for ( ca = 0; ca < cal; ca ++ ) {
  11759. value = customAttribute.value[ ca ];
  11760. customAttribute.array[ offset ] = value.r;
  11761. customAttribute.array[ offset + 1 ] = value.g;
  11762. customAttribute.array[ offset + 2 ] = value.b;
  11763. offset += 3;
  11764. }
  11765. } else {
  11766. for ( ca = 0; ca < cal; ca ++ ) {
  11767. value = customAttribute.value[ ca ];
  11768. customAttribute.array[ offset ] = value.x;
  11769. customAttribute.array[ offset + 1 ] = value.y;
  11770. customAttribute.array[ offset + 2 ] = value.z;
  11771. offset += 3;
  11772. }
  11773. }
  11774. } else if ( customAttribute.size === 4 ) {
  11775. for ( ca = 0; ca < cal; ca ++ ) {
  11776. value = customAttribute.value[ ca ];
  11777. customAttribute.array[ offset ] = value.x;
  11778. customAttribute.array[ offset + 1 ] = value.y;
  11779. customAttribute.array[ offset + 2 ] = value.z;
  11780. customAttribute.array[ offset + 3 ] = value.w;
  11781. offset += 4;
  11782. }
  11783. }
  11784. }
  11785. }
  11786. }
  11787. }
  11788. if ( dirtyVertices || object.sortParticles ) {
  11789. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11790. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11791. }
  11792. if ( dirtyColors || object.sortParticles ) {
  11793. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11794. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11795. }
  11796. if ( customAttributes ) {
  11797. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11798. customAttribute = customAttributes[ i ];
  11799. if ( customAttribute.needsUpdate || object.sortParticles ) {
  11800. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11801. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11802. }
  11803. }
  11804. }
  11805. };
  11806. function setLineBuffers ( geometry, hint ) {
  11807. var v, c, d, vertex, offset, color,
  11808. vertices = geometry.vertices,
  11809. colors = geometry.colors,
  11810. lineDistances = geometry.lineDistances,
  11811. vl = vertices.length,
  11812. cl = colors.length,
  11813. dl = lineDistances.length,
  11814. vertexArray = geometry.__vertexArray,
  11815. colorArray = geometry.__colorArray,
  11816. lineDistanceArray = geometry.__lineDistanceArray,
  11817. dirtyVertices = geometry.verticesNeedUpdate,
  11818. dirtyColors = geometry.colorsNeedUpdate,
  11819. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11820. customAttributes = geometry.__webglCustomAttributesList,
  11821. i, il,
  11822. a, ca, cal, value,
  11823. customAttribute;
  11824. if ( dirtyVertices ) {
  11825. for ( v = 0; v < vl; v ++ ) {
  11826. vertex = vertices[ v ];
  11827. offset = v * 3;
  11828. vertexArray[ offset ] = vertex.x;
  11829. vertexArray[ offset + 1 ] = vertex.y;
  11830. vertexArray[ offset + 2 ] = vertex.z;
  11831. }
  11832. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11833. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11834. }
  11835. if ( dirtyColors ) {
  11836. for ( c = 0; c < cl; c ++ ) {
  11837. color = colors[ c ];
  11838. offset = c * 3;
  11839. colorArray[ offset ] = color.r;
  11840. colorArray[ offset + 1 ] = color.g;
  11841. colorArray[ offset + 2 ] = color.b;
  11842. }
  11843. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11844. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11845. }
  11846. if ( dirtyLineDistances ) {
  11847. for ( d = 0; d < dl; d ++ ) {
  11848. lineDistanceArray[ d ] = lineDistances[ d ];
  11849. }
  11850. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11851. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11852. }
  11853. if ( customAttributes ) {
  11854. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11855. customAttribute = customAttributes[ i ];
  11856. if ( customAttribute.needsUpdate &&
  11857. ( customAttribute.boundTo === undefined ||
  11858. customAttribute.boundTo === "vertices" ) ) {
  11859. offset = 0;
  11860. cal = customAttribute.value.length;
  11861. if ( customAttribute.size === 1 ) {
  11862. for ( ca = 0; ca < cal; ca ++ ) {
  11863. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11864. }
  11865. } else if ( customAttribute.size === 2 ) {
  11866. for ( ca = 0; ca < cal; ca ++ ) {
  11867. value = customAttribute.value[ ca ];
  11868. customAttribute.array[ offset ] = value.x;
  11869. customAttribute.array[ offset + 1 ] = value.y;
  11870. offset += 2;
  11871. }
  11872. } else if ( customAttribute.size === 3 ) {
  11873. if ( customAttribute.type === "c" ) {
  11874. for ( ca = 0; ca < cal; ca ++ ) {
  11875. value = customAttribute.value[ ca ];
  11876. customAttribute.array[ offset ] = value.r;
  11877. customAttribute.array[ offset + 1 ] = value.g;
  11878. customAttribute.array[ offset + 2 ] = value.b;
  11879. offset += 3;
  11880. }
  11881. } else {
  11882. for ( ca = 0; ca < cal; ca ++ ) {
  11883. value = customAttribute.value[ ca ];
  11884. customAttribute.array[ offset ] = value.x;
  11885. customAttribute.array[ offset + 1 ] = value.y;
  11886. customAttribute.array[ offset + 2 ] = value.z;
  11887. offset += 3;
  11888. }
  11889. }
  11890. } else if ( customAttribute.size === 4 ) {
  11891. for ( ca = 0; ca < cal; ca ++ ) {
  11892. value = customAttribute.value[ ca ];
  11893. customAttribute.array[ offset ] = value.x;
  11894. customAttribute.array[ offset + 1 ] = value.y;
  11895. customAttribute.array[ offset + 2 ] = value.z;
  11896. customAttribute.array[ offset + 3 ] = value.w;
  11897. offset += 4;
  11898. }
  11899. }
  11900. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11901. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11902. }
  11903. }
  11904. }
  11905. };
  11906. function setRibbonBuffers ( geometry, hint ) {
  11907. var v, c, n, vertex, offset, color, normal,
  11908. i, il, ca, cal, customAttribute, value,
  11909. vertices = geometry.vertices,
  11910. colors = geometry.colors,
  11911. normals = geometry.normals,
  11912. vl = vertices.length,
  11913. cl = colors.length,
  11914. nl = normals.length,
  11915. vertexArray = geometry.__vertexArray,
  11916. colorArray = geometry.__colorArray,
  11917. normalArray = geometry.__normalArray,
  11918. dirtyVertices = geometry.verticesNeedUpdate,
  11919. dirtyColors = geometry.colorsNeedUpdate,
  11920. dirtyNormals = geometry.normalsNeedUpdate,
  11921. customAttributes = geometry.__webglCustomAttributesList;
  11922. if ( dirtyVertices ) {
  11923. for ( v = 0; v < vl; v ++ ) {
  11924. vertex = vertices[ v ];
  11925. offset = v * 3;
  11926. vertexArray[ offset ] = vertex.x;
  11927. vertexArray[ offset + 1 ] = vertex.y;
  11928. vertexArray[ offset + 2 ] = vertex.z;
  11929. }
  11930. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11931. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11932. }
  11933. if ( dirtyColors ) {
  11934. for ( c = 0; c < cl; c ++ ) {
  11935. color = colors[ c ];
  11936. offset = c * 3;
  11937. colorArray[ offset ] = color.r;
  11938. colorArray[ offset + 1 ] = color.g;
  11939. colorArray[ offset + 2 ] = color.b;
  11940. }
  11941. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11942. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11943. }
  11944. if ( dirtyNormals ) {
  11945. for ( n = 0; n < nl; n ++ ) {
  11946. normal = normals[ n ];
  11947. offset = n * 3;
  11948. normalArray[ offset ] = normal.x;
  11949. normalArray[ offset + 1 ] = normal.y;
  11950. normalArray[ offset + 2 ] = normal.z;
  11951. }
  11952. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11953. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11954. }
  11955. if ( customAttributes ) {
  11956. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11957. customAttribute = customAttributes[ i ];
  11958. if ( customAttribute.needsUpdate &&
  11959. ( customAttribute.boundTo === undefined ||
  11960. customAttribute.boundTo === "vertices" ) ) {
  11961. offset = 0;
  11962. cal = customAttribute.value.length;
  11963. if ( customAttribute.size === 1 ) {
  11964. for ( ca = 0; ca < cal; ca ++ ) {
  11965. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11966. }
  11967. } else if ( customAttribute.size === 2 ) {
  11968. for ( ca = 0; ca < cal; ca ++ ) {
  11969. value = customAttribute.value[ ca ];
  11970. customAttribute.array[ offset ] = value.x;
  11971. customAttribute.array[ offset + 1 ] = value.y;
  11972. offset += 2;
  11973. }
  11974. } else if ( customAttribute.size === 3 ) {
  11975. if ( customAttribute.type === "c" ) {
  11976. for ( ca = 0; ca < cal; ca ++ ) {
  11977. value = customAttribute.value[ ca ];
  11978. customAttribute.array[ offset ] = value.r;
  11979. customAttribute.array[ offset + 1 ] = value.g;
  11980. customAttribute.array[ offset + 2 ] = value.b;
  11981. offset += 3;
  11982. }
  11983. } else {
  11984. for ( ca = 0; ca < cal; ca ++ ) {
  11985. value = customAttribute.value[ ca ];
  11986. customAttribute.array[ offset ] = value.x;
  11987. customAttribute.array[ offset + 1 ] = value.y;
  11988. customAttribute.array[ offset + 2 ] = value.z;
  11989. offset += 3;
  11990. }
  11991. }
  11992. } else if ( customAttribute.size === 4 ) {
  11993. for ( ca = 0; ca < cal; ca ++ ) {
  11994. value = customAttribute.value[ ca ];
  11995. customAttribute.array[ offset ] = value.x;
  11996. customAttribute.array[ offset + 1 ] = value.y;
  11997. customAttribute.array[ offset + 2 ] = value.z;
  11998. customAttribute.array[ offset + 3 ] = value.w;
  11999. offset += 4;
  12000. }
  12001. }
  12002. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12003. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12004. }
  12005. }
  12006. }
  12007. };
  12008. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12009. if ( ! geometryGroup.__inittedArrays ) {
  12010. return;
  12011. }
  12012. var normalType = bufferGuessNormalType( material ),
  12013. vertexColorType = bufferGuessVertexColorType( material ),
  12014. uvType = bufferGuessUVType( material ),
  12015. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12016. var f, fl, fi, face,
  12017. vertexNormals, faceNormal, normal,
  12018. vertexColors, faceColor,
  12019. vertexTangents,
  12020. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12021. c1, c2, c3, c4,
  12022. sw1, sw2, sw3, sw4,
  12023. si1, si2, si3, si4,
  12024. sa1, sa2, sa3, sa4,
  12025. sb1, sb2, sb3, sb4,
  12026. m, ml, i, il,
  12027. vn, uvi, uv2i,
  12028. vk, vkl, vka,
  12029. nka, chf, faceVertexNormals,
  12030. a,
  12031. vertexIndex = 0,
  12032. offset = 0,
  12033. offset_uv = 0,
  12034. offset_uv2 = 0,
  12035. offset_face = 0,
  12036. offset_normal = 0,
  12037. offset_tangent = 0,
  12038. offset_line = 0,
  12039. offset_color = 0,
  12040. offset_skin = 0,
  12041. offset_morphTarget = 0,
  12042. offset_custom = 0,
  12043. offset_customSrc = 0,
  12044. value,
  12045. vertexArray = geometryGroup.__vertexArray,
  12046. uvArray = geometryGroup.__uvArray,
  12047. uv2Array = geometryGroup.__uv2Array,
  12048. normalArray = geometryGroup.__normalArray,
  12049. tangentArray = geometryGroup.__tangentArray,
  12050. colorArray = geometryGroup.__colorArray,
  12051. skinIndexArray = geometryGroup.__skinIndexArray,
  12052. skinWeightArray = geometryGroup.__skinWeightArray,
  12053. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12054. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12055. customAttributes = geometryGroup.__webglCustomAttributesList,
  12056. customAttribute,
  12057. faceArray = geometryGroup.__faceArray,
  12058. lineArray = geometryGroup.__lineArray,
  12059. geometry = object.geometry, // this is shared for all chunks
  12060. dirtyVertices = geometry.verticesNeedUpdate,
  12061. dirtyElements = geometry.elementsNeedUpdate,
  12062. dirtyUvs = geometry.uvsNeedUpdate,
  12063. dirtyNormals = geometry.normalsNeedUpdate,
  12064. dirtyTangents = geometry.tangentsNeedUpdate,
  12065. dirtyColors = geometry.colorsNeedUpdate,
  12066. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12067. vertices = geometry.vertices,
  12068. chunk_faces3 = geometryGroup.faces3,
  12069. chunk_faces4 = geometryGroup.faces4,
  12070. obj_faces = geometry.faces,
  12071. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12072. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12073. obj_colors = geometry.colors,
  12074. obj_skinIndices = geometry.skinIndices,
  12075. obj_skinWeights = geometry.skinWeights,
  12076. morphTargets = geometry.morphTargets,
  12077. morphNormals = geometry.morphNormals;
  12078. if ( dirtyVertices ) {
  12079. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12080. face = obj_faces[ chunk_faces3[ f ] ];
  12081. v1 = vertices[ face.a ];
  12082. v2 = vertices[ face.b ];
  12083. v3 = vertices[ face.c ];
  12084. vertexArray[ offset ] = v1.x;
  12085. vertexArray[ offset + 1 ] = v1.y;
  12086. vertexArray[ offset + 2 ] = v1.z;
  12087. vertexArray[ offset + 3 ] = v2.x;
  12088. vertexArray[ offset + 4 ] = v2.y;
  12089. vertexArray[ offset + 5 ] = v2.z;
  12090. vertexArray[ offset + 6 ] = v3.x;
  12091. vertexArray[ offset + 7 ] = v3.y;
  12092. vertexArray[ offset + 8 ] = v3.z;
  12093. offset += 9;
  12094. }
  12095. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12096. face = obj_faces[ chunk_faces4[ f ] ];
  12097. v1 = vertices[ face.a ];
  12098. v2 = vertices[ face.b ];
  12099. v3 = vertices[ face.c ];
  12100. v4 = vertices[ face.d ];
  12101. vertexArray[ offset ] = v1.x;
  12102. vertexArray[ offset + 1 ] = v1.y;
  12103. vertexArray[ offset + 2 ] = v1.z;
  12104. vertexArray[ offset + 3 ] = v2.x;
  12105. vertexArray[ offset + 4 ] = v2.y;
  12106. vertexArray[ offset + 5 ] = v2.z;
  12107. vertexArray[ offset + 6 ] = v3.x;
  12108. vertexArray[ offset + 7 ] = v3.y;
  12109. vertexArray[ offset + 8 ] = v3.z;
  12110. vertexArray[ offset + 9 ] = v4.x;
  12111. vertexArray[ offset + 10 ] = v4.y;
  12112. vertexArray[ offset + 11 ] = v4.z;
  12113. offset += 12;
  12114. }
  12115. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12116. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12117. }
  12118. if ( dirtyMorphTargets ) {
  12119. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12120. offset_morphTarget = 0;
  12121. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12122. chf = chunk_faces3[ f ];
  12123. face = obj_faces[ chf ];
  12124. // morph positions
  12125. v1 = morphTargets[ vk ].vertices[ face.a ];
  12126. v2 = morphTargets[ vk ].vertices[ face.b ];
  12127. v3 = morphTargets[ vk ].vertices[ face.c ];
  12128. vka = morphTargetsArrays[ vk ];
  12129. vka[ offset_morphTarget ] = v1.x;
  12130. vka[ offset_morphTarget + 1 ] = v1.y;
  12131. vka[ offset_morphTarget + 2 ] = v1.z;
  12132. vka[ offset_morphTarget + 3 ] = v2.x;
  12133. vka[ offset_morphTarget + 4 ] = v2.y;
  12134. vka[ offset_morphTarget + 5 ] = v2.z;
  12135. vka[ offset_morphTarget + 6 ] = v3.x;
  12136. vka[ offset_morphTarget + 7 ] = v3.y;
  12137. vka[ offset_morphTarget + 8 ] = v3.z;
  12138. // morph normals
  12139. if ( material.morphNormals ) {
  12140. if ( needsSmoothNormals ) {
  12141. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12142. n1 = faceVertexNormals.a;
  12143. n2 = faceVertexNormals.b;
  12144. n3 = faceVertexNormals.c;
  12145. } else {
  12146. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12147. n2 = n1;
  12148. n3 = n1;
  12149. }
  12150. nka = morphNormalsArrays[ vk ];
  12151. nka[ offset_morphTarget ] = n1.x;
  12152. nka[ offset_morphTarget + 1 ] = n1.y;
  12153. nka[ offset_morphTarget + 2 ] = n1.z;
  12154. nka[ offset_morphTarget + 3 ] = n2.x;
  12155. nka[ offset_morphTarget + 4 ] = n2.y;
  12156. nka[ offset_morphTarget + 5 ] = n2.z;
  12157. nka[ offset_morphTarget + 6 ] = n3.x;
  12158. nka[ offset_morphTarget + 7 ] = n3.y;
  12159. nka[ offset_morphTarget + 8 ] = n3.z;
  12160. }
  12161. //
  12162. offset_morphTarget += 9;
  12163. }
  12164. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12165. chf = chunk_faces4[ f ];
  12166. face = obj_faces[ chf ];
  12167. // morph positions
  12168. v1 = morphTargets[ vk ].vertices[ face.a ];
  12169. v2 = morphTargets[ vk ].vertices[ face.b ];
  12170. v3 = morphTargets[ vk ].vertices[ face.c ];
  12171. v4 = morphTargets[ vk ].vertices[ face.d ];
  12172. vka = morphTargetsArrays[ vk ];
  12173. vka[ offset_morphTarget ] = v1.x;
  12174. vka[ offset_morphTarget + 1 ] = v1.y;
  12175. vka[ offset_morphTarget + 2 ] = v1.z;
  12176. vka[ offset_morphTarget + 3 ] = v2.x;
  12177. vka[ offset_morphTarget + 4 ] = v2.y;
  12178. vka[ offset_morphTarget + 5 ] = v2.z;
  12179. vka[ offset_morphTarget + 6 ] = v3.x;
  12180. vka[ offset_morphTarget + 7 ] = v3.y;
  12181. vka[ offset_morphTarget + 8 ] = v3.z;
  12182. vka[ offset_morphTarget + 9 ] = v4.x;
  12183. vka[ offset_morphTarget + 10 ] = v4.y;
  12184. vka[ offset_morphTarget + 11 ] = v4.z;
  12185. // morph normals
  12186. if ( material.morphNormals ) {
  12187. if ( needsSmoothNormals ) {
  12188. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12189. n1 = faceVertexNormals.a;
  12190. n2 = faceVertexNormals.b;
  12191. n3 = faceVertexNormals.c;
  12192. n4 = faceVertexNormals.d;
  12193. } else {
  12194. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12195. n2 = n1;
  12196. n3 = n1;
  12197. n4 = n1;
  12198. }
  12199. nka = morphNormalsArrays[ vk ];
  12200. nka[ offset_morphTarget ] = n1.x;
  12201. nka[ offset_morphTarget + 1 ] = n1.y;
  12202. nka[ offset_morphTarget + 2 ] = n1.z;
  12203. nka[ offset_morphTarget + 3 ] = n2.x;
  12204. nka[ offset_morphTarget + 4 ] = n2.y;
  12205. nka[ offset_morphTarget + 5 ] = n2.z;
  12206. nka[ offset_morphTarget + 6 ] = n3.x;
  12207. nka[ offset_morphTarget + 7 ] = n3.y;
  12208. nka[ offset_morphTarget + 8 ] = n3.z;
  12209. nka[ offset_morphTarget + 9 ] = n4.x;
  12210. nka[ offset_morphTarget + 10 ] = n4.y;
  12211. nka[ offset_morphTarget + 11 ] = n4.z;
  12212. }
  12213. //
  12214. offset_morphTarget += 12;
  12215. }
  12216. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12217. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12218. if ( material.morphNormals ) {
  12219. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12220. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12221. }
  12222. }
  12223. }
  12224. if ( obj_skinWeights.length ) {
  12225. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12226. face = obj_faces[ chunk_faces3[ f ] ];
  12227. // weights
  12228. sw1 = obj_skinWeights[ face.a ];
  12229. sw2 = obj_skinWeights[ face.b ];
  12230. sw3 = obj_skinWeights[ face.c ];
  12231. skinWeightArray[ offset_skin ] = sw1.x;
  12232. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12233. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12234. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12235. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12236. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12237. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12238. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12239. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12240. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12241. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12242. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12243. // indices
  12244. si1 = obj_skinIndices[ face.a ];
  12245. si2 = obj_skinIndices[ face.b ];
  12246. si3 = obj_skinIndices[ face.c ];
  12247. skinIndexArray[ offset_skin ] = si1.x;
  12248. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12249. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12250. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12251. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12252. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12253. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12254. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12255. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12256. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12257. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12258. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12259. offset_skin += 12;
  12260. }
  12261. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12262. face = obj_faces[ chunk_faces4[ f ] ];
  12263. // weights
  12264. sw1 = obj_skinWeights[ face.a ];
  12265. sw2 = obj_skinWeights[ face.b ];
  12266. sw3 = obj_skinWeights[ face.c ];
  12267. sw4 = obj_skinWeights[ face.d ];
  12268. skinWeightArray[ offset_skin ] = sw1.x;
  12269. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12270. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12271. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12272. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12273. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12274. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12275. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12276. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12277. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12278. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12279. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12280. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  12281. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  12282. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  12283. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  12284. // indices
  12285. si1 = obj_skinIndices[ face.a ];
  12286. si2 = obj_skinIndices[ face.b ];
  12287. si3 = obj_skinIndices[ face.c ];
  12288. si4 = obj_skinIndices[ face.d ];
  12289. skinIndexArray[ offset_skin ] = si1.x;
  12290. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12291. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12292. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12293. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12294. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12295. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12296. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12297. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12298. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12299. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12300. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12301. skinIndexArray[ offset_skin + 12 ] = si4.x;
  12302. skinIndexArray[ offset_skin + 13 ] = si4.y;
  12303. skinIndexArray[ offset_skin + 14 ] = si4.z;
  12304. skinIndexArray[ offset_skin + 15 ] = si4.w;
  12305. offset_skin += 16;
  12306. }
  12307. if ( offset_skin > 0 ) {
  12308. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12309. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12310. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12311. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12312. }
  12313. }
  12314. if ( dirtyColors && vertexColorType ) {
  12315. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12316. face = obj_faces[ chunk_faces3[ f ] ];
  12317. vertexColors = face.vertexColors;
  12318. faceColor = face.color;
  12319. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12320. c1 = vertexColors[ 0 ];
  12321. c2 = vertexColors[ 1 ];
  12322. c3 = vertexColors[ 2 ];
  12323. } else {
  12324. c1 = faceColor;
  12325. c2 = faceColor;
  12326. c3 = faceColor;
  12327. }
  12328. colorArray[ offset_color ] = c1.r;
  12329. colorArray[ offset_color + 1 ] = c1.g;
  12330. colorArray[ offset_color + 2 ] = c1.b;
  12331. colorArray[ offset_color + 3 ] = c2.r;
  12332. colorArray[ offset_color + 4 ] = c2.g;
  12333. colorArray[ offset_color + 5 ] = c2.b;
  12334. colorArray[ offset_color + 6 ] = c3.r;
  12335. colorArray[ offset_color + 7 ] = c3.g;
  12336. colorArray[ offset_color + 8 ] = c3.b;
  12337. offset_color += 9;
  12338. }
  12339. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12340. face = obj_faces[ chunk_faces4[ f ] ];
  12341. vertexColors = face.vertexColors;
  12342. faceColor = face.color;
  12343. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  12344. c1 = vertexColors[ 0 ];
  12345. c2 = vertexColors[ 1 ];
  12346. c3 = vertexColors[ 2 ];
  12347. c4 = vertexColors[ 3 ];
  12348. } else {
  12349. c1 = faceColor;
  12350. c2 = faceColor;
  12351. c3 = faceColor;
  12352. c4 = faceColor;
  12353. }
  12354. colorArray[ offset_color ] = c1.r;
  12355. colorArray[ offset_color + 1 ] = c1.g;
  12356. colorArray[ offset_color + 2 ] = c1.b;
  12357. colorArray[ offset_color + 3 ] = c2.r;
  12358. colorArray[ offset_color + 4 ] = c2.g;
  12359. colorArray[ offset_color + 5 ] = c2.b;
  12360. colorArray[ offset_color + 6 ] = c3.r;
  12361. colorArray[ offset_color + 7 ] = c3.g;
  12362. colorArray[ offset_color + 8 ] = c3.b;
  12363. colorArray[ offset_color + 9 ] = c4.r;
  12364. colorArray[ offset_color + 10 ] = c4.g;
  12365. colorArray[ offset_color + 11 ] = c4.b;
  12366. offset_color += 12;
  12367. }
  12368. if ( offset_color > 0 ) {
  12369. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12370. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12371. }
  12372. }
  12373. if ( dirtyTangents && geometry.hasTangents ) {
  12374. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12375. face = obj_faces[ chunk_faces3[ f ] ];
  12376. vertexTangents = face.vertexTangents;
  12377. t1 = vertexTangents[ 0 ];
  12378. t2 = vertexTangents[ 1 ];
  12379. t3 = vertexTangents[ 2 ];
  12380. tangentArray[ offset_tangent ] = t1.x;
  12381. tangentArray[ offset_tangent + 1 ] = t1.y;
  12382. tangentArray[ offset_tangent + 2 ] = t1.z;
  12383. tangentArray[ offset_tangent + 3 ] = t1.w;
  12384. tangentArray[ offset_tangent + 4 ] = t2.x;
  12385. tangentArray[ offset_tangent + 5 ] = t2.y;
  12386. tangentArray[ offset_tangent + 6 ] = t2.z;
  12387. tangentArray[ offset_tangent + 7 ] = t2.w;
  12388. tangentArray[ offset_tangent + 8 ] = t3.x;
  12389. tangentArray[ offset_tangent + 9 ] = t3.y;
  12390. tangentArray[ offset_tangent + 10 ] = t3.z;
  12391. tangentArray[ offset_tangent + 11 ] = t3.w;
  12392. offset_tangent += 12;
  12393. }
  12394. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12395. face = obj_faces[ chunk_faces4[ f ] ];
  12396. vertexTangents = face.vertexTangents;
  12397. t1 = vertexTangents[ 0 ];
  12398. t2 = vertexTangents[ 1 ];
  12399. t3 = vertexTangents[ 2 ];
  12400. t4 = vertexTangents[ 3 ];
  12401. tangentArray[ offset_tangent ] = t1.x;
  12402. tangentArray[ offset_tangent + 1 ] = t1.y;
  12403. tangentArray[ offset_tangent + 2 ] = t1.z;
  12404. tangentArray[ offset_tangent + 3 ] = t1.w;
  12405. tangentArray[ offset_tangent + 4 ] = t2.x;
  12406. tangentArray[ offset_tangent + 5 ] = t2.y;
  12407. tangentArray[ offset_tangent + 6 ] = t2.z;
  12408. tangentArray[ offset_tangent + 7 ] = t2.w;
  12409. tangentArray[ offset_tangent + 8 ] = t3.x;
  12410. tangentArray[ offset_tangent + 9 ] = t3.y;
  12411. tangentArray[ offset_tangent + 10 ] = t3.z;
  12412. tangentArray[ offset_tangent + 11 ] = t3.w;
  12413. tangentArray[ offset_tangent + 12 ] = t4.x;
  12414. tangentArray[ offset_tangent + 13 ] = t4.y;
  12415. tangentArray[ offset_tangent + 14 ] = t4.z;
  12416. tangentArray[ offset_tangent + 15 ] = t4.w;
  12417. offset_tangent += 16;
  12418. }
  12419. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12420. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12421. }
  12422. if ( dirtyNormals && normalType ) {
  12423. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12424. face = obj_faces[ chunk_faces3[ f ] ];
  12425. vertexNormals = face.vertexNormals;
  12426. faceNormal = face.normal;
  12427. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12428. for ( i = 0; i < 3; i ++ ) {
  12429. vn = vertexNormals[ i ];
  12430. normalArray[ offset_normal ] = vn.x;
  12431. normalArray[ offset_normal + 1 ] = vn.y;
  12432. normalArray[ offset_normal + 2 ] = vn.z;
  12433. offset_normal += 3;
  12434. }
  12435. } else {
  12436. for ( i = 0; i < 3; i ++ ) {
  12437. normalArray[ offset_normal ] = faceNormal.x;
  12438. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12439. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12440. offset_normal += 3;
  12441. }
  12442. }
  12443. }
  12444. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12445. face = obj_faces[ chunk_faces4[ f ] ];
  12446. vertexNormals = face.vertexNormals;
  12447. faceNormal = face.normal;
  12448. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  12449. for ( i = 0; i < 4; i ++ ) {
  12450. vn = vertexNormals[ i ];
  12451. normalArray[ offset_normal ] = vn.x;
  12452. normalArray[ offset_normal + 1 ] = vn.y;
  12453. normalArray[ offset_normal + 2 ] = vn.z;
  12454. offset_normal += 3;
  12455. }
  12456. } else {
  12457. for ( i = 0; i < 4; i ++ ) {
  12458. normalArray[ offset_normal ] = faceNormal.x;
  12459. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12460. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12461. offset_normal += 3;
  12462. }
  12463. }
  12464. }
  12465. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12466. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12467. }
  12468. if ( dirtyUvs && obj_uvs && uvType ) {
  12469. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12470. fi = chunk_faces3[ f ];
  12471. uv = obj_uvs[ fi ];
  12472. if ( uv === undefined ) continue;
  12473. for ( i = 0; i < 3; i ++ ) {
  12474. uvi = uv[ i ];
  12475. uvArray[ offset_uv ] = uvi.x;
  12476. uvArray[ offset_uv + 1 ] = uvi.y;
  12477. offset_uv += 2;
  12478. }
  12479. }
  12480. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12481. fi = chunk_faces4[ f ];
  12482. uv = obj_uvs[ fi ];
  12483. if ( uv === undefined ) continue;
  12484. for ( i = 0; i < 4; i ++ ) {
  12485. uvi = uv[ i ];
  12486. uvArray[ offset_uv ] = uvi.x;
  12487. uvArray[ offset_uv + 1 ] = uvi.y;
  12488. offset_uv += 2;
  12489. }
  12490. }
  12491. if ( offset_uv > 0 ) {
  12492. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12493. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12494. }
  12495. }
  12496. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12497. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12498. fi = chunk_faces3[ f ];
  12499. uv2 = obj_uvs2[ fi ];
  12500. if ( uv2 === undefined ) continue;
  12501. for ( i = 0; i < 3; i ++ ) {
  12502. uv2i = uv2[ i ];
  12503. uv2Array[ offset_uv2 ] = uv2i.x;
  12504. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12505. offset_uv2 += 2;
  12506. }
  12507. }
  12508. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12509. fi = chunk_faces4[ f ];
  12510. uv2 = obj_uvs2[ fi ];
  12511. if ( uv2 === undefined ) continue;
  12512. for ( i = 0; i < 4; i ++ ) {
  12513. uv2i = uv2[ i ];
  12514. uv2Array[ offset_uv2 ] = uv2i.x;
  12515. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12516. offset_uv2 += 2;
  12517. }
  12518. }
  12519. if ( offset_uv2 > 0 ) {
  12520. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12521. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12522. }
  12523. }
  12524. if ( dirtyElements ) {
  12525. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12526. faceArray[ offset_face ] = vertexIndex;
  12527. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12528. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12529. offset_face += 3;
  12530. lineArray[ offset_line ] = vertexIndex;
  12531. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12532. lineArray[ offset_line + 2 ] = vertexIndex;
  12533. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12534. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12535. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12536. offset_line += 6;
  12537. vertexIndex += 3;
  12538. }
  12539. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12540. faceArray[ offset_face ] = vertexIndex;
  12541. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12542. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12543. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12544. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12545. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12546. offset_face += 6;
  12547. lineArray[ offset_line ] = vertexIndex;
  12548. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12549. lineArray[ offset_line + 2 ] = vertexIndex;
  12550. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12551. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12552. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12553. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12554. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12555. offset_line += 8;
  12556. vertexIndex += 4;
  12557. }
  12558. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12559. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12560. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12561. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12562. }
  12563. if ( customAttributes ) {
  12564. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12565. customAttribute = customAttributes[ i ];
  12566. if ( ! customAttribute.__original.needsUpdate ) continue;
  12567. offset_custom = 0;
  12568. offset_customSrc = 0;
  12569. if ( customAttribute.size === 1 ) {
  12570. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12571. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12572. face = obj_faces[ chunk_faces3[ f ] ];
  12573. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12574. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12575. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12576. offset_custom += 3;
  12577. }
  12578. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12579. face = obj_faces[ chunk_faces4[ f ] ];
  12580. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12581. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12582. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12583. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  12584. offset_custom += 4;
  12585. }
  12586. } else if ( customAttribute.boundTo === "faces" ) {
  12587. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12588. value = customAttribute.value[ chunk_faces3[ f ] ];
  12589. customAttribute.array[ offset_custom ] = value;
  12590. customAttribute.array[ offset_custom + 1 ] = value;
  12591. customAttribute.array[ offset_custom + 2 ] = value;
  12592. offset_custom += 3;
  12593. }
  12594. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12595. value = customAttribute.value[ chunk_faces4[ f ] ];
  12596. customAttribute.array[ offset_custom ] = value;
  12597. customAttribute.array[ offset_custom + 1 ] = value;
  12598. customAttribute.array[ offset_custom + 2 ] = value;
  12599. customAttribute.array[ offset_custom + 3 ] = value;
  12600. offset_custom += 4;
  12601. }
  12602. }
  12603. } else if ( customAttribute.size === 2 ) {
  12604. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12605. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12606. face = obj_faces[ chunk_faces3[ f ] ];
  12607. v1 = customAttribute.value[ face.a ];
  12608. v2 = customAttribute.value[ face.b ];
  12609. v3 = customAttribute.value[ face.c ];
  12610. customAttribute.array[ offset_custom ] = v1.x;
  12611. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12612. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12613. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12614. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12615. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12616. offset_custom += 6;
  12617. }
  12618. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12619. face = obj_faces[ chunk_faces4[ f ] ];
  12620. v1 = customAttribute.value[ face.a ];
  12621. v2 = customAttribute.value[ face.b ];
  12622. v3 = customAttribute.value[ face.c ];
  12623. v4 = customAttribute.value[ face.d ];
  12624. customAttribute.array[ offset_custom ] = v1.x;
  12625. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12626. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12627. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12628. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12629. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12630. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12631. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12632. offset_custom += 8;
  12633. }
  12634. } else if ( customAttribute.boundTo === "faces" ) {
  12635. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12636. value = customAttribute.value[ chunk_faces3[ f ] ];
  12637. v1 = value;
  12638. v2 = value;
  12639. v3 = value;
  12640. customAttribute.array[ offset_custom ] = v1.x;
  12641. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12642. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12643. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12644. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12645. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12646. offset_custom += 6;
  12647. }
  12648. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12649. value = customAttribute.value[ chunk_faces4[ f ] ];
  12650. v1 = value;
  12651. v2 = value;
  12652. v3 = value;
  12653. v4 = value;
  12654. customAttribute.array[ offset_custom ] = v1.x;
  12655. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12656. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12657. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12658. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12659. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12660. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12661. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12662. offset_custom += 8;
  12663. }
  12664. }
  12665. } else if ( customAttribute.size === 3 ) {
  12666. var pp;
  12667. if ( customAttribute.type === "c" ) {
  12668. pp = [ "r", "g", "b" ];
  12669. } else {
  12670. pp = [ "x", "y", "z" ];
  12671. }
  12672. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12673. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12674. face = obj_faces[ chunk_faces3[ f ] ];
  12675. v1 = customAttribute.value[ face.a ];
  12676. v2 = customAttribute.value[ face.b ];
  12677. v3 = customAttribute.value[ face.c ];
  12678. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12679. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12680. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12681. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12682. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12683. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12684. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12685. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12686. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12687. offset_custom += 9;
  12688. }
  12689. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12690. face = obj_faces[ chunk_faces4[ f ] ];
  12691. v1 = customAttribute.value[ face.a ];
  12692. v2 = customAttribute.value[ face.b ];
  12693. v3 = customAttribute.value[ face.c ];
  12694. v4 = customAttribute.value[ face.d ];
  12695. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12696. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12697. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12698. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12699. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12700. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12701. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12702. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12703. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12704. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12705. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12706. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12707. offset_custom += 12;
  12708. }
  12709. } else if ( customAttribute.boundTo === "faces" ) {
  12710. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12711. value = customAttribute.value[ chunk_faces3[ f ] ];
  12712. v1 = value;
  12713. v2 = value;
  12714. v3 = value;
  12715. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12716. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12717. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12718. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12719. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12720. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12721. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12722. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12723. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12724. offset_custom += 9;
  12725. }
  12726. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12727. value = customAttribute.value[ chunk_faces4[ f ] ];
  12728. v1 = value;
  12729. v2 = value;
  12730. v3 = value;
  12731. v4 = value;
  12732. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12733. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12734. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12735. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12736. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12737. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12738. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12739. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12740. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12741. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12742. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12743. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12744. offset_custom += 12;
  12745. }
  12746. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12747. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12748. value = customAttribute.value[ chunk_faces3[ f ] ];
  12749. v1 = value[ 0 ];
  12750. v2 = value[ 1 ];
  12751. v3 = value[ 2 ];
  12752. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12753. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12754. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12755. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12756. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12757. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12758. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12759. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12760. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12761. offset_custom += 9;
  12762. }
  12763. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12764. value = customAttribute.value[ chunk_faces4[ f ] ];
  12765. v1 = value[ 0 ];
  12766. v2 = value[ 1 ];
  12767. v3 = value[ 2 ];
  12768. v4 = value[ 3 ];
  12769. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12770. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12771. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12772. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12773. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12774. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12775. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12776. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12777. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12778. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12779. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12780. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12781. offset_custom += 12;
  12782. }
  12783. }
  12784. } else if ( customAttribute.size === 4 ) {
  12785. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12786. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12787. face = obj_faces[ chunk_faces3[ f ] ];
  12788. v1 = customAttribute.value[ face.a ];
  12789. v2 = customAttribute.value[ face.b ];
  12790. v3 = customAttribute.value[ face.c ];
  12791. customAttribute.array[ offset_custom ] = v1.x;
  12792. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12793. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12794. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12795. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12796. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12797. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12798. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12799. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12800. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12801. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12802. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12803. offset_custom += 12;
  12804. }
  12805. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12806. face = obj_faces[ chunk_faces4[ f ] ];
  12807. v1 = customAttribute.value[ face.a ];
  12808. v2 = customAttribute.value[ face.b ];
  12809. v3 = customAttribute.value[ face.c ];
  12810. v4 = customAttribute.value[ face.d ];
  12811. customAttribute.array[ offset_custom ] = v1.x;
  12812. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12813. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12814. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12815. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12816. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12817. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12818. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12819. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12820. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12821. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12822. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12823. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12824. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12825. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12826. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12827. offset_custom += 16;
  12828. }
  12829. } else if ( customAttribute.boundTo === "faces" ) {
  12830. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12831. value = customAttribute.value[ chunk_faces3[ f ] ];
  12832. v1 = value;
  12833. v2 = value;
  12834. v3 = value;
  12835. customAttribute.array[ offset_custom ] = v1.x;
  12836. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12837. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12838. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12839. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12840. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12841. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12842. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12843. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12844. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12845. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12846. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12847. offset_custom += 12;
  12848. }
  12849. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12850. value = customAttribute.value[ chunk_faces4[ f ] ];
  12851. v1 = value;
  12852. v2 = value;
  12853. v3 = value;
  12854. v4 = value;
  12855. customAttribute.array[ offset_custom ] = v1.x;
  12856. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12857. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12858. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12859. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12860. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12861. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12862. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12863. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12864. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12865. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12866. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12867. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12868. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12869. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12870. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12871. offset_custom += 16;
  12872. }
  12873. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12874. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12875. value = customAttribute.value[ chunk_faces3[ f ] ];
  12876. v1 = value[ 0 ];
  12877. v2 = value[ 1 ];
  12878. v3 = value[ 2 ];
  12879. customAttribute.array[ offset_custom ] = v1.x;
  12880. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12881. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12882. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12883. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12884. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12885. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12886. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12887. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12888. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12889. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12890. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12891. offset_custom += 12;
  12892. }
  12893. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12894. value = customAttribute.value[ chunk_faces4[ f ] ];
  12895. v1 = value[ 0 ];
  12896. v2 = value[ 1 ];
  12897. v3 = value[ 2 ];
  12898. v4 = value[ 3 ];
  12899. customAttribute.array[ offset_custom ] = v1.x;
  12900. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12901. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12902. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12903. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12904. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12905. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12906. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12907. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12908. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12909. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12910. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12911. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12912. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12913. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12914. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12915. offset_custom += 16;
  12916. }
  12917. }
  12918. }
  12919. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12920. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12921. }
  12922. }
  12923. if ( dispose ) {
  12924. delete geometryGroup.__inittedArrays;
  12925. delete geometryGroup.__colorArray;
  12926. delete geometryGroup.__normalArray;
  12927. delete geometryGroup.__tangentArray;
  12928. delete geometryGroup.__uvArray;
  12929. delete geometryGroup.__uv2Array;
  12930. delete geometryGroup.__faceArray;
  12931. delete geometryGroup.__vertexArray;
  12932. delete geometryGroup.__lineArray;
  12933. delete geometryGroup.__skinIndexArray;
  12934. delete geometryGroup.__skinWeightArray;
  12935. }
  12936. };
  12937. function setDirectBuffers ( geometry, hint, dispose ) {
  12938. var attributes = geometry.attributes;
  12939. var attributeName, attributeItem;
  12940. for ( attributeName in attributes ) {
  12941. attributeItem = attributes[ attributeName ];
  12942. if ( attributeItem.needsUpdate ) {
  12943. if ( attributeName === 'index' ) {
  12944. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  12945. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  12946. } else {
  12947. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  12948. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  12949. }
  12950. attributeItem.needsUpdate = false;
  12951. }
  12952. if ( dispose && ! attributeItem.dynamic ) {
  12953. delete attributeItem.array;
  12954. }
  12955. }
  12956. };
  12957. // Buffer rendering
  12958. this.renderBufferImmediate = function ( object, program, material ) {
  12959. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12960. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12961. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12962. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12963. if ( object.hasPositions ) {
  12964. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12965. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12966. _gl.enableVertexAttribArray( program.attributes.position );
  12967. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12968. }
  12969. if ( object.hasNormals ) {
  12970. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12971. if ( material.shading === THREE.FlatShading ) {
  12972. var nx, ny, nz,
  12973. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12974. normalArray,
  12975. i, il = object.count * 3;
  12976. for( i = 0; i < il; i += 9 ) {
  12977. normalArray = object.normalArray;
  12978. nax = normalArray[ i ];
  12979. nay = normalArray[ i + 1 ];
  12980. naz = normalArray[ i + 2 ];
  12981. nbx = normalArray[ i + 3 ];
  12982. nby = normalArray[ i + 4 ];
  12983. nbz = normalArray[ i + 5 ];
  12984. ncx = normalArray[ i + 6 ];
  12985. ncy = normalArray[ i + 7 ];
  12986. ncz = normalArray[ i + 8 ];
  12987. nx = ( nax + nbx + ncx ) / 3;
  12988. ny = ( nay + nby + ncy ) / 3;
  12989. nz = ( naz + nbz + ncz ) / 3;
  12990. normalArray[ i ] = nx;
  12991. normalArray[ i + 1 ] = ny;
  12992. normalArray[ i + 2 ] = nz;
  12993. normalArray[ i + 3 ] = nx;
  12994. normalArray[ i + 4 ] = ny;
  12995. normalArray[ i + 5 ] = nz;
  12996. normalArray[ i + 6 ] = nx;
  12997. normalArray[ i + 7 ] = ny;
  12998. normalArray[ i + 8 ] = nz;
  12999. }
  13000. }
  13001. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13002. _gl.enableVertexAttribArray( program.attributes.normal );
  13003. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13004. }
  13005. if ( object.hasUvs && material.map ) {
  13006. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13007. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13008. _gl.enableVertexAttribArray( program.attributes.uv );
  13009. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13010. }
  13011. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13012. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13013. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13014. _gl.enableVertexAttribArray( program.attributes.color );
  13015. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13016. }
  13017. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13018. object.count = 0;
  13019. };
  13020. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13021. if ( material.visible === false ) return;
  13022. var program, programAttributes, linewidth, primitives, a, attribute, geometryAttributes;
  13023. var attributeItem, attributeName, attributePointer, attributeSize;
  13024. program = setProgram( camera, lights, fog, material, object );
  13025. programAttributes = program.attributes;
  13026. geometryAttributes = geometry.attributes;
  13027. var updateBuffers = false,
  13028. wireframeBit = material.wireframe ? 1 : 0,
  13029. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13030. if ( geometryHash !== _currentGeometryGroupHash ) {
  13031. _currentGeometryGroupHash = geometryHash;
  13032. updateBuffers = true;
  13033. }
  13034. if ( updateBuffers ) {
  13035. disableAttributes();
  13036. }
  13037. // render mesh
  13038. if ( object instanceof THREE.Mesh ) {
  13039. var index = geometryAttributes[ "index" ];
  13040. // indexed triangles
  13041. if ( index ) {
  13042. var offsets = geometry.offsets;
  13043. // if there is more than 1 chunk
  13044. // must set attribute pointers to use new offsets for each chunk
  13045. // even if geometry and materials didn't change
  13046. if ( offsets.length > 1 ) updateBuffers = true;
  13047. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13048. var startIndex = offsets[ i ].index;
  13049. if ( updateBuffers ) {
  13050. for ( attributeName in geometryAttributes ) {
  13051. if ( attributeName === 'index' ) continue;
  13052. attributePointer = programAttributes[ attributeName ];
  13053. attributeItem = geometryAttributes[ attributeName ];
  13054. attributeSize = attributeItem.itemSize;
  13055. if ( attributePointer >= 0 ) {
  13056. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13057. enableAttribute( attributePointer );
  13058. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13059. }
  13060. }
  13061. // indices
  13062. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13063. }
  13064. // render indexed triangles
  13065. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13066. _this.info.render.calls ++;
  13067. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13068. _this.info.render.faces += offsets[ i ].count / 3;
  13069. }
  13070. // non-indexed triangles
  13071. } else {
  13072. if ( updateBuffers ) {
  13073. for ( attributeName in geometryAttributes ) {
  13074. if ( attributeName === 'index') continue;
  13075. attributePointer = programAttributes[ attributeName ];
  13076. attributeItem = geometryAttributes[ attributeName ];
  13077. attributeSize = attributeItem.itemSize;
  13078. if ( attributePointer >= 0 ) {
  13079. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13080. enableAttribute( attributePointer );
  13081. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13082. }
  13083. }
  13084. }
  13085. var position = geometry.attributes[ "position" ];
  13086. // render non-indexed triangles
  13087. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13088. _this.info.render.calls ++;
  13089. _this.info.render.vertices += position.numItems / 3;
  13090. _this.info.render.faces += position.numItems / 3 / 3;
  13091. }
  13092. // render particles
  13093. } else if ( object instanceof THREE.ParticleSystem ) {
  13094. if ( updateBuffers ) {
  13095. for ( attributeName in geometryAttributes ) {
  13096. attributePointer = programAttributes[ attributeName ];
  13097. attributeItem = geometryAttributes[ attributeName ];
  13098. attributeSize = attributeItem.itemSize;
  13099. if ( attributePointer >= 0 ) {
  13100. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13101. enableAttribute( attributePointer );
  13102. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13103. }
  13104. }
  13105. var position = geometryAttributes[ "position" ];
  13106. // render particles
  13107. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13108. _this.info.render.calls ++;
  13109. _this.info.render.points += position.numItems / 3;
  13110. }
  13111. } else if ( object instanceof THREE.Line ) {
  13112. if ( updateBuffers ) {
  13113. for ( attributeName in geometryAttributes ) {
  13114. attributePointer = programAttributes[ attributeName ];
  13115. attributeItem = geometryAttributes[ attributeName ];
  13116. attributeSize = attributeItem.itemSize;
  13117. if ( attributePointer >= 0 ) {
  13118. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13119. enableAttribute( attributePointer );
  13120. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13121. }
  13122. }
  13123. // render lines
  13124. setLineWidth( material.linewidth );
  13125. var position = geometryAttributes[ "position" ];
  13126. _gl.drawArrays( _gl.LINE_STRIP, 0, position.numItems / 3 );
  13127. _this.info.render.calls ++;
  13128. _this.info.render.points += position.numItems;
  13129. }
  13130. }
  13131. };
  13132. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13133. if ( material.visible === false ) return;
  13134. var program, attributes, linewidth, primitives, a, attribute, i, il;
  13135. program = setProgram( camera, lights, fog, material, object );
  13136. attributes = program.attributes;
  13137. var updateBuffers = false,
  13138. wireframeBit = material.wireframe ? 1 : 0,
  13139. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13140. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13141. _currentGeometryGroupHash = geometryGroupHash;
  13142. updateBuffers = true;
  13143. }
  13144. if ( updateBuffers ) {
  13145. disableAttributes();
  13146. }
  13147. // vertices
  13148. if ( !material.morphTargets && attributes.position >= 0 ) {
  13149. if ( updateBuffers ) {
  13150. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13151. enableAttribute( attributes.position );
  13152. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13153. }
  13154. } else {
  13155. if ( object.morphTargetBase ) {
  13156. setupMorphTargets( material, geometryGroup, object );
  13157. }
  13158. }
  13159. if ( updateBuffers ) {
  13160. // custom attributes
  13161. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13162. if ( geometryGroup.__webglCustomAttributesList ) {
  13163. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13164. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13165. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13166. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13167. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13168. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13169. }
  13170. }
  13171. }
  13172. // colors
  13173. if ( attributes.color >= 0 ) {
  13174. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13175. enableAttribute( attributes.color );
  13176. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13177. }
  13178. // normals
  13179. if ( attributes.normal >= 0 ) {
  13180. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13181. enableAttribute( attributes.normal );
  13182. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13183. }
  13184. // tangents
  13185. if ( attributes.tangent >= 0 ) {
  13186. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13187. enableAttribute( attributes.tangent );
  13188. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13189. }
  13190. // uvs
  13191. if ( attributes.uv >= 0 ) {
  13192. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13193. enableAttribute( attributes.uv );
  13194. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13195. }
  13196. if ( attributes.uv2 >= 0 ) {
  13197. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13198. enableAttribute( attributes.uv2 );
  13199. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13200. }
  13201. if ( material.skinning &&
  13202. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13203. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13204. enableAttribute( attributes.skinIndex );
  13205. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13206. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13207. enableAttribute( attributes.skinWeight );
  13208. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13209. }
  13210. // line distances
  13211. if ( attributes.lineDistance >= 0 ) {
  13212. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13213. enableAttribute( attributes.lineDistance );
  13214. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13215. }
  13216. }
  13217. // render mesh
  13218. if ( object instanceof THREE.Mesh ) {
  13219. // wireframe
  13220. if ( material.wireframe ) {
  13221. setLineWidth( material.wireframeLinewidth );
  13222. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13223. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13224. // triangles
  13225. } else {
  13226. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13227. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13228. }
  13229. _this.info.render.calls ++;
  13230. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13231. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13232. // render lines
  13233. } else if ( object instanceof THREE.Line ) {
  13234. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13235. setLineWidth( material.linewidth );
  13236. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13237. _this.info.render.calls ++;
  13238. // render particles
  13239. } else if ( object instanceof THREE.ParticleSystem ) {
  13240. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13241. _this.info.render.calls ++;
  13242. _this.info.render.points += geometryGroup.__webglParticleCount;
  13243. // render ribbon
  13244. } else if ( object instanceof THREE.Ribbon ) {
  13245. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  13246. _this.info.render.calls ++;
  13247. }
  13248. };
  13249. function enableAttribute( attribute ) {
  13250. if ( ! _enabledAttributes[ attribute ] ) {
  13251. _gl.enableVertexAttribArray( attribute );
  13252. _enabledAttributes[ attribute ] = true;
  13253. }
  13254. };
  13255. function disableAttributes() {
  13256. for ( var attribute in _enabledAttributes ) {
  13257. if ( _enabledAttributes[ attribute ] ) {
  13258. _gl.disableVertexAttribArray( attribute );
  13259. _enabledAttributes[ attribute ] = false;
  13260. }
  13261. }
  13262. };
  13263. function setupMorphTargets ( material, geometryGroup, object ) {
  13264. // set base
  13265. var attributes = material.program.attributes;
  13266. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13267. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13268. enableAttribute( attributes.position );
  13269. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13270. } else if ( attributes.position >= 0 ) {
  13271. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13272. enableAttribute( attributes.position );
  13273. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13274. }
  13275. if ( object.morphTargetForcedOrder.length ) {
  13276. // set forced order
  13277. var m = 0;
  13278. var order = object.morphTargetForcedOrder;
  13279. var influences = object.morphTargetInfluences;
  13280. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13281. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13282. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13283. enableAttribute( attributes[ "morphTarget" + m ] );
  13284. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13285. }
  13286. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13287. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13288. enableAttribute( attributes[ "morphNormal" + m ] );
  13289. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13290. }
  13291. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13292. m ++;
  13293. }
  13294. } else {
  13295. // find the most influencing
  13296. var influence, activeInfluenceIndices = [];
  13297. var influences = object.morphTargetInfluences;
  13298. var i, il = influences.length;
  13299. for ( i = 0; i < il; i ++ ) {
  13300. influence = influences[ i ];
  13301. if ( influence > 0 ) {
  13302. activeInfluenceIndices.push( [ influence, i ] );
  13303. }
  13304. }
  13305. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13306. activeInfluenceIndices.sort( numericalSort );
  13307. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13308. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13309. activeInfluenceIndices.sort( numericalSort );
  13310. } else if ( activeInfluenceIndices.length === 0 ) {
  13311. activeInfluenceIndices.push( [ 0, 0 ] );
  13312. };
  13313. var influenceIndex, m = 0;
  13314. while ( m < material.numSupportedMorphTargets ) {
  13315. if ( activeInfluenceIndices[ m ] ) {
  13316. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13317. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13318. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13319. enableAttribute( attributes[ "morphTarget" + m ] );
  13320. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13321. }
  13322. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13323. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13324. enableAttribute( attributes[ "morphNormal" + m ] );
  13325. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13326. }
  13327. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13328. } else {
  13329. /*
  13330. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13331. if ( material.morphNormals ) {
  13332. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13333. }
  13334. */
  13335. object.__webglMorphTargetInfluences[ m ] = 0;
  13336. }
  13337. m ++;
  13338. }
  13339. }
  13340. // load updated influences uniform
  13341. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13342. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13343. }
  13344. };
  13345. // Sorting
  13346. function painterSortStable ( a, b ) {
  13347. if ( a.z !== b.z ) {
  13348. return b.z - a.z;
  13349. } else {
  13350. return a.id - b.id;
  13351. }
  13352. };
  13353. function numericalSort ( a, b ) {
  13354. return b[ 0 ] - a[ 0 ];
  13355. };
  13356. // Rendering
  13357. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13358. if ( camera instanceof THREE.Camera === false ) {
  13359. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13360. return;
  13361. }
  13362. var i, il,
  13363. webglObject, object,
  13364. renderList,
  13365. lights = scene.__lights,
  13366. fog = scene.fog;
  13367. // reset caching for this frame
  13368. _currentMaterialId = -1;
  13369. _lightsNeedUpdate = true;
  13370. // update scene graph
  13371. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13372. // update camera matrices and frustum
  13373. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13374. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13375. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13376. _frustum.setFromMatrix( _projScreenMatrix );
  13377. // update WebGL objects
  13378. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13379. // custom render plugins (pre pass)
  13380. renderPlugins( this.renderPluginsPre, scene, camera );
  13381. //
  13382. _this.info.render.calls = 0;
  13383. _this.info.render.vertices = 0;
  13384. _this.info.render.faces = 0;
  13385. _this.info.render.points = 0;
  13386. this.setRenderTarget( renderTarget );
  13387. if ( this.autoClear || forceClear ) {
  13388. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13389. }
  13390. // set matrices for regular objects (frustum culled)
  13391. renderList = scene.__webglObjects;
  13392. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13393. webglObject = renderList[ i ];
  13394. object = webglObject.object;
  13395. webglObject.id = i;
  13396. webglObject.render = false;
  13397. if ( object.visible ) {
  13398. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13399. setupMatrices( object, camera );
  13400. unrollBufferMaterial( webglObject );
  13401. webglObject.render = true;
  13402. if ( this.sortObjects === true ) {
  13403. if ( object.renderDepth !== null ) {
  13404. webglObject.z = object.renderDepth;
  13405. } else {
  13406. _vector3.getPositionFromMatrix( object.matrixWorld );
  13407. _vector3.applyProjection( _projScreenMatrix );
  13408. webglObject.z = _vector3.z;
  13409. }
  13410. }
  13411. }
  13412. }
  13413. }
  13414. if ( this.sortObjects ) {
  13415. renderList.sort( painterSortStable );
  13416. }
  13417. // set matrices for immediate objects
  13418. renderList = scene.__webglObjectsImmediate;
  13419. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13420. webglObject = renderList[ i ];
  13421. object = webglObject.object;
  13422. if ( object.visible ) {
  13423. setupMatrices( object, camera );
  13424. unrollImmediateBufferMaterial( webglObject );
  13425. }
  13426. }
  13427. if ( scene.overrideMaterial ) {
  13428. var material = scene.overrideMaterial;
  13429. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13430. this.setDepthTest( material.depthTest );
  13431. this.setDepthWrite( material.depthWrite );
  13432. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13433. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13434. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13435. } else {
  13436. var material = null;
  13437. // opaque pass (front-to-back order)
  13438. this.setBlending( THREE.NoBlending );
  13439. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13440. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13441. // transparent pass (back-to-front order)
  13442. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13443. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13444. }
  13445. // custom render plugins (post pass)
  13446. renderPlugins( this.renderPluginsPost, scene, camera );
  13447. // Generate mipmap if we're using any kind of mipmap filtering
  13448. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13449. updateRenderTargetMipmap( renderTarget );
  13450. }
  13451. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13452. this.setDepthTest( true );
  13453. this.setDepthWrite( true );
  13454. // _gl.finish();
  13455. };
  13456. function renderPlugins( plugins, scene, camera ) {
  13457. if ( ! plugins.length ) return;
  13458. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13459. // reset state for plugin (to start from clean slate)
  13460. _currentProgram = null;
  13461. _currentCamera = null;
  13462. _oldBlending = -1;
  13463. _oldDepthTest = -1;
  13464. _oldDepthWrite = -1;
  13465. _oldDoubleSided = -1;
  13466. _oldFlipSided = -1;
  13467. _currentGeometryGroupHash = -1;
  13468. _currentMaterialId = -1;
  13469. _lightsNeedUpdate = true;
  13470. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13471. // reset state after plugin (anything could have changed)
  13472. _currentProgram = null;
  13473. _currentCamera = null;
  13474. _oldBlending = -1;
  13475. _oldDepthTest = -1;
  13476. _oldDepthWrite = -1;
  13477. _oldDoubleSided = -1;
  13478. _oldFlipSided = -1;
  13479. _currentGeometryGroupHash = -1;
  13480. _currentMaterialId = -1;
  13481. _lightsNeedUpdate = true;
  13482. }
  13483. };
  13484. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13485. var webglObject, object, buffer, material, start, end, delta;
  13486. if ( reverse ) {
  13487. start = renderList.length - 1;
  13488. end = -1;
  13489. delta = -1;
  13490. } else {
  13491. start = 0;
  13492. end = renderList.length;
  13493. delta = 1;
  13494. }
  13495. for ( var i = start; i !== end; i += delta ) {
  13496. webglObject = renderList[ i ];
  13497. if ( webglObject.render ) {
  13498. object = webglObject.object;
  13499. buffer = webglObject.buffer;
  13500. if ( overrideMaterial ) {
  13501. material = overrideMaterial;
  13502. } else {
  13503. material = webglObject[ materialType ];
  13504. if ( ! material ) continue;
  13505. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13506. _this.setDepthTest( material.depthTest );
  13507. _this.setDepthWrite( material.depthWrite );
  13508. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13509. }
  13510. _this.setMaterialFaces( material );
  13511. if ( buffer instanceof THREE.BufferGeometry ) {
  13512. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13513. } else {
  13514. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13515. }
  13516. }
  13517. }
  13518. };
  13519. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13520. var webglObject, object, material, program;
  13521. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13522. webglObject = renderList[ i ];
  13523. object = webglObject.object;
  13524. if ( object.visible ) {
  13525. if ( overrideMaterial ) {
  13526. material = overrideMaterial;
  13527. } else {
  13528. material = webglObject[ materialType ];
  13529. if ( ! material ) continue;
  13530. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13531. _this.setDepthTest( material.depthTest );
  13532. _this.setDepthWrite( material.depthWrite );
  13533. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13534. }
  13535. _this.renderImmediateObject( camera, lights, fog, material, object );
  13536. }
  13537. }
  13538. };
  13539. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13540. var program = setProgram( camera, lights, fog, material, object );
  13541. _currentGeometryGroupHash = -1;
  13542. _this.setMaterialFaces( material );
  13543. if ( object.immediateRenderCallback ) {
  13544. object.immediateRenderCallback( program, _gl, _frustum );
  13545. } else {
  13546. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13547. }
  13548. };
  13549. function unrollImmediateBufferMaterial ( globject ) {
  13550. var object = globject.object,
  13551. material = object.material;
  13552. if ( material.transparent ) {
  13553. globject.transparent = material;
  13554. globject.opaque = null;
  13555. } else {
  13556. globject.opaque = material;
  13557. globject.transparent = null;
  13558. }
  13559. };
  13560. function unrollBufferMaterial ( globject ) {
  13561. var object = globject.object,
  13562. buffer = globject.buffer,
  13563. material, materialIndex, meshMaterial;
  13564. meshMaterial = object.material;
  13565. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13566. materialIndex = buffer.materialIndex;
  13567. material = meshMaterial.materials[ materialIndex ];
  13568. if ( material.transparent ) {
  13569. globject.transparent = material;
  13570. globject.opaque = null;
  13571. } else {
  13572. globject.opaque = material;
  13573. globject.transparent = null;
  13574. }
  13575. } else {
  13576. material = meshMaterial;
  13577. if ( material ) {
  13578. if ( material.transparent ) {
  13579. globject.transparent = material;
  13580. globject.opaque = null;
  13581. } else {
  13582. globject.opaque = material;
  13583. globject.transparent = null;
  13584. }
  13585. }
  13586. }
  13587. };
  13588. // Geometry splitting
  13589. function sortFacesByMaterial ( geometry, material ) {
  13590. var f, fl, face, materialIndex, vertices,
  13591. groupHash, hash_map = {};
  13592. var numMorphTargets = geometry.morphTargets.length;
  13593. var numMorphNormals = geometry.morphNormals.length;
  13594. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13595. geometry.geometryGroups = {};
  13596. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13597. face = geometry.faces[ f ];
  13598. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13599. if ( hash_map[ materialIndex ] === undefined ) {
  13600. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13601. }
  13602. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13603. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13604. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13605. }
  13606. vertices = face instanceof THREE.Face3 ? 3 : 4;
  13607. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13608. hash_map[ materialIndex ].counter += 1;
  13609. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13610. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13611. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13612. }
  13613. }
  13614. if ( face instanceof THREE.Face3 ) {
  13615. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13616. } else {
  13617. geometry.geometryGroups[ groupHash ].faces4.push( f );
  13618. }
  13619. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13620. }
  13621. geometry.geometryGroupsList = [];
  13622. for ( var g in geometry.geometryGroups ) {
  13623. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13624. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13625. }
  13626. };
  13627. // Objects refresh
  13628. this.initWebGLObjects = function ( scene ) {
  13629. if ( !scene.__webglObjects ) {
  13630. scene.__webglObjects = [];
  13631. scene.__webglObjectsImmediate = [];
  13632. scene.__webglSprites = [];
  13633. scene.__webglFlares = [];
  13634. }
  13635. while ( scene.__objectsAdded.length ) {
  13636. addObject( scene.__objectsAdded[ 0 ], scene );
  13637. scene.__objectsAdded.splice( 0, 1 );
  13638. }
  13639. while ( scene.__objectsRemoved.length ) {
  13640. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13641. scene.__objectsRemoved.splice( 0, 1 );
  13642. }
  13643. // update must be called after objects adding / removal
  13644. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13645. var object = scene.__webglObjects[ o ].object;
  13646. // TODO: Remove this hack (WebGLRenderer refactoring)
  13647. if ( object.__webglInit === undefined ) {
  13648. if ( object.__webglActive !== undefined ) {
  13649. removeObject( object, scene );
  13650. }
  13651. addObject( object, scene );
  13652. }
  13653. updateObject( object );
  13654. }
  13655. };
  13656. // Objects adding
  13657. function addObject( object, scene ) {
  13658. var g, geometry, material, geometryGroup;
  13659. if ( object.__webglInit === undefined ) {
  13660. object.__webglInit = true;
  13661. object._modelViewMatrix = new THREE.Matrix4();
  13662. object._normalMatrix = new THREE.Matrix3();
  13663. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13664. object.geometry.__webglInit = true;
  13665. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13666. }
  13667. geometry = object.geometry;
  13668. if ( geometry === undefined ) {
  13669. // fail silently for now
  13670. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13671. initDirectBuffers( geometry );
  13672. } else if ( object instanceof THREE.Mesh ) {
  13673. material = object.material;
  13674. if ( geometry.geometryGroups === undefined ) {
  13675. sortFacesByMaterial( geometry, material );
  13676. }
  13677. // create separate VBOs per geometry chunk
  13678. for ( g in geometry.geometryGroups ) {
  13679. geometryGroup = geometry.geometryGroups[ g ];
  13680. // initialise VBO on the first access
  13681. if ( ! geometryGroup.__webglVertexBuffer ) {
  13682. createMeshBuffers( geometryGroup );
  13683. initMeshBuffers( geometryGroup, object );
  13684. geometry.verticesNeedUpdate = true;
  13685. geometry.morphTargetsNeedUpdate = true;
  13686. geometry.elementsNeedUpdate = true;
  13687. geometry.uvsNeedUpdate = true;
  13688. geometry.normalsNeedUpdate = true;
  13689. geometry.tangentsNeedUpdate = true;
  13690. geometry.colorsNeedUpdate = true;
  13691. }
  13692. }
  13693. } else if ( object instanceof THREE.Ribbon ) {
  13694. if ( ! geometry.__webglVertexBuffer ) {
  13695. createRibbonBuffers( geometry );
  13696. initRibbonBuffers( geometry, object );
  13697. geometry.verticesNeedUpdate = true;
  13698. geometry.colorsNeedUpdate = true;
  13699. geometry.normalsNeedUpdate = true;
  13700. }
  13701. } else if ( object instanceof THREE.Line ) {
  13702. if ( ! geometry.__webglVertexBuffer ) {
  13703. createLineBuffers( geometry );
  13704. initLineBuffers( geometry, object );
  13705. geometry.verticesNeedUpdate = true;
  13706. geometry.colorsNeedUpdate = true;
  13707. geometry.lineDistancesNeedUpdate = true;
  13708. }
  13709. } else if ( object instanceof THREE.ParticleSystem ) {
  13710. if ( ! geometry.__webglVertexBuffer ) {
  13711. createParticleBuffers( geometry );
  13712. initParticleBuffers( geometry, object );
  13713. geometry.verticesNeedUpdate = true;
  13714. geometry.colorsNeedUpdate = true;
  13715. }
  13716. }
  13717. }
  13718. if ( object.__webglActive === undefined ) {
  13719. if ( object instanceof THREE.Mesh ) {
  13720. geometry = object.geometry;
  13721. if ( geometry instanceof THREE.BufferGeometry ) {
  13722. addBuffer( scene.__webglObjects, geometry, object );
  13723. } else if ( geometry instanceof THREE.Geometry ) {
  13724. for ( g in geometry.geometryGroups ) {
  13725. geometryGroup = geometry.geometryGroups[ g ];
  13726. addBuffer( scene.__webglObjects, geometryGroup, object );
  13727. }
  13728. }
  13729. } else if ( object instanceof THREE.Ribbon ||
  13730. object instanceof THREE.Line ||
  13731. object instanceof THREE.ParticleSystem ) {
  13732. geometry = object.geometry;
  13733. addBuffer( scene.__webglObjects, geometry, object );
  13734. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13735. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13736. } else if ( object instanceof THREE.Sprite ) {
  13737. scene.__webglSprites.push( object );
  13738. } else if ( object instanceof THREE.LensFlare ) {
  13739. scene.__webglFlares.push( object );
  13740. }
  13741. object.__webglActive = true;
  13742. }
  13743. };
  13744. function addBuffer( objlist, buffer, object ) {
  13745. objlist.push(
  13746. {
  13747. buffer: buffer,
  13748. object: object,
  13749. opaque: null,
  13750. transparent: null
  13751. }
  13752. );
  13753. };
  13754. function addBufferImmediate( objlist, object ) {
  13755. objlist.push(
  13756. {
  13757. object: object,
  13758. opaque: null,
  13759. transparent: null
  13760. }
  13761. );
  13762. };
  13763. // Objects updates
  13764. function updateObject( object ) {
  13765. var geometry = object.geometry,
  13766. geometryGroup, customAttributesDirty, material;
  13767. if ( geometry instanceof THREE.BufferGeometry ) {
  13768. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13769. } else if ( object instanceof THREE.Mesh ) {
  13770. // check all geometry groups
  13771. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13772. geometryGroup = geometry.geometryGroupsList[ i ];
  13773. material = getBufferMaterial( object, geometryGroup );
  13774. if ( geometry.buffersNeedUpdate ) {
  13775. initMeshBuffers( geometryGroup, object );
  13776. }
  13777. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13778. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13779. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13780. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13781. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13782. }
  13783. }
  13784. geometry.verticesNeedUpdate = false;
  13785. geometry.morphTargetsNeedUpdate = false;
  13786. geometry.elementsNeedUpdate = false;
  13787. geometry.uvsNeedUpdate = false;
  13788. geometry.normalsNeedUpdate = false;
  13789. geometry.colorsNeedUpdate = false;
  13790. geometry.tangentsNeedUpdate = false;
  13791. geometry.buffersNeedUpdate = false;
  13792. material.attributes && clearCustomAttributes( material );
  13793. } else if ( object instanceof THREE.Ribbon ) {
  13794. material = getBufferMaterial( object, geometry );
  13795. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13796. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  13797. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  13798. }
  13799. geometry.verticesNeedUpdate = false;
  13800. geometry.colorsNeedUpdate = false;
  13801. geometry.normalsNeedUpdate = false;
  13802. material.attributes && clearCustomAttributes( material );
  13803. } else if ( object instanceof THREE.Line ) {
  13804. material = getBufferMaterial( object, geometry );
  13805. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13806. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13807. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13808. }
  13809. geometry.verticesNeedUpdate = false;
  13810. geometry.colorsNeedUpdate = false;
  13811. geometry.lineDistancesNeedUpdate = false;
  13812. material.attributes && clearCustomAttributes( material );
  13813. } else if ( object instanceof THREE.ParticleSystem ) {
  13814. material = getBufferMaterial( object, geometry );
  13815. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13816. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13817. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13818. }
  13819. geometry.verticesNeedUpdate = false;
  13820. geometry.colorsNeedUpdate = false;
  13821. material.attributes && clearCustomAttributes( material );
  13822. }
  13823. };
  13824. // Objects updates - custom attributes check
  13825. function areCustomAttributesDirty( material ) {
  13826. for ( var a in material.attributes ) {
  13827. if ( material.attributes[ a ].needsUpdate ) return true;
  13828. }
  13829. return false;
  13830. };
  13831. function clearCustomAttributes( material ) {
  13832. for ( var a in material.attributes ) {
  13833. material.attributes[ a ].needsUpdate = false;
  13834. }
  13835. };
  13836. // Objects removal
  13837. function removeObject( object, scene ) {
  13838. if ( object instanceof THREE.Mesh ||
  13839. object instanceof THREE.ParticleSystem ||
  13840. object instanceof THREE.Ribbon ||
  13841. object instanceof THREE.Line ) {
  13842. removeInstances( scene.__webglObjects, object );
  13843. } else if ( object instanceof THREE.Sprite ) {
  13844. removeInstancesDirect( scene.__webglSprites, object );
  13845. } else if ( object instanceof THREE.LensFlare ) {
  13846. removeInstancesDirect( scene.__webglFlares, object );
  13847. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13848. removeInstances( scene.__webglObjectsImmediate, object );
  13849. }
  13850. delete object.__webglActive;
  13851. };
  13852. function removeInstances( objlist, object ) {
  13853. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13854. if ( objlist[ o ].object === object ) {
  13855. objlist.splice( o, 1 );
  13856. }
  13857. }
  13858. };
  13859. function removeInstancesDirect( objlist, object ) {
  13860. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13861. if ( objlist[ o ] === object ) {
  13862. objlist.splice( o, 1 );
  13863. }
  13864. }
  13865. };
  13866. // Materials
  13867. this.initMaterial = function ( material, lights, fog, object ) {
  13868. material.addEventListener( 'dispose', onMaterialDispose );
  13869. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13870. if ( material instanceof THREE.MeshDepthMaterial ) {
  13871. shaderID = 'depth';
  13872. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13873. shaderID = 'normal';
  13874. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13875. shaderID = 'basic';
  13876. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13877. shaderID = 'lambert';
  13878. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13879. shaderID = 'phong';
  13880. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13881. shaderID = 'basic';
  13882. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13883. shaderID = 'dashed';
  13884. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13885. shaderID = 'particle_basic';
  13886. }
  13887. if ( shaderID ) {
  13888. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13889. }
  13890. // heuristics to create shader parameters according to lights in the scene
  13891. // (not to blow over maxLights budget)
  13892. maxLightCount = allocateLights( lights );
  13893. maxShadows = allocateShadows( lights );
  13894. maxBones = allocateBones( object );
  13895. parameters = {
  13896. map: !!material.map,
  13897. envMap: !!material.envMap,
  13898. lightMap: !!material.lightMap,
  13899. bumpMap: !!material.bumpMap,
  13900. normalMap: !!material.normalMap,
  13901. specularMap: !!material.specularMap,
  13902. vertexColors: material.vertexColors,
  13903. fog: fog,
  13904. useFog: material.fog,
  13905. fogExp: fog instanceof THREE.FogExp2,
  13906. sizeAttenuation: material.sizeAttenuation,
  13907. skinning: material.skinning,
  13908. maxBones: maxBones,
  13909. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13910. boneTextureWidth: object && object.boneTextureWidth,
  13911. boneTextureHeight: object && object.boneTextureHeight,
  13912. morphTargets: material.morphTargets,
  13913. morphNormals: material.morphNormals,
  13914. maxMorphTargets: this.maxMorphTargets,
  13915. maxMorphNormals: this.maxMorphNormals,
  13916. maxDirLights: maxLightCount.directional,
  13917. maxPointLights: maxLightCount.point,
  13918. maxSpotLights: maxLightCount.spot,
  13919. maxHemiLights: maxLightCount.hemi,
  13920. maxShadows: maxShadows,
  13921. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13922. shadowMapType: this.shadowMapType,
  13923. shadowMapDebug: this.shadowMapDebug,
  13924. shadowMapCascade: this.shadowMapCascade,
  13925. alphaTest: material.alphaTest,
  13926. metal: material.metal,
  13927. perPixel: material.perPixel,
  13928. wrapAround: material.wrapAround,
  13929. doubleSided: material.side === THREE.DoubleSide,
  13930. flipSided: material.side === THREE.BackSide
  13931. };
  13932. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13933. var attributes = material.program.attributes;
  13934. if ( material.morphTargets ) {
  13935. material.numSupportedMorphTargets = 0;
  13936. var id, base = "morphTarget";
  13937. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13938. id = base + i;
  13939. if ( attributes[ id ] >= 0 ) {
  13940. material.numSupportedMorphTargets ++;
  13941. }
  13942. }
  13943. }
  13944. if ( material.morphNormals ) {
  13945. material.numSupportedMorphNormals = 0;
  13946. var id, base = "morphNormal";
  13947. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13948. id = base + i;
  13949. if ( attributes[ id ] >= 0 ) {
  13950. material.numSupportedMorphNormals ++;
  13951. }
  13952. }
  13953. }
  13954. material.uniformsList = [];
  13955. for ( u in material.uniforms ) {
  13956. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13957. }
  13958. };
  13959. function setMaterialShaders( material, shaders ) {
  13960. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13961. material.vertexShader = shaders.vertexShader;
  13962. material.fragmentShader = shaders.fragmentShader;
  13963. };
  13964. function setProgram( camera, lights, fog, material, object ) {
  13965. _usedTextureUnits = 0;
  13966. if ( material.needsUpdate ) {
  13967. if ( material.program ) deallocateMaterial( material );
  13968. _this.initMaterial( material, lights, fog, object );
  13969. material.needsUpdate = false;
  13970. }
  13971. if ( material.morphTargets ) {
  13972. if ( ! object.__webglMorphTargetInfluences ) {
  13973. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13974. }
  13975. }
  13976. var refreshMaterial = false;
  13977. var program = material.program,
  13978. p_uniforms = program.uniforms,
  13979. m_uniforms = material.uniforms;
  13980. if ( program !== _currentProgram ) {
  13981. _gl.useProgram( program );
  13982. _currentProgram = program;
  13983. refreshMaterial = true;
  13984. }
  13985. if ( material.id !== _currentMaterialId ) {
  13986. _currentMaterialId = material.id;
  13987. refreshMaterial = true;
  13988. }
  13989. if ( refreshMaterial || camera !== _currentCamera ) {
  13990. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13991. if ( camera !== _currentCamera ) _currentCamera = camera;
  13992. }
  13993. // skinning uniforms must be set even if material didn't change
  13994. // auto-setting of texture unit for bone texture must go before other textures
  13995. // not sure why, but otherwise weird things happen
  13996. if ( material.skinning ) {
  13997. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13998. if ( p_uniforms.boneTexture !== null ) {
  13999. var textureUnit = getTextureUnit();
  14000. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14001. _this.setTexture( object.boneTexture, textureUnit );
  14002. }
  14003. } else {
  14004. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14005. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14006. }
  14007. }
  14008. }
  14009. if ( refreshMaterial ) {
  14010. // refresh uniforms common to several materials
  14011. if ( fog && material.fog ) {
  14012. refreshUniformsFog( m_uniforms, fog );
  14013. }
  14014. if ( material instanceof THREE.MeshPhongMaterial ||
  14015. material instanceof THREE.MeshLambertMaterial ||
  14016. material.lights ) {
  14017. if ( _lightsNeedUpdate ) {
  14018. setupLights( program, lights );
  14019. _lightsNeedUpdate = false;
  14020. }
  14021. refreshUniformsLights( m_uniforms, _lights );
  14022. }
  14023. if ( material instanceof THREE.MeshBasicMaterial ||
  14024. material instanceof THREE.MeshLambertMaterial ||
  14025. material instanceof THREE.MeshPhongMaterial ) {
  14026. refreshUniformsCommon( m_uniforms, material );
  14027. }
  14028. // refresh single material specific uniforms
  14029. if ( material instanceof THREE.LineBasicMaterial ) {
  14030. refreshUniformsLine( m_uniforms, material );
  14031. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14032. refreshUniformsLine( m_uniforms, material );
  14033. refreshUniformsDash( m_uniforms, material );
  14034. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14035. refreshUniformsParticle( m_uniforms, material );
  14036. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14037. refreshUniformsPhong( m_uniforms, material );
  14038. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14039. refreshUniformsLambert( m_uniforms, material );
  14040. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14041. m_uniforms.mNear.value = camera.near;
  14042. m_uniforms.mFar.value = camera.far;
  14043. m_uniforms.opacity.value = material.opacity;
  14044. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14045. m_uniforms.opacity.value = material.opacity;
  14046. }
  14047. if ( object.receiveShadow && ! material._shadowPass ) {
  14048. refreshUniformsShadow( m_uniforms, lights );
  14049. }
  14050. // load common uniforms
  14051. loadUniformsGeneric( program, material.uniformsList );
  14052. // load material specific uniforms
  14053. // (shader material also gets them for the sake of genericity)
  14054. if ( material instanceof THREE.ShaderMaterial ||
  14055. material instanceof THREE.MeshPhongMaterial ||
  14056. material.envMap ) {
  14057. if ( p_uniforms.cameraPosition !== null ) {
  14058. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14059. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14060. }
  14061. }
  14062. if ( material instanceof THREE.MeshPhongMaterial ||
  14063. material instanceof THREE.MeshLambertMaterial ||
  14064. material instanceof THREE.ShaderMaterial ||
  14065. material.skinning ) {
  14066. if ( p_uniforms.viewMatrix !== null ) {
  14067. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14068. }
  14069. }
  14070. }
  14071. loadUniformsMatrices( p_uniforms, object );
  14072. if ( p_uniforms.modelMatrix !== null ) {
  14073. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14074. }
  14075. return program;
  14076. };
  14077. // Uniforms (refresh uniforms objects)
  14078. function refreshUniformsCommon ( uniforms, material ) {
  14079. uniforms.opacity.value = material.opacity;
  14080. if ( _this.gammaInput ) {
  14081. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14082. } else {
  14083. uniforms.diffuse.value = material.color;
  14084. }
  14085. uniforms.map.value = material.map;
  14086. uniforms.lightMap.value = material.lightMap;
  14087. uniforms.specularMap.value = material.specularMap;
  14088. if ( material.bumpMap ) {
  14089. uniforms.bumpMap.value = material.bumpMap;
  14090. uniforms.bumpScale.value = material.bumpScale;
  14091. }
  14092. if ( material.normalMap ) {
  14093. uniforms.normalMap.value = material.normalMap;
  14094. uniforms.normalScale.value.copy( material.normalScale );
  14095. }
  14096. // uv repeat and offset setting priorities
  14097. // 1. color map
  14098. // 2. specular map
  14099. // 3. normal map
  14100. // 4. bump map
  14101. var uvScaleMap;
  14102. if ( material.map ) {
  14103. uvScaleMap = material.map;
  14104. } else if ( material.specularMap ) {
  14105. uvScaleMap = material.specularMap;
  14106. } else if ( material.normalMap ) {
  14107. uvScaleMap = material.normalMap;
  14108. } else if ( material.bumpMap ) {
  14109. uvScaleMap = material.bumpMap;
  14110. }
  14111. if ( uvScaleMap !== undefined ) {
  14112. var offset = uvScaleMap.offset;
  14113. var repeat = uvScaleMap.repeat;
  14114. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14115. }
  14116. uniforms.envMap.value = material.envMap;
  14117. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14118. if ( _this.gammaInput ) {
  14119. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14120. uniforms.reflectivity.value = material.reflectivity;
  14121. } else {
  14122. uniforms.reflectivity.value = material.reflectivity;
  14123. }
  14124. uniforms.refractionRatio.value = material.refractionRatio;
  14125. uniforms.combine.value = material.combine;
  14126. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14127. };
  14128. function refreshUniformsLine ( uniforms, material ) {
  14129. uniforms.diffuse.value = material.color;
  14130. uniforms.opacity.value = material.opacity;
  14131. };
  14132. function refreshUniformsDash ( uniforms, material ) {
  14133. uniforms.dashSize.value = material.dashSize;
  14134. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14135. uniforms.scale.value = material.scale;
  14136. };
  14137. function refreshUniformsParticle ( uniforms, material ) {
  14138. uniforms.psColor.value = material.color;
  14139. uniforms.opacity.value = material.opacity;
  14140. uniforms.size.value = material.size;
  14141. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14142. uniforms.map.value = material.map;
  14143. };
  14144. function refreshUniformsFog ( uniforms, fog ) {
  14145. uniforms.fogColor.value = fog.color;
  14146. if ( fog instanceof THREE.Fog ) {
  14147. uniforms.fogNear.value = fog.near;
  14148. uniforms.fogFar.value = fog.far;
  14149. } else if ( fog instanceof THREE.FogExp2 ) {
  14150. uniforms.fogDensity.value = fog.density;
  14151. }
  14152. };
  14153. function refreshUniformsPhong ( uniforms, material ) {
  14154. uniforms.shininess.value = material.shininess;
  14155. if ( _this.gammaInput ) {
  14156. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14157. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14158. uniforms.specular.value.copyGammaToLinear( material.specular );
  14159. } else {
  14160. uniforms.ambient.value = material.ambient;
  14161. uniforms.emissive.value = material.emissive;
  14162. uniforms.specular.value = material.specular;
  14163. }
  14164. if ( material.wrapAround ) {
  14165. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14166. }
  14167. };
  14168. function refreshUniformsLambert ( uniforms, material ) {
  14169. if ( _this.gammaInput ) {
  14170. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14171. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14172. } else {
  14173. uniforms.ambient.value = material.ambient;
  14174. uniforms.emissive.value = material.emissive;
  14175. }
  14176. if ( material.wrapAround ) {
  14177. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14178. }
  14179. };
  14180. function refreshUniformsLights ( uniforms, lights ) {
  14181. uniforms.ambientLightColor.value = lights.ambient;
  14182. uniforms.directionalLightColor.value = lights.directional.colors;
  14183. uniforms.directionalLightDirection.value = lights.directional.positions;
  14184. uniforms.pointLightColor.value = lights.point.colors;
  14185. uniforms.pointLightPosition.value = lights.point.positions;
  14186. uniforms.pointLightDistance.value = lights.point.distances;
  14187. uniforms.spotLightColor.value = lights.spot.colors;
  14188. uniforms.spotLightPosition.value = lights.spot.positions;
  14189. uniforms.spotLightDistance.value = lights.spot.distances;
  14190. uniforms.spotLightDirection.value = lights.spot.directions;
  14191. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14192. uniforms.spotLightExponent.value = lights.spot.exponents;
  14193. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14194. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14195. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14196. };
  14197. function refreshUniformsShadow ( uniforms, lights ) {
  14198. if ( uniforms.shadowMatrix ) {
  14199. var j = 0;
  14200. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14201. var light = lights[ i ];
  14202. if ( ! light.castShadow ) continue;
  14203. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14204. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14205. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14206. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14207. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14208. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14209. j ++;
  14210. }
  14211. }
  14212. }
  14213. };
  14214. // Uniforms (load to GPU)
  14215. function loadUniformsMatrices ( uniforms, object ) {
  14216. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14217. if ( uniforms.normalMatrix ) {
  14218. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14219. }
  14220. };
  14221. function getTextureUnit() {
  14222. var textureUnit = _usedTextureUnits;
  14223. if ( textureUnit >= _maxTextures ) {
  14224. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14225. }
  14226. _usedTextureUnits += 1;
  14227. return textureUnit;
  14228. };
  14229. function loadUniformsGeneric ( program, uniforms ) {
  14230. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14231. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14232. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14233. if ( !location ) continue;
  14234. uniform = uniforms[ j ][ 0 ];
  14235. type = uniform.type;
  14236. value = uniform.value;
  14237. if ( type === "i" ) { // single integer
  14238. _gl.uniform1i( location, value );
  14239. } else if ( type === "f" ) { // single float
  14240. _gl.uniform1f( location, value );
  14241. } else if ( type === "v2" ) { // single THREE.Vector2
  14242. _gl.uniform2f( location, value.x, value.y );
  14243. } else if ( type === "v3" ) { // single THREE.Vector3
  14244. _gl.uniform3f( location, value.x, value.y, value.z );
  14245. } else if ( type === "v4" ) { // single THREE.Vector4
  14246. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14247. } else if ( type === "c" ) { // single THREE.Color
  14248. _gl.uniform3f( location, value.r, value.g, value.b );
  14249. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14250. _gl.uniform1iv( location, value );
  14251. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14252. _gl.uniform3iv( location, value );
  14253. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14254. _gl.uniform1fv( location, value );
  14255. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14256. _gl.uniform3fv( location, value );
  14257. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14258. if ( uniform._array === undefined ) {
  14259. uniform._array = new Float32Array( 2 * value.length );
  14260. }
  14261. for ( i = 0, il = value.length; i < il; i ++ ) {
  14262. offset = i * 2;
  14263. uniform._array[ offset ] = value[ i ].x;
  14264. uniform._array[ offset + 1 ] = value[ i ].y;
  14265. }
  14266. _gl.uniform2fv( location, uniform._array );
  14267. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14268. if ( uniform._array === undefined ) {
  14269. uniform._array = new Float32Array( 3 * value.length );
  14270. }
  14271. for ( i = 0, il = value.length; i < il; i ++ ) {
  14272. offset = i * 3;
  14273. uniform._array[ offset ] = value[ i ].x;
  14274. uniform._array[ offset + 1 ] = value[ i ].y;
  14275. uniform._array[ offset + 2 ] = value[ i ].z;
  14276. }
  14277. _gl.uniform3fv( location, uniform._array );
  14278. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14279. if ( uniform._array === undefined ) {
  14280. uniform._array = new Float32Array( 4 * value.length );
  14281. }
  14282. for ( i = 0, il = value.length; i < il; i ++ ) {
  14283. offset = i * 4;
  14284. uniform._array[ offset ] = value[ i ].x;
  14285. uniform._array[ offset + 1 ] = value[ i ].y;
  14286. uniform._array[ offset + 2 ] = value[ i ].z;
  14287. uniform._array[ offset + 3 ] = value[ i ].w;
  14288. }
  14289. _gl.uniform4fv( location, uniform._array );
  14290. } else if ( type === "m4") { // single THREE.Matrix4
  14291. if ( uniform._array === undefined ) {
  14292. uniform._array = new Float32Array( 16 );
  14293. }
  14294. value.flattenToArray( uniform._array );
  14295. _gl.uniformMatrix4fv( location, false, uniform._array );
  14296. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14297. if ( uniform._array === undefined ) {
  14298. uniform._array = new Float32Array( 16 * value.length );
  14299. }
  14300. for ( i = 0, il = value.length; i < il; i ++ ) {
  14301. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14302. }
  14303. _gl.uniformMatrix4fv( location, false, uniform._array );
  14304. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14305. texture = value;
  14306. textureUnit = getTextureUnit();
  14307. _gl.uniform1i( location, textureUnit );
  14308. if ( !texture ) continue;
  14309. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14310. setCubeTexture( texture, textureUnit );
  14311. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14312. setCubeTextureDynamic( texture, textureUnit );
  14313. } else {
  14314. _this.setTexture( texture, textureUnit );
  14315. }
  14316. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14317. if ( uniform._array === undefined ) {
  14318. uniform._array = [];
  14319. }
  14320. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14321. uniform._array[ i ] = getTextureUnit();
  14322. }
  14323. _gl.uniform1iv( location, uniform._array );
  14324. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14325. texture = uniform.value[ i ];
  14326. textureUnit = uniform._array[ i ];
  14327. if ( !texture ) continue;
  14328. _this.setTexture( texture, textureUnit );
  14329. }
  14330. }
  14331. }
  14332. };
  14333. function setupMatrices ( object, camera ) {
  14334. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14335. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14336. };
  14337. //
  14338. function setColorGamma( array, offset, color, intensitySq ) {
  14339. array[ offset ] = color.r * color.r * intensitySq;
  14340. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14341. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14342. };
  14343. function setColorLinear( array, offset, color, intensity ) {
  14344. array[ offset ] = color.r * intensity;
  14345. array[ offset + 1 ] = color.g * intensity;
  14346. array[ offset + 2 ] = color.b * intensity;
  14347. };
  14348. function setupLights ( program, lights ) {
  14349. var l, ll, light, n,
  14350. r = 0, g = 0, b = 0,
  14351. color, skyColor, groundColor,
  14352. intensity, intensitySq,
  14353. position,
  14354. distance,
  14355. zlights = _lights,
  14356. dirColors = zlights.directional.colors,
  14357. dirPositions = zlights.directional.positions,
  14358. pointColors = zlights.point.colors,
  14359. pointPositions = zlights.point.positions,
  14360. pointDistances = zlights.point.distances,
  14361. spotColors = zlights.spot.colors,
  14362. spotPositions = zlights.spot.positions,
  14363. spotDistances = zlights.spot.distances,
  14364. spotDirections = zlights.spot.directions,
  14365. spotAnglesCos = zlights.spot.anglesCos,
  14366. spotExponents = zlights.spot.exponents,
  14367. hemiSkyColors = zlights.hemi.skyColors,
  14368. hemiGroundColors = zlights.hemi.groundColors,
  14369. hemiPositions = zlights.hemi.positions,
  14370. dirLength = 0,
  14371. pointLength = 0,
  14372. spotLength = 0,
  14373. hemiLength = 0,
  14374. dirCount = 0,
  14375. pointCount = 0,
  14376. spotCount = 0,
  14377. hemiCount = 0,
  14378. dirOffset = 0,
  14379. pointOffset = 0,
  14380. spotOffset = 0,
  14381. hemiOffset = 0;
  14382. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14383. light = lights[ l ];
  14384. if ( light.onlyShadow ) continue;
  14385. color = light.color;
  14386. intensity = light.intensity;
  14387. distance = light.distance;
  14388. if ( light instanceof THREE.AmbientLight ) {
  14389. if ( ! light.visible ) continue;
  14390. if ( _this.gammaInput ) {
  14391. r += color.r * color.r;
  14392. g += color.g * color.g;
  14393. b += color.b * color.b;
  14394. } else {
  14395. r += color.r;
  14396. g += color.g;
  14397. b += color.b;
  14398. }
  14399. } else if ( light instanceof THREE.DirectionalLight ) {
  14400. dirCount += 1;
  14401. if ( ! light.visible ) continue;
  14402. _direction.getPositionFromMatrix( light.matrixWorld );
  14403. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14404. _direction.sub( _vector3 );
  14405. _direction.normalize();
  14406. // skip lights with undefined direction
  14407. // these create troubles in OpenGL (making pixel black)
  14408. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14409. dirOffset = dirLength * 3;
  14410. dirPositions[ dirOffset ] = _direction.x;
  14411. dirPositions[ dirOffset + 1 ] = _direction.y;
  14412. dirPositions[ dirOffset + 2 ] = _direction.z;
  14413. if ( _this.gammaInput ) {
  14414. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14415. } else {
  14416. setColorLinear( dirColors, dirOffset, color, intensity );
  14417. }
  14418. dirLength += 1;
  14419. } else if ( light instanceof THREE.PointLight ) {
  14420. pointCount += 1;
  14421. if ( ! light.visible ) continue;
  14422. pointOffset = pointLength * 3;
  14423. if ( _this.gammaInput ) {
  14424. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14425. } else {
  14426. setColorLinear( pointColors, pointOffset, color, intensity );
  14427. }
  14428. _vector3.getPositionFromMatrix( light.matrixWorld );
  14429. pointPositions[ pointOffset ] = _vector3.x;
  14430. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14431. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14432. pointDistances[ pointLength ] = distance;
  14433. pointLength += 1;
  14434. } else if ( light instanceof THREE.SpotLight ) {
  14435. spotCount += 1;
  14436. if ( ! light.visible ) continue;
  14437. spotOffset = spotLength * 3;
  14438. if ( _this.gammaInput ) {
  14439. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14440. } else {
  14441. setColorLinear( spotColors, spotOffset, color, intensity );
  14442. }
  14443. _vector3.getPositionFromMatrix( light.matrixWorld );
  14444. spotPositions[ spotOffset ] = _vector3.x;
  14445. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14446. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14447. spotDistances[ spotLength ] = distance;
  14448. _direction.copy( _vector3 );
  14449. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14450. _direction.sub( _vector3 );
  14451. _direction.normalize();
  14452. spotDirections[ spotOffset ] = _direction.x;
  14453. spotDirections[ spotOffset + 1 ] = _direction.y;
  14454. spotDirections[ spotOffset + 2 ] = _direction.z;
  14455. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14456. spotExponents[ spotLength ] = light.exponent;
  14457. spotLength += 1;
  14458. } else if ( light instanceof THREE.HemisphereLight ) {
  14459. hemiCount += 1;
  14460. if ( ! light.visible ) continue;
  14461. _direction.getPositionFromMatrix( light.matrixWorld );
  14462. _direction.normalize();
  14463. // skip lights with undefined direction
  14464. // these create troubles in OpenGL (making pixel black)
  14465. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14466. hemiOffset = hemiLength * 3;
  14467. hemiPositions[ hemiOffset ] = _direction.x;
  14468. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14469. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14470. skyColor = light.color;
  14471. groundColor = light.groundColor;
  14472. if ( _this.gammaInput ) {
  14473. intensitySq = intensity * intensity;
  14474. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14475. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14476. } else {
  14477. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14478. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14479. }
  14480. hemiLength += 1;
  14481. }
  14482. }
  14483. // null eventual remains from removed lights
  14484. // (this is to avoid if in shader)
  14485. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14486. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14487. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14488. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14489. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14490. zlights.directional.length = dirLength;
  14491. zlights.point.length = pointLength;
  14492. zlights.spot.length = spotLength;
  14493. zlights.hemi.length = hemiLength;
  14494. zlights.ambient[ 0 ] = r;
  14495. zlights.ambient[ 1 ] = g;
  14496. zlights.ambient[ 2 ] = b;
  14497. };
  14498. // GL state setting
  14499. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14500. if ( cullFace === THREE.CullFaceNone ) {
  14501. _gl.disable( _gl.CULL_FACE );
  14502. } else {
  14503. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14504. _gl.frontFace( _gl.CW );
  14505. } else {
  14506. _gl.frontFace( _gl.CCW );
  14507. }
  14508. if ( cullFace === THREE.CullFaceBack ) {
  14509. _gl.cullFace( _gl.BACK );
  14510. } else if ( cullFace === THREE.CullFaceFront ) {
  14511. _gl.cullFace( _gl.FRONT );
  14512. } else {
  14513. _gl.cullFace( _gl.FRONT_AND_BACK );
  14514. }
  14515. _gl.enable( _gl.CULL_FACE );
  14516. }
  14517. };
  14518. this.setMaterialFaces = function ( material ) {
  14519. var doubleSided = material.side === THREE.DoubleSide;
  14520. var flipSided = material.side === THREE.BackSide;
  14521. if ( _oldDoubleSided !== doubleSided ) {
  14522. if ( doubleSided ) {
  14523. _gl.disable( _gl.CULL_FACE );
  14524. } else {
  14525. _gl.enable( _gl.CULL_FACE );
  14526. }
  14527. _oldDoubleSided = doubleSided;
  14528. }
  14529. if ( _oldFlipSided !== flipSided ) {
  14530. if ( flipSided ) {
  14531. _gl.frontFace( _gl.CW );
  14532. } else {
  14533. _gl.frontFace( _gl.CCW );
  14534. }
  14535. _oldFlipSided = flipSided;
  14536. }
  14537. };
  14538. this.setDepthTest = function ( depthTest ) {
  14539. if ( _oldDepthTest !== depthTest ) {
  14540. if ( depthTest ) {
  14541. _gl.enable( _gl.DEPTH_TEST );
  14542. } else {
  14543. _gl.disable( _gl.DEPTH_TEST );
  14544. }
  14545. _oldDepthTest = depthTest;
  14546. }
  14547. };
  14548. this.setDepthWrite = function ( depthWrite ) {
  14549. if ( _oldDepthWrite !== depthWrite ) {
  14550. _gl.depthMask( depthWrite );
  14551. _oldDepthWrite = depthWrite;
  14552. }
  14553. };
  14554. function setLineWidth ( width ) {
  14555. if ( width !== _oldLineWidth ) {
  14556. _gl.lineWidth( width );
  14557. _oldLineWidth = width;
  14558. }
  14559. };
  14560. function setPolygonOffset ( polygonoffset, factor, units ) {
  14561. if ( _oldPolygonOffset !== polygonoffset ) {
  14562. if ( polygonoffset ) {
  14563. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14564. } else {
  14565. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14566. }
  14567. _oldPolygonOffset = polygonoffset;
  14568. }
  14569. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14570. _gl.polygonOffset( factor, units );
  14571. _oldPolygonOffsetFactor = factor;
  14572. _oldPolygonOffsetUnits = units;
  14573. }
  14574. };
  14575. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14576. if ( blending !== _oldBlending ) {
  14577. if ( blending === THREE.NoBlending ) {
  14578. _gl.disable( _gl.BLEND );
  14579. } else if ( blending === THREE.AdditiveBlending ) {
  14580. _gl.enable( _gl.BLEND );
  14581. _gl.blendEquation( _gl.FUNC_ADD );
  14582. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14583. } else if ( blending === THREE.SubtractiveBlending ) {
  14584. // TODO: Find blendFuncSeparate() combination
  14585. _gl.enable( _gl.BLEND );
  14586. _gl.blendEquation( _gl.FUNC_ADD );
  14587. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14588. } else if ( blending === THREE.MultiplyBlending ) {
  14589. // TODO: Find blendFuncSeparate() combination
  14590. _gl.enable( _gl.BLEND );
  14591. _gl.blendEquation( _gl.FUNC_ADD );
  14592. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14593. } else if ( blending === THREE.CustomBlending ) {
  14594. _gl.enable( _gl.BLEND );
  14595. } else {
  14596. _gl.enable( _gl.BLEND );
  14597. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14598. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14599. }
  14600. _oldBlending = blending;
  14601. }
  14602. if ( blending === THREE.CustomBlending ) {
  14603. if ( blendEquation !== _oldBlendEquation ) {
  14604. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14605. _oldBlendEquation = blendEquation;
  14606. }
  14607. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14608. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14609. _oldBlendSrc = blendSrc;
  14610. _oldBlendDst = blendDst;
  14611. }
  14612. } else {
  14613. _oldBlendEquation = null;
  14614. _oldBlendSrc = null;
  14615. _oldBlendDst = null;
  14616. }
  14617. };
  14618. // Defines
  14619. function generateDefines ( defines ) {
  14620. var value, chunk, chunks = [];
  14621. for ( var d in defines ) {
  14622. value = defines[ d ];
  14623. if ( value === false ) continue;
  14624. chunk = "#define " + d + " " + value;
  14625. chunks.push( chunk );
  14626. }
  14627. return chunks.join( "\n" );
  14628. };
  14629. // Shaders
  14630. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  14631. var p, pl, d, program, code;
  14632. var chunks = [];
  14633. // Generate code
  14634. if ( shaderID ) {
  14635. chunks.push( shaderID );
  14636. } else {
  14637. chunks.push( fragmentShader );
  14638. chunks.push( vertexShader );
  14639. }
  14640. for ( d in defines ) {
  14641. chunks.push( d );
  14642. chunks.push( defines[ d ] );
  14643. }
  14644. for ( p in parameters ) {
  14645. chunks.push( p );
  14646. chunks.push( parameters[ p ] );
  14647. }
  14648. code = chunks.join();
  14649. // Check if code has been already compiled
  14650. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14651. var programInfo = _programs[ p ];
  14652. if ( programInfo.code === code ) {
  14653. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14654. programInfo.usedTimes ++;
  14655. return programInfo.program;
  14656. }
  14657. }
  14658. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14659. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14660. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14661. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14662. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14663. }
  14664. // console.log( "building new program " );
  14665. //
  14666. var customDefines = generateDefines( defines );
  14667. //
  14668. program = _gl.createProgram();
  14669. var prefix_vertex = [
  14670. "precision " + _precision + " float;",
  14671. customDefines,
  14672. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14673. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14674. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14675. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14676. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14677. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14678. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14679. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14680. "#define MAX_SHADOWS " + parameters.maxShadows,
  14681. "#define MAX_BONES " + parameters.maxBones,
  14682. parameters.map ? "#define USE_MAP" : "",
  14683. parameters.envMap ? "#define USE_ENVMAP" : "",
  14684. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14685. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14686. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14687. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14688. parameters.vertexColors ? "#define USE_COLOR" : "",
  14689. parameters.skinning ? "#define USE_SKINNING" : "",
  14690. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14691. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  14692. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  14693. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14694. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14695. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14696. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14697. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14698. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14699. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14700. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14701. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14702. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14703. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14704. "uniform mat4 modelMatrix;",
  14705. "uniform mat4 modelViewMatrix;",
  14706. "uniform mat4 projectionMatrix;",
  14707. "uniform mat4 viewMatrix;",
  14708. "uniform mat3 normalMatrix;",
  14709. "uniform vec3 cameraPosition;",
  14710. "attribute vec3 position;",
  14711. "attribute vec3 normal;",
  14712. "attribute vec2 uv;",
  14713. "attribute vec2 uv2;",
  14714. "#ifdef USE_COLOR",
  14715. "attribute vec3 color;",
  14716. "#endif",
  14717. "#ifdef USE_MORPHTARGETS",
  14718. "attribute vec3 morphTarget0;",
  14719. "attribute vec3 morphTarget1;",
  14720. "attribute vec3 morphTarget2;",
  14721. "attribute vec3 morphTarget3;",
  14722. "#ifdef USE_MORPHNORMALS",
  14723. "attribute vec3 morphNormal0;",
  14724. "attribute vec3 morphNormal1;",
  14725. "attribute vec3 morphNormal2;",
  14726. "attribute vec3 morphNormal3;",
  14727. "#else",
  14728. "attribute vec3 morphTarget4;",
  14729. "attribute vec3 morphTarget5;",
  14730. "attribute vec3 morphTarget6;",
  14731. "attribute vec3 morphTarget7;",
  14732. "#endif",
  14733. "#endif",
  14734. "#ifdef USE_SKINNING",
  14735. "attribute vec4 skinIndex;",
  14736. "attribute vec4 skinWeight;",
  14737. "#endif",
  14738. ""
  14739. ].join("\n");
  14740. var prefix_fragment = [
  14741. "precision " + _precision + " float;",
  14742. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14743. customDefines,
  14744. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14745. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14746. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14747. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14748. "#define MAX_SHADOWS " + parameters.maxShadows,
  14749. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14750. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14751. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14752. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14753. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14754. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14755. parameters.map ? "#define USE_MAP" : "",
  14756. parameters.envMap ? "#define USE_ENVMAP" : "",
  14757. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14758. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14759. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14760. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14761. parameters.vertexColors ? "#define USE_COLOR" : "",
  14762. parameters.metal ? "#define METAL" : "",
  14763. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14764. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14765. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14766. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14767. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14768. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14769. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14770. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14771. "uniform mat4 viewMatrix;",
  14772. "uniform vec3 cameraPosition;",
  14773. ""
  14774. ].join("\n");
  14775. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14776. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14777. _gl.attachShader( program, glVertexShader );
  14778. _gl.attachShader( program, glFragmentShader );
  14779. _gl.linkProgram( program );
  14780. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14781. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14782. }
  14783. // clean up
  14784. _gl.deleteShader( glFragmentShader );
  14785. _gl.deleteShader( glVertexShader );
  14786. // console.log( prefix_fragment + fragmentShader );
  14787. // console.log( prefix_vertex + vertexShader );
  14788. program.uniforms = {};
  14789. program.attributes = {};
  14790. var identifiers, u, a, i;
  14791. // cache uniform locations
  14792. identifiers = [
  14793. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14794. 'morphTargetInfluences'
  14795. ];
  14796. if ( parameters.useVertexTexture ) {
  14797. identifiers.push( 'boneTexture' );
  14798. } else {
  14799. identifiers.push( 'boneGlobalMatrices' );
  14800. }
  14801. for ( u in uniforms ) {
  14802. identifiers.push( u );
  14803. }
  14804. cacheUniformLocations( program, identifiers );
  14805. // cache attributes locations
  14806. identifiers = [
  14807. "position", "normal", "uv", "uv2", "tangent", "color",
  14808. "skinIndex", "skinWeight", "lineDistance"
  14809. ];
  14810. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14811. identifiers.push( "morphTarget" + i );
  14812. }
  14813. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14814. identifiers.push( "morphNormal" + i );
  14815. }
  14816. for ( a in attributes ) {
  14817. identifiers.push( a );
  14818. }
  14819. cacheAttributeLocations( program, identifiers );
  14820. program.id = _programs_counter ++;
  14821. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14822. _this.info.memory.programs = _programs.length;
  14823. return program;
  14824. };
  14825. // Shader parameters cache
  14826. function cacheUniformLocations ( program, identifiers ) {
  14827. var i, l, id;
  14828. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14829. id = identifiers[ i ];
  14830. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14831. }
  14832. };
  14833. function cacheAttributeLocations ( program, identifiers ) {
  14834. var i, l, id;
  14835. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14836. id = identifiers[ i ];
  14837. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14838. }
  14839. };
  14840. function addLineNumbers ( string ) {
  14841. var chunks = string.split( "\n" );
  14842. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14843. // Chrome reports shader errors on lines
  14844. // starting counting from 1
  14845. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14846. }
  14847. return chunks.join( "\n" );
  14848. };
  14849. function getShader ( type, string ) {
  14850. var shader;
  14851. if ( type === "fragment" ) {
  14852. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14853. } else if ( type === "vertex" ) {
  14854. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14855. }
  14856. _gl.shaderSource( shader, string );
  14857. _gl.compileShader( shader );
  14858. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14859. console.error( _gl.getShaderInfoLog( shader ) );
  14860. console.error( addLineNumbers( string ) );
  14861. return null;
  14862. }
  14863. return shader;
  14864. };
  14865. // Textures
  14866. function isPowerOfTwo ( value ) {
  14867. return ( value & ( value - 1 ) ) === 0;
  14868. };
  14869. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14870. if ( isImagePowerOfTwo ) {
  14871. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14872. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14873. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14874. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14875. } else {
  14876. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14877. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14878. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14879. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14880. }
  14881. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14882. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14883. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14884. texture.__oldAnisotropy = texture.anisotropy;
  14885. }
  14886. }
  14887. };
  14888. this.setTexture = function ( texture, slot ) {
  14889. if ( texture.needsUpdate ) {
  14890. if ( ! texture.__webglInit ) {
  14891. texture.__webglInit = true;
  14892. texture.addEventListener( 'dispose', onTextureDispose );
  14893. texture.__webglTexture = _gl.createTexture();
  14894. _this.info.memory.textures ++;
  14895. }
  14896. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14897. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14898. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14899. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14900. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14901. var image = texture.image,
  14902. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14903. glFormat = paramThreeToGL( texture.format ),
  14904. glType = paramThreeToGL( texture.type );
  14905. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14906. var mipmap, mipmaps = texture.mipmaps;
  14907. if ( texture instanceof THREE.DataTexture ) {
  14908. // use manually created mipmaps if available
  14909. // if there are no manual mipmaps
  14910. // set 0 level mipmap and then use GL to generate other mipmap levels
  14911. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14912. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14913. mipmap = mipmaps[ i ];
  14914. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14915. }
  14916. texture.generateMipmaps = false;
  14917. } else {
  14918. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14919. }
  14920. } else if ( texture instanceof THREE.CompressedTexture ) {
  14921. // compressed textures can only use manually created mipmaps
  14922. // WebGL can't generate mipmaps for DDS textures
  14923. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14924. mipmap = mipmaps[ i ];
  14925. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14926. }
  14927. } else { // regular Texture (image, video, canvas)
  14928. // use manually created mipmaps if available
  14929. // if there are no manual mipmaps
  14930. // set 0 level mipmap and then use GL to generate other mipmap levels
  14931. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14932. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14933. mipmap = mipmaps[ i ];
  14934. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14935. }
  14936. texture.generateMipmaps = false;
  14937. } else {
  14938. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14939. }
  14940. }
  14941. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14942. texture.needsUpdate = false;
  14943. if ( texture.onUpdate ) texture.onUpdate();
  14944. } else {
  14945. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14946. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14947. }
  14948. };
  14949. function clampToMaxSize ( image, maxSize ) {
  14950. if ( image.width <= maxSize && image.height <= maxSize ) {
  14951. return image;
  14952. }
  14953. // Warning: Scaling through the canvas will only work with images that use
  14954. // premultiplied alpha.
  14955. var maxDimension = Math.max( image.width, image.height );
  14956. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14957. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14958. var canvas = document.createElement( 'canvas' );
  14959. canvas.width = newWidth;
  14960. canvas.height = newHeight;
  14961. var ctx = canvas.getContext( "2d" );
  14962. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14963. return canvas;
  14964. }
  14965. function setCubeTexture ( texture, slot ) {
  14966. if ( texture.image.length === 6 ) {
  14967. if ( texture.needsUpdate ) {
  14968. if ( ! texture.image.__webglTextureCube ) {
  14969. texture.image.__webglTextureCube = _gl.createTexture();
  14970. _this.info.memory.textures ++;
  14971. }
  14972. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14973. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14974. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14975. var isCompressed = texture instanceof THREE.CompressedTexture;
  14976. var cubeImage = [];
  14977. for ( var i = 0; i < 6; i ++ ) {
  14978. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14979. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14980. } else {
  14981. cubeImage[ i ] = texture.image[ i ];
  14982. }
  14983. }
  14984. var image = cubeImage[ 0 ],
  14985. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14986. glFormat = paramThreeToGL( texture.format ),
  14987. glType = paramThreeToGL( texture.type );
  14988. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14989. for ( var i = 0; i < 6; i ++ ) {
  14990. if ( isCompressed ) {
  14991. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14992. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14993. mipmap = mipmaps[ j ];
  14994. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14995. }
  14996. } else {
  14997. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14998. }
  14999. }
  15000. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15001. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15002. }
  15003. texture.needsUpdate = false;
  15004. if ( texture.onUpdate ) texture.onUpdate();
  15005. } else {
  15006. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15007. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15008. }
  15009. }
  15010. };
  15011. function setCubeTextureDynamic ( texture, slot ) {
  15012. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15013. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15014. };
  15015. // Render targets
  15016. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15017. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15018. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15019. };
  15020. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15021. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15022. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15023. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15024. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15025. /* For some reason this is not working. Defaulting to RGBA4.
  15026. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15027. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15028. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15029. */
  15030. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15031. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15032. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15033. } else {
  15034. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15035. }
  15036. };
  15037. this.setRenderTarget = function ( renderTarget ) {
  15038. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15039. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15040. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15041. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15042. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15043. renderTarget.__webglTexture = _gl.createTexture();
  15044. _this.info.memory.textures ++;
  15045. // Setup texture, create render and frame buffers
  15046. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15047. glFormat = paramThreeToGL( renderTarget.format ),
  15048. glType = paramThreeToGL( renderTarget.type );
  15049. if ( isCube ) {
  15050. renderTarget.__webglFramebuffer = [];
  15051. renderTarget.__webglRenderbuffer = [];
  15052. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15053. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15054. for ( var i = 0; i < 6; i ++ ) {
  15055. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15056. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15057. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15058. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15059. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15060. }
  15061. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15062. } else {
  15063. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15064. if ( renderTarget.shareDepthFrom ) {
  15065. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15066. } else {
  15067. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15068. }
  15069. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15070. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15071. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15072. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15073. if ( renderTarget.shareDepthFrom ) {
  15074. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15075. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15076. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15077. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15078. }
  15079. } else {
  15080. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15081. }
  15082. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15083. }
  15084. // Release everything
  15085. if ( isCube ) {
  15086. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15087. } else {
  15088. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15089. }
  15090. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15091. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15092. }
  15093. var framebuffer, width, height, vx, vy;
  15094. if ( renderTarget ) {
  15095. if ( isCube ) {
  15096. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15097. } else {
  15098. framebuffer = renderTarget.__webglFramebuffer;
  15099. }
  15100. width = renderTarget.width;
  15101. height = renderTarget.height;
  15102. vx = 0;
  15103. vy = 0;
  15104. } else {
  15105. framebuffer = null;
  15106. width = _viewportWidth;
  15107. height = _viewportHeight;
  15108. vx = _viewportX;
  15109. vy = _viewportY;
  15110. }
  15111. if ( framebuffer !== _currentFramebuffer ) {
  15112. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15113. _gl.viewport( vx, vy, width, height );
  15114. _currentFramebuffer = framebuffer;
  15115. }
  15116. _currentWidth = width;
  15117. _currentHeight = height;
  15118. };
  15119. function updateRenderTargetMipmap ( renderTarget ) {
  15120. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15121. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15122. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15123. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15124. } else {
  15125. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15126. _gl.generateMipmap( _gl.TEXTURE_2D );
  15127. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15128. }
  15129. };
  15130. // Fallback filters for non-power-of-2 textures
  15131. function filterFallback ( f ) {
  15132. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15133. return _gl.NEAREST;
  15134. }
  15135. return _gl.LINEAR;
  15136. };
  15137. // Map three.js constants to WebGL constants
  15138. function paramThreeToGL ( p ) {
  15139. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15140. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15141. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15142. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15143. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15144. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15145. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15146. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15147. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15148. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15149. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15150. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15151. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15152. if ( p === THREE.ByteType ) return _gl.BYTE;
  15153. if ( p === THREE.ShortType ) return _gl.SHORT;
  15154. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15155. if ( p === THREE.IntType ) return _gl.INT;
  15156. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15157. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15158. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15159. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15160. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15161. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15162. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15163. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15164. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15165. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15166. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15167. if ( p === THREE.OneFactor ) return _gl.ONE;
  15168. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15169. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15170. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15171. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15172. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15173. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15174. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15175. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15176. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15177. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15178. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15179. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15180. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15181. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15182. }
  15183. return 0;
  15184. };
  15185. // Allocations
  15186. function allocateBones ( object ) {
  15187. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15188. return 1024;
  15189. } else {
  15190. // default for when object is not specified
  15191. // ( for example when prebuilding shader
  15192. // to be used with multiple objects )
  15193. //
  15194. // - leave some extra space for other uniforms
  15195. // - limit here is ANGLE's 254 max uniform vectors
  15196. // (up to 54 should be safe)
  15197. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15198. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15199. var maxBones = nVertexMatrices;
  15200. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15201. maxBones = Math.min( object.bones.length, maxBones );
  15202. if ( maxBones < object.bones.length ) {
  15203. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15204. }
  15205. }
  15206. return maxBones;
  15207. }
  15208. };
  15209. function allocateLights ( lights ) {
  15210. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  15211. dirLights = pointLights = spotLights = hemiLights = 0;
  15212. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15213. light = lights[ l ];
  15214. if ( light.onlyShadow ) continue;
  15215. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15216. if ( light instanceof THREE.PointLight ) pointLights ++;
  15217. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15218. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15219. }
  15220. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15221. };
  15222. function allocateShadows ( lights ) {
  15223. var l, ll, light, maxShadows = 0;
  15224. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  15225. light = lights[ l ];
  15226. if ( ! light.castShadow ) continue;
  15227. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15228. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15229. }
  15230. return maxShadows;
  15231. };
  15232. // Initialization
  15233. function initGL () {
  15234. try {
  15235. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15236. throw 'Error creating WebGL context.';
  15237. }
  15238. } catch ( error ) {
  15239. console.error( error );
  15240. }
  15241. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15242. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15243. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  15244. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  15245. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15246. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  15247. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  15248. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15249. if ( ! _glExtensionTextureFloat ) {
  15250. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15251. }
  15252. if ( ! _glExtensionStandardDerivatives ) {
  15253. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15254. }
  15255. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15256. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15257. }
  15258. if ( ! _glExtensionCompressedTextureS3TC ) {
  15259. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15260. }
  15261. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15262. _gl.getShaderPrecisionFormat = function() {
  15263. return {
  15264. "rangeMin" : 1,
  15265. "rangeMax" : 1,
  15266. "precision" : 1
  15267. };
  15268. }
  15269. }
  15270. };
  15271. function setDefaultGLState () {
  15272. _gl.clearColor( 0, 0, 0, 1 );
  15273. _gl.clearDepth( 1 );
  15274. _gl.clearStencil( 0 );
  15275. _gl.enable( _gl.DEPTH_TEST );
  15276. _gl.depthFunc( _gl.LEQUAL );
  15277. _gl.frontFace( _gl.CCW );
  15278. _gl.cullFace( _gl.BACK );
  15279. _gl.enable( _gl.CULL_FACE );
  15280. _gl.enable( _gl.BLEND );
  15281. _gl.blendEquation( _gl.FUNC_ADD );
  15282. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15283. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15284. };
  15285. // default plugins (order is important)
  15286. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15287. this.addPrePlugin( this.shadowMapPlugin );
  15288. this.addPostPlugin( new THREE.SpritePlugin() );
  15289. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15290. };
  15291. /**
  15292. * @author szimek / https://github.com/szimek/
  15293. * @author alteredq / http://alteredqualia.com/
  15294. */
  15295. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15296. this.width = width;
  15297. this.height = height;
  15298. options = options || {};
  15299. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15300. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15301. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15302. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15303. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15304. this.offset = new THREE.Vector2( 0, 0 );
  15305. this.repeat = new THREE.Vector2( 1, 1 );
  15306. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15307. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15308. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15309. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15310. this.generateMipmaps = true;
  15311. this.shareDepthFrom = null;
  15312. };
  15313. THREE.WebGLRenderTarget.prototype = {
  15314. constructor: THREE.WebGLRenderTarget,
  15315. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  15316. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  15317. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  15318. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  15319. clone: function () {
  15320. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15321. tmp.wrapS = this.wrapS;
  15322. tmp.wrapT = this.wrapT;
  15323. tmp.magFilter = this.magFilter;
  15324. tmp.minFilter = this.minFilter;
  15325. tmp.anisotropy = this.anisotropy;
  15326. tmp.offset.copy( this.offset );
  15327. tmp.repeat.copy( this.repeat );
  15328. tmp.format = this.format;
  15329. tmp.type = this.type;
  15330. tmp.depthBuffer = this.depthBuffer;
  15331. tmp.stencilBuffer = this.stencilBuffer;
  15332. tmp.generateMipmaps = this.generateMipmaps;
  15333. tmp.shareDepthFrom = this.shareDepthFrom;
  15334. return tmp;
  15335. },
  15336. dispose: function () {
  15337. this.dispatchEvent( { type: 'dispose' } );
  15338. }
  15339. };
  15340. /**
  15341. * @author alteredq / http://alteredqualia.com
  15342. */
  15343. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15344. THREE.WebGLRenderTarget.call( this, width, height, options );
  15345. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15346. };
  15347. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15348. /**
  15349. * @author mrdoob / http://mrdoob.com/
  15350. */
  15351. THREE.RenderableVertex = function () {
  15352. this.positionWorld = new THREE.Vector3();
  15353. this.positionScreen = new THREE.Vector4();
  15354. this.visible = true;
  15355. };
  15356. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15357. this.positionWorld.copy( vertex.positionWorld );
  15358. this.positionScreen.copy( vertex.positionScreen );
  15359. };
  15360. /**
  15361. * @author mrdoob / http://mrdoob.com/
  15362. */
  15363. THREE.RenderableFace3 = function () {
  15364. this.v1 = new THREE.RenderableVertex();
  15365. this.v2 = new THREE.RenderableVertex();
  15366. this.v3 = new THREE.RenderableVertex();
  15367. this.centroidModel = new THREE.Vector3();
  15368. this.normalModel = new THREE.Vector3();
  15369. this.normalModelView = new THREE.Vector3();
  15370. this.vertexNormalsLength = 0;
  15371. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15372. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15373. this.color = null;
  15374. this.material = null;
  15375. this.uvs = [[]];
  15376. this.z = null;
  15377. };
  15378. /**
  15379. * @author mrdoob / http://mrdoob.com/
  15380. */
  15381. THREE.RenderableFace4 = function () {
  15382. this.v1 = new THREE.RenderableVertex();
  15383. this.v2 = new THREE.RenderableVertex();
  15384. this.v3 = new THREE.RenderableVertex();
  15385. this.v4 = new THREE.RenderableVertex();
  15386. this.centroidModel = new THREE.Vector3();
  15387. this.normalModel = new THREE.Vector3();
  15388. this.normalModelView = new THREE.Vector3();
  15389. this.vertexNormalsLength = 0;
  15390. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15391. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15392. this.color = null;
  15393. this.material = null;
  15394. this.uvs = [[]];
  15395. this.z = null;
  15396. };
  15397. /**
  15398. * @author mrdoob / http://mrdoob.com/
  15399. */
  15400. THREE.RenderableObject = function () {
  15401. this.object = null;
  15402. this.z = null;
  15403. };
  15404. /**
  15405. * @author mrdoob / http://mrdoob.com/
  15406. */
  15407. THREE.RenderableParticle = function () {
  15408. this.object = null;
  15409. this.x = null;
  15410. this.y = null;
  15411. this.z = null;
  15412. this.rotation = null;
  15413. this.scale = new THREE.Vector2();
  15414. this.material = null;
  15415. };
  15416. /**
  15417. * @author mrdoob / http://mrdoob.com/
  15418. */
  15419. THREE.RenderableLine = function () {
  15420. this.z = null;
  15421. this.v1 = new THREE.RenderableVertex();
  15422. this.v2 = new THREE.RenderableVertex();
  15423. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15424. this.material = null;
  15425. };
  15426. /**
  15427. * @author mrdoob / http://mrdoob.com/
  15428. * @author alteredq / http://alteredqualia.com/
  15429. */
  15430. THREE.GeometryUtils = {
  15431. // Merge two geometries or geometry and geometry from object (using object's transform)
  15432. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15433. var matrix, normalMatrix,
  15434. vertexOffset = geometry1.vertices.length,
  15435. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15436. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15437. vertices1 = geometry1.vertices,
  15438. vertices2 = geometry2.vertices,
  15439. faces1 = geometry1.faces,
  15440. faces2 = geometry2.faces,
  15441. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15442. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15443. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15444. if ( object2 instanceof THREE.Mesh ) {
  15445. object2.matrixAutoUpdate && object2.updateMatrix();
  15446. matrix = object2.matrix;
  15447. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15448. }
  15449. // vertices
  15450. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15451. var vertex = vertices2[ i ];
  15452. var vertexCopy = vertex.clone();
  15453. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15454. vertices1.push( vertexCopy );
  15455. }
  15456. // faces
  15457. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15458. var face = faces2[ i ], faceCopy, normal, color,
  15459. faceVertexNormals = face.vertexNormals,
  15460. faceVertexColors = face.vertexColors;
  15461. if ( face instanceof THREE.Face3 ) {
  15462. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15463. } else if ( face instanceof THREE.Face4 ) {
  15464. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15465. }
  15466. faceCopy.normal.copy( face.normal );
  15467. if ( normalMatrix ) {
  15468. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15469. }
  15470. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15471. normal = faceVertexNormals[ j ].clone();
  15472. if ( normalMatrix ) {
  15473. normal.applyMatrix3( normalMatrix ).normalize();
  15474. }
  15475. faceCopy.vertexNormals.push( normal );
  15476. }
  15477. faceCopy.color.copy( face.color );
  15478. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15479. color = faceVertexColors[ j ];
  15480. faceCopy.vertexColors.push( color.clone() );
  15481. }
  15482. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15483. faceCopy.centroid.copy( face.centroid );
  15484. if ( matrix ) {
  15485. faceCopy.centroid.applyMatrix4( matrix );
  15486. }
  15487. faces1.push( faceCopy );
  15488. }
  15489. // uvs
  15490. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15491. var uv = uvs2[ i ], uvCopy = [];
  15492. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15493. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15494. }
  15495. uvs1.push( uvCopy );
  15496. }
  15497. },
  15498. removeMaterials: function ( geometry, materialIndexArray ) {
  15499. var materialIndexMap = {};
  15500. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15501. materialIndexMap[ materialIndexArray[i] ] = true;
  15502. }
  15503. var face, newFaces = [];
  15504. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15505. face = geometry.faces[ i ];
  15506. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15507. }
  15508. geometry.faces = newFaces;
  15509. },
  15510. // Get random point in triangle (via barycentric coordinates)
  15511. // (uniform distribution)
  15512. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15513. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15514. var a, b, c,
  15515. point = new THREE.Vector3(),
  15516. tmp = THREE.GeometryUtils.__v1;
  15517. a = THREE.GeometryUtils.random();
  15518. b = THREE.GeometryUtils.random();
  15519. if ( ( a + b ) > 1 ) {
  15520. a = 1 - a;
  15521. b = 1 - b;
  15522. }
  15523. c = 1 - a - b;
  15524. point.copy( vectorA );
  15525. point.multiplyScalar( a );
  15526. tmp.copy( vectorB );
  15527. tmp.multiplyScalar( b );
  15528. point.add( tmp );
  15529. tmp.copy( vectorC );
  15530. tmp.multiplyScalar( c );
  15531. point.add( tmp );
  15532. return point;
  15533. },
  15534. // Get random point in face (triangle / quad)
  15535. // (uniform distribution)
  15536. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15537. var vA, vB, vC, vD;
  15538. if ( face instanceof THREE.Face3 ) {
  15539. vA = geometry.vertices[ face.a ];
  15540. vB = geometry.vertices[ face.b ];
  15541. vC = geometry.vertices[ face.c ];
  15542. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15543. } else if ( face instanceof THREE.Face4 ) {
  15544. vA = geometry.vertices[ face.a ];
  15545. vB = geometry.vertices[ face.b ];
  15546. vC = geometry.vertices[ face.c ];
  15547. vD = geometry.vertices[ face.d ];
  15548. var area1, area2;
  15549. if ( useCachedAreas ) {
  15550. if ( face._area1 && face._area2 ) {
  15551. area1 = face._area1;
  15552. area2 = face._area2;
  15553. } else {
  15554. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15555. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15556. face._area1 = area1;
  15557. face._area2 = area2;
  15558. }
  15559. } else {
  15560. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15561. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15562. }
  15563. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15564. if ( r < area1 ) {
  15565. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15566. } else {
  15567. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15568. }
  15569. }
  15570. },
  15571. // Get uniformly distributed random points in mesh
  15572. // - create array with cumulative sums of face areas
  15573. // - pick random number from 0 to total area
  15574. // - find corresponding place in area array by binary search
  15575. // - get random point in face
  15576. randomPointsInGeometry: function ( geometry, n ) {
  15577. var face, i,
  15578. faces = geometry.faces,
  15579. vertices = geometry.vertices,
  15580. il = faces.length,
  15581. totalArea = 0,
  15582. cumulativeAreas = [],
  15583. vA, vB, vC, vD;
  15584. // precompute face areas
  15585. for ( i = 0; i < il; i ++ ) {
  15586. face = faces[ i ];
  15587. if ( face instanceof THREE.Face3 ) {
  15588. vA = vertices[ face.a ];
  15589. vB = vertices[ face.b ];
  15590. vC = vertices[ face.c ];
  15591. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15592. } else if ( face instanceof THREE.Face4 ) {
  15593. vA = vertices[ face.a ];
  15594. vB = vertices[ face.b ];
  15595. vC = vertices[ face.c ];
  15596. vD = vertices[ face.d ];
  15597. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15598. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15599. face._area = face._area1 + face._area2;
  15600. }
  15601. totalArea += face._area;
  15602. cumulativeAreas[ i ] = totalArea;
  15603. }
  15604. // binary search cumulative areas array
  15605. function binarySearchIndices( value ) {
  15606. function binarySearch( start, end ) {
  15607. // return closest larger index
  15608. // if exact number is not found
  15609. if ( end < start )
  15610. return start;
  15611. var mid = start + Math.floor( ( end - start ) / 2 );
  15612. if ( cumulativeAreas[ mid ] > value ) {
  15613. return binarySearch( start, mid - 1 );
  15614. } else if ( cumulativeAreas[ mid ] < value ) {
  15615. return binarySearch( mid + 1, end );
  15616. } else {
  15617. return mid;
  15618. }
  15619. }
  15620. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15621. return result;
  15622. }
  15623. // pick random face weighted by face area
  15624. var r, index,
  15625. result = [];
  15626. var stats = {};
  15627. for ( i = 0; i < n; i ++ ) {
  15628. r = THREE.GeometryUtils.random() * totalArea;
  15629. index = binarySearchIndices( r );
  15630. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15631. if ( ! stats[ index ] ) {
  15632. stats[ index ] = 1;
  15633. } else {
  15634. stats[ index ] += 1;
  15635. }
  15636. }
  15637. return result;
  15638. },
  15639. // Get triangle area (half of parallelogram)
  15640. // http://mathworld.wolfram.com/TriangleArea.html
  15641. triangleArea: function ( vectorA, vectorB, vectorC ) {
  15642. var tmp1 = THREE.GeometryUtils.__v1,
  15643. tmp2 = THREE.GeometryUtils.__v2;
  15644. tmp1.subVectors( vectorB, vectorA );
  15645. tmp2.subVectors( vectorC, vectorA );
  15646. tmp1.cross( tmp2 );
  15647. return 0.5 * tmp1.length();
  15648. },
  15649. // Center geometry so that 0,0,0 is in center of bounding box
  15650. center: function ( geometry ) {
  15651. geometry.computeBoundingBox();
  15652. var bb = geometry.boundingBox;
  15653. var offset = new THREE.Vector3();
  15654. offset.addVectors( bb.min, bb.max );
  15655. offset.multiplyScalar( -0.5 );
  15656. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15657. geometry.computeBoundingBox();
  15658. return offset;
  15659. },
  15660. // Normalize UVs to be from <0,1>
  15661. // (for now just the first set of UVs)
  15662. normalizeUVs: function ( geometry ) {
  15663. var uvSet = geometry.faceVertexUvs[ 0 ];
  15664. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  15665. var uvs = uvSet[ i ];
  15666. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  15667. // texture repeat
  15668. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  15669. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  15670. }
  15671. }
  15672. },
  15673. triangulateQuads: function ( geometry ) {
  15674. var i, il, j, jl;
  15675. var faces = [];
  15676. var faceUvs = [];
  15677. var faceVertexUvs = [];
  15678. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  15679. faceUvs[ i ] = [];
  15680. }
  15681. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15682. faceVertexUvs[ i ] = [];
  15683. }
  15684. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15685. var face = geometry.faces[ i ];
  15686. if ( face instanceof THREE.Face4 ) {
  15687. var a = face.a;
  15688. var b = face.b;
  15689. var c = face.c;
  15690. var d = face.d;
  15691. var triA = new THREE.Face3();
  15692. var triB = new THREE.Face3();
  15693. triA.color.copy( face.color );
  15694. triB.color.copy( face.color );
  15695. triA.materialIndex = face.materialIndex;
  15696. triB.materialIndex = face.materialIndex;
  15697. triA.a = a;
  15698. triA.b = b;
  15699. triA.c = d;
  15700. triB.a = b;
  15701. triB.b = c;
  15702. triB.c = d;
  15703. if ( face.vertexColors.length === 4 ) {
  15704. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  15705. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  15706. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15707. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  15708. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  15709. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15710. }
  15711. faces.push( triA, triB );
  15712. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15713. if ( geometry.faceVertexUvs[ j ].length ) {
  15714. var uvs = geometry.faceVertexUvs[ j ][ i ];
  15715. var uvA = uvs[ 0 ];
  15716. var uvB = uvs[ 1 ];
  15717. var uvC = uvs[ 2 ];
  15718. var uvD = uvs[ 3 ];
  15719. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  15720. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  15721. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15722. }
  15723. }
  15724. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15725. if ( geometry.faceUvs[ j ].length ) {
  15726. var faceUv = geometry.faceUvs[ j ][ i ];
  15727. faceUvs[ j ].push( faceUv, faceUv );
  15728. }
  15729. }
  15730. } else {
  15731. faces.push( face );
  15732. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15733. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15734. }
  15735. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15736. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15737. }
  15738. }
  15739. }
  15740. geometry.faces = faces;
  15741. geometry.faceUvs = faceUvs;
  15742. geometry.faceVertexUvs = faceVertexUvs;
  15743. geometry.computeCentroids();
  15744. geometry.computeFaceNormals();
  15745. geometry.computeVertexNormals();
  15746. if ( geometry.hasTangents ) geometry.computeTangents();
  15747. },
  15748. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  15749. var faces = geometry.faces;
  15750. var start = startFace || 0;
  15751. var end = endFace || faces.length - 1;
  15752. for ( var i = start; i <= end; i ++ ) {
  15753. faces[i].materialIndex = index;
  15754. }
  15755. }
  15756. };
  15757. THREE.GeometryUtils.random = THREE.Math.random16;
  15758. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15759. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15760. /**
  15761. * @author alteredq / http://alteredqualia.com/
  15762. * @author mrdoob / http://mrdoob.com/
  15763. */
  15764. THREE.ImageUtils = {
  15765. crossOrigin: 'anonymous',
  15766. loadTexture: function ( url, mapping, onLoad, onError ) {
  15767. var image = new Image();
  15768. var texture = new THREE.Texture( image, mapping );
  15769. var loader = new THREE.ImageLoader();
  15770. loader.addEventListener( 'load', function ( event ) {
  15771. texture.image = event.content;
  15772. texture.needsUpdate = true;
  15773. if ( onLoad ) onLoad( texture );
  15774. } );
  15775. loader.addEventListener( 'error', function ( event ) {
  15776. if ( onError ) onError( event.message );
  15777. } );
  15778. loader.crossOrigin = this.crossOrigin;
  15779. loader.load( url, image );
  15780. texture.sourceFile = url;
  15781. return texture;
  15782. },
  15783. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15784. var texture = new THREE.CompressedTexture();
  15785. texture.mapping = mapping;
  15786. var request = new XMLHttpRequest();
  15787. request.onload = function () {
  15788. var buffer = request.response;
  15789. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15790. texture.format = dds.format;
  15791. texture.mipmaps = dds.mipmaps;
  15792. texture.image.width = dds.width;
  15793. texture.image.height = dds.height;
  15794. // gl.generateMipmap fails for compressed textures
  15795. // mipmaps must be embedded in the DDS file
  15796. // or texture filters must not use mipmapping
  15797. texture.generateMipmaps = false;
  15798. texture.needsUpdate = true;
  15799. if ( onLoad ) onLoad( texture );
  15800. }
  15801. request.onerror = onError;
  15802. request.open( 'GET', url, true );
  15803. request.responseType = "arraybuffer";
  15804. request.send( null );
  15805. return texture;
  15806. },
  15807. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15808. var images = [];
  15809. images.loadCount = 0;
  15810. var texture = new THREE.Texture();
  15811. texture.image = images;
  15812. if ( mapping !== undefined ) texture.mapping = mapping;
  15813. // no flipping needed for cube textures
  15814. texture.flipY = false;
  15815. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15816. var cubeImage = new Image();
  15817. images[ i ] = cubeImage;
  15818. cubeImage.onload = function () {
  15819. images.loadCount += 1;
  15820. if ( images.loadCount === 6 ) {
  15821. texture.needsUpdate = true;
  15822. if ( onLoad ) onLoad( texture );
  15823. }
  15824. };
  15825. cubeImage.onerror = onError;
  15826. cubeImage.crossOrigin = this.crossOrigin;
  15827. cubeImage.src = array[ i ];
  15828. }
  15829. return texture;
  15830. },
  15831. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15832. var images = [];
  15833. images.loadCount = 0;
  15834. var texture = new THREE.CompressedTexture();
  15835. texture.image = images;
  15836. if ( mapping !== undefined ) texture.mapping = mapping;
  15837. // no flipping for cube textures
  15838. // (also flipping doesn't work for compressed textures )
  15839. texture.flipY = false;
  15840. // can't generate mipmaps for compressed textures
  15841. // mips must be embedded in DDS files
  15842. texture.generateMipmaps = false;
  15843. var generateCubeFaceCallback = function ( rq, img ) {
  15844. return function () {
  15845. var buffer = rq.response;
  15846. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15847. img.format = dds.format;
  15848. img.mipmaps = dds.mipmaps;
  15849. img.width = dds.width;
  15850. img.height = dds.height;
  15851. images.loadCount += 1;
  15852. if ( images.loadCount === 6 ) {
  15853. texture.format = dds.format;
  15854. texture.needsUpdate = true;
  15855. if ( onLoad ) onLoad( texture );
  15856. }
  15857. }
  15858. }
  15859. // compressed cubemap textures as 6 separate DDS files
  15860. if ( array instanceof Array ) {
  15861. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15862. var cubeImage = {};
  15863. images[ i ] = cubeImage;
  15864. var request = new XMLHttpRequest();
  15865. request.onload = generateCubeFaceCallback( request, cubeImage );
  15866. request.onerror = onError;
  15867. var url = array[ i ];
  15868. request.open( 'GET', url, true );
  15869. request.responseType = "arraybuffer";
  15870. request.send( null );
  15871. }
  15872. // compressed cubemap texture stored in a single DDS file
  15873. } else {
  15874. var url = array;
  15875. var request = new XMLHttpRequest();
  15876. request.onload = function( ) {
  15877. var buffer = request.response;
  15878. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15879. if ( dds.isCubemap ) {
  15880. var faces = dds.mipmaps.length / dds.mipmapCount;
  15881. for ( var f = 0; f < faces; f ++ ) {
  15882. images[ f ] = { mipmaps : [] };
  15883. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15884. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15885. images[ f ].format = dds.format;
  15886. images[ f ].width = dds.width;
  15887. images[ f ].height = dds.height;
  15888. }
  15889. }
  15890. texture.format = dds.format;
  15891. texture.needsUpdate = true;
  15892. if ( onLoad ) onLoad( texture );
  15893. }
  15894. }
  15895. request.onerror = onError;
  15896. request.open( 'GET', url, true );
  15897. request.responseType = "arraybuffer";
  15898. request.send( null );
  15899. }
  15900. return texture;
  15901. },
  15902. parseDDS: function ( buffer, loadMipmaps ) {
  15903. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15904. // Adapted from @toji's DDS utils
  15905. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15906. // All values and structures referenced from:
  15907. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15908. var DDS_MAGIC = 0x20534444;
  15909. var DDSD_CAPS = 0x1,
  15910. DDSD_HEIGHT = 0x2,
  15911. DDSD_WIDTH = 0x4,
  15912. DDSD_PITCH = 0x8,
  15913. DDSD_PIXELFORMAT = 0x1000,
  15914. DDSD_MIPMAPCOUNT = 0x20000,
  15915. DDSD_LINEARSIZE = 0x80000,
  15916. DDSD_DEPTH = 0x800000;
  15917. var DDSCAPS_COMPLEX = 0x8,
  15918. DDSCAPS_MIPMAP = 0x400000,
  15919. DDSCAPS_TEXTURE = 0x1000;
  15920. var DDSCAPS2_CUBEMAP = 0x200,
  15921. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15922. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15923. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15924. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15925. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15926. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15927. DDSCAPS2_VOLUME = 0x200000;
  15928. var DDPF_ALPHAPIXELS = 0x1,
  15929. DDPF_ALPHA = 0x2,
  15930. DDPF_FOURCC = 0x4,
  15931. DDPF_RGB = 0x40,
  15932. DDPF_YUV = 0x200,
  15933. DDPF_LUMINANCE = 0x20000;
  15934. function fourCCToInt32( value ) {
  15935. return value.charCodeAt(0) +
  15936. (value.charCodeAt(1) << 8) +
  15937. (value.charCodeAt(2) << 16) +
  15938. (value.charCodeAt(3) << 24);
  15939. }
  15940. function int32ToFourCC( value ) {
  15941. return String.fromCharCode(
  15942. value & 0xff,
  15943. (value >> 8) & 0xff,
  15944. (value >> 16) & 0xff,
  15945. (value >> 24) & 0xff
  15946. );
  15947. }
  15948. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15949. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15950. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15951. var headerLengthInt = 31; // The header length in 32 bit ints
  15952. // Offsets into the header array
  15953. var off_magic = 0;
  15954. var off_size = 1;
  15955. var off_flags = 2;
  15956. var off_height = 3;
  15957. var off_width = 4;
  15958. var off_mipmapCount = 7;
  15959. var off_pfFlags = 20;
  15960. var off_pfFourCC = 21;
  15961. var off_caps = 27;
  15962. var off_caps2 = 28;
  15963. var off_caps3 = 29;
  15964. var off_caps4 = 30;
  15965. // Parse header
  15966. var header = new Int32Array( buffer, 0, headerLengthInt );
  15967. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15968. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15969. return dds;
  15970. }
  15971. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15972. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15973. return dds;
  15974. }
  15975. var blockBytes;
  15976. var fourCC = header[ off_pfFourCC ];
  15977. switch ( fourCC ) {
  15978. case FOURCC_DXT1:
  15979. blockBytes = 8;
  15980. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15981. break;
  15982. case FOURCC_DXT3:
  15983. blockBytes = 16;
  15984. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15985. break;
  15986. case FOURCC_DXT5:
  15987. blockBytes = 16;
  15988. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15989. break;
  15990. default:
  15991. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15992. return dds;
  15993. }
  15994. dds.mipmapCount = 1;
  15995. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15996. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15997. }
  15998. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15999. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16000. dds.width = header[ off_width ];
  16001. dds.height = header[ off_height ];
  16002. var dataOffset = header[ off_size ] + 4;
  16003. // Extract mipmaps buffers
  16004. var width = dds.width;
  16005. var height = dds.height;
  16006. var faces = dds.isCubemap ? 6 : 1;
  16007. for ( var face = 0; face < faces; face ++ ) {
  16008. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16009. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16010. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16011. var mipmap = { "data": byteArray, "width": width, "height": height };
  16012. dds.mipmaps.push( mipmap );
  16013. dataOffset += dataLength;
  16014. width = Math.max( width * 0.5, 1 );
  16015. height = Math.max( height * 0.5, 1 );
  16016. }
  16017. width = dds.width;
  16018. height = dds.height;
  16019. }
  16020. return dds;
  16021. },
  16022. getNormalMap: function ( image, depth ) {
  16023. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16024. var cross = function ( a, b ) {
  16025. 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 ] ];
  16026. }
  16027. var subtract = function ( a, b ) {
  16028. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16029. }
  16030. var normalize = function ( a ) {
  16031. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16032. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16033. }
  16034. depth = depth | 1;
  16035. var width = image.width;
  16036. var height = image.height;
  16037. var canvas = document.createElement( 'canvas' );
  16038. canvas.width = width;
  16039. canvas.height = height;
  16040. var context = canvas.getContext( '2d' );
  16041. context.drawImage( image, 0, 0 );
  16042. var data = context.getImageData( 0, 0, width, height ).data;
  16043. var imageData = context.createImageData( width, height );
  16044. var output = imageData.data;
  16045. for ( var x = 0; x < width; x ++ ) {
  16046. for ( var y = 0; y < height; y ++ ) {
  16047. var ly = y - 1 < 0 ? 0 : y - 1;
  16048. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16049. var lx = x - 1 < 0 ? 0 : x - 1;
  16050. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16051. var points = [];
  16052. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16053. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16054. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16055. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16056. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16057. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16058. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16059. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16060. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16061. var normals = [];
  16062. var num_points = points.length;
  16063. for ( var i = 0; i < num_points; i ++ ) {
  16064. var v1 = points[ i ];
  16065. var v2 = points[ ( i + 1 ) % num_points ];
  16066. v1 = subtract( v1, origin );
  16067. v2 = subtract( v2, origin );
  16068. normals.push( normalize( cross( v1, v2 ) ) );
  16069. }
  16070. var normal = [ 0, 0, 0 ];
  16071. for ( var i = 0; i < normals.length; i ++ ) {
  16072. normal[ 0 ] += normals[ i ][ 0 ];
  16073. normal[ 1 ] += normals[ i ][ 1 ];
  16074. normal[ 2 ] += normals[ i ][ 2 ];
  16075. }
  16076. normal[ 0 ] /= normals.length;
  16077. normal[ 1 ] /= normals.length;
  16078. normal[ 2 ] /= normals.length;
  16079. var idx = ( y * width + x ) * 4;
  16080. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16081. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16082. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16083. output[ idx + 3 ] = 255;
  16084. }
  16085. }
  16086. context.putImageData( imageData, 0, 0 );
  16087. return canvas;
  16088. },
  16089. generateDataTexture: function ( width, height, color ) {
  16090. var size = width * height;
  16091. var data = new Uint8Array( 3 * size );
  16092. var r = Math.floor( color.r * 255 );
  16093. var g = Math.floor( color.g * 255 );
  16094. var b = Math.floor( color.b * 255 );
  16095. for ( var i = 0; i < size; i ++ ) {
  16096. data[ i * 3 ] = r;
  16097. data[ i * 3 + 1 ] = g;
  16098. data[ i * 3 + 2 ] = b;
  16099. }
  16100. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16101. texture.needsUpdate = true;
  16102. return texture;
  16103. }
  16104. };
  16105. /**
  16106. * @author alteredq / http://alteredqualia.com/
  16107. */
  16108. THREE.SceneUtils = {
  16109. createMultiMaterialObject: function ( geometry, materials ) {
  16110. var group = new THREE.Object3D();
  16111. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16112. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16113. }
  16114. return group;
  16115. },
  16116. detach : function ( child, parent, scene ) {
  16117. child.applyMatrix( parent.matrixWorld );
  16118. parent.remove( child );
  16119. scene.add( child );
  16120. },
  16121. attach: function ( child, scene, parent ) {
  16122. var matrixWorldInverse = new THREE.Matrix4();
  16123. matrixWorldInverse.getInverse( parent.matrixWorld );
  16124. child.applyMatrix( matrixWorldInverse );
  16125. scene.remove( child );
  16126. parent.add( child );
  16127. }
  16128. };
  16129. /**
  16130. * @author zz85 / http://www.lab4games.net/zz85/blog
  16131. * @author alteredq / http://alteredqualia.com/
  16132. *
  16133. * For Text operations in three.js (See TextGeometry)
  16134. *
  16135. * It uses techniques used in:
  16136. *
  16137. * typeface.js and canvastext
  16138. * For converting fonts and rendering with javascript
  16139. * http://typeface.neocracy.org
  16140. *
  16141. * Triangulation ported from AS3
  16142. * Simple Polygon Triangulation
  16143. * http://actionsnippet.com/?p=1462
  16144. *
  16145. * A Method to triangulate shapes with holes
  16146. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16147. *
  16148. */
  16149. THREE.FontUtils = {
  16150. faces : {},
  16151. // Just for now. face[weight][style]
  16152. face : "helvetiker",
  16153. weight: "normal",
  16154. style : "normal",
  16155. size : 150,
  16156. divisions : 10,
  16157. getFace : function() {
  16158. return this.faces[ this.face ][ this.weight ][ this.style ];
  16159. },
  16160. loadFace : function( data ) {
  16161. var family = data.familyName.toLowerCase();
  16162. var ThreeFont = this;
  16163. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16164. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16165. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16166. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16167. return data;
  16168. },
  16169. drawText : function( text ) {
  16170. var characterPts = [], allPts = [];
  16171. // RenderText
  16172. var i, p,
  16173. face = this.getFace(),
  16174. scale = this.size / face.resolution,
  16175. offset = 0,
  16176. chars = String( text ).split( '' ),
  16177. length = chars.length;
  16178. var fontPaths = [];
  16179. for ( i = 0; i < length; i ++ ) {
  16180. var path = new THREE.Path();
  16181. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16182. offset += ret.offset;
  16183. fontPaths.push( ret.path );
  16184. }
  16185. // get the width
  16186. var width = offset / 2;
  16187. //
  16188. // for ( p = 0; p < allPts.length; p++ ) {
  16189. //
  16190. // allPts[ p ].x -= width;
  16191. //
  16192. // }
  16193. //var extract = this.extractPoints( allPts, characterPts );
  16194. //extract.contour = allPts;
  16195. //extract.paths = fontPaths;
  16196. //extract.offset = width;
  16197. return { paths : fontPaths, offset : width };
  16198. },
  16199. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16200. var pts = [];
  16201. var i, i2, divisions,
  16202. outline, action, length,
  16203. scaleX, scaleY,
  16204. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16205. laste,
  16206. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16207. if ( !glyph ) return;
  16208. if ( glyph.o ) {
  16209. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16210. length = outline.length;
  16211. scaleX = scale;
  16212. scaleY = scale;
  16213. for ( i = 0; i < length; ) {
  16214. action = outline[ i ++ ];
  16215. //console.log( action );
  16216. switch( action ) {
  16217. case 'm':
  16218. // Move To
  16219. x = outline[ i++ ] * scaleX + offset;
  16220. y = outline[ i++ ] * scaleY;
  16221. path.moveTo( x, y );
  16222. break;
  16223. case 'l':
  16224. // Line To
  16225. x = outline[ i++ ] * scaleX + offset;
  16226. y = outline[ i++ ] * scaleY;
  16227. path.lineTo(x,y);
  16228. break;
  16229. case 'q':
  16230. // QuadraticCurveTo
  16231. cpx = outline[ i++ ] * scaleX + offset;
  16232. cpy = outline[ i++ ] * scaleY;
  16233. cpx1 = outline[ i++ ] * scaleX + offset;
  16234. cpy1 = outline[ i++ ] * scaleY;
  16235. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16236. laste = pts[ pts.length - 1 ];
  16237. if ( laste ) {
  16238. cpx0 = laste.x;
  16239. cpy0 = laste.y;
  16240. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16241. var t = i2 / divisions;
  16242. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16243. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16244. }
  16245. }
  16246. break;
  16247. case 'b':
  16248. // Cubic Bezier Curve
  16249. cpx = outline[ i++ ] * scaleX + offset;
  16250. cpy = outline[ i++ ] * scaleY;
  16251. cpx1 = outline[ i++ ] * scaleX + offset;
  16252. cpy1 = outline[ i++ ] * -scaleY;
  16253. cpx2 = outline[ i++ ] * scaleX + offset;
  16254. cpy2 = outline[ i++ ] * -scaleY;
  16255. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16256. laste = pts[ pts.length - 1 ];
  16257. if ( laste ) {
  16258. cpx0 = laste.x;
  16259. cpy0 = laste.y;
  16260. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16261. var t = i2 / divisions;
  16262. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16263. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16264. }
  16265. }
  16266. break;
  16267. }
  16268. }
  16269. }
  16270. return { offset: glyph.ha*scale, path:path};
  16271. }
  16272. };
  16273. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16274. // Parameters
  16275. parameters = parameters || {};
  16276. var size = parameters.size !== undefined ? parameters.size : 100;
  16277. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16278. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16279. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16280. var style = parameters.style !== undefined ? parameters.style : "normal";
  16281. THREE.FontUtils.size = size;
  16282. THREE.FontUtils.divisions = curveSegments;
  16283. THREE.FontUtils.face = font;
  16284. THREE.FontUtils.weight = weight;
  16285. THREE.FontUtils.style = style;
  16286. // Get a Font data json object
  16287. var data = THREE.FontUtils.drawText( text );
  16288. var paths = data.paths;
  16289. var shapes = [];
  16290. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16291. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16292. }
  16293. return shapes;
  16294. };
  16295. /**
  16296. * This code is a quick port of code written in C++ which was submitted to
  16297. * flipcode.com by John W. Ratcliff // July 22, 2000
  16298. * See original code and more information here:
  16299. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16300. *
  16301. * ported to actionscript by Zevan Rosser
  16302. * www.actionsnippet.com
  16303. *
  16304. * ported to javascript by Joshua Koo
  16305. * http://www.lab4games.net/zz85/blog
  16306. *
  16307. */
  16308. ( function( namespace ) {
  16309. var EPSILON = 0.0000000001;
  16310. // takes in an contour array and returns
  16311. var process = function( contour, indices ) {
  16312. var n = contour.length;
  16313. if ( n < 3 ) return null;
  16314. var result = [],
  16315. verts = [],
  16316. vertIndices = [];
  16317. /* we want a counter-clockwise polygon in verts */
  16318. var u, v, w;
  16319. if ( area( contour ) > 0.0 ) {
  16320. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16321. } else {
  16322. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16323. }
  16324. var nv = n;
  16325. /* remove nv - 2 vertices, creating 1 triangle every time */
  16326. var count = 2 * nv; /* error detection */
  16327. for( v = nv - 1; nv > 2; ) {
  16328. /* if we loop, it is probably a non-simple polygon */
  16329. if ( ( count-- ) <= 0 ) {
  16330. //** Triangulate: ERROR - probable bad polygon!
  16331. //throw ( "Warning, unable to triangulate polygon!" );
  16332. //return null;
  16333. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16334. console.log( "Warning, unable to triangulate polygon!" );
  16335. if ( indices ) return vertIndices;
  16336. return result;
  16337. }
  16338. /* three consecutive vertices in current polygon, <u,v,w> */
  16339. u = v; if ( nv <= u ) u = 0; /* previous */
  16340. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16341. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16342. if ( snip( contour, u, v, w, nv, verts ) ) {
  16343. var a, b, c, s, t;
  16344. /* true names of the vertices */
  16345. a = verts[ u ];
  16346. b = verts[ v ];
  16347. c = verts[ w ];
  16348. /* output Triangle */
  16349. result.push( [ contour[ a ],
  16350. contour[ b ],
  16351. contour[ c ] ] );
  16352. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16353. /* remove v from the remaining polygon */
  16354. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16355. verts[ s ] = verts[ t ];
  16356. }
  16357. nv--;
  16358. /* reset error detection counter */
  16359. count = 2 * nv;
  16360. }
  16361. }
  16362. if ( indices ) return vertIndices;
  16363. return result;
  16364. };
  16365. // calculate area of the contour polygon
  16366. var area = function ( contour ) {
  16367. var n = contour.length;
  16368. var a = 0.0;
  16369. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16370. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16371. }
  16372. return a * 0.5;
  16373. };
  16374. var snip = function ( contour, u, v, w, n, verts ) {
  16375. var p;
  16376. var ax, ay, bx, by;
  16377. var cx, cy, px, py;
  16378. ax = contour[ verts[ u ] ].x;
  16379. ay = contour[ verts[ u ] ].y;
  16380. bx = contour[ verts[ v ] ].x;
  16381. by = contour[ verts[ v ] ].y;
  16382. cx = contour[ verts[ w ] ].x;
  16383. cy = contour[ verts[ w ] ].y;
  16384. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16385. var aX, aY, bX, bY, cX, cY;
  16386. var apx, apy, bpx, bpy, cpx, cpy;
  16387. var cCROSSap, bCROSScp, aCROSSbp;
  16388. aX = cx - bx; aY = cy - by;
  16389. bX = ax - cx; bY = ay - cy;
  16390. cX = bx - ax; cY = by - ay;
  16391. for ( p = 0; p < n; p++ ) {
  16392. if( (p === u) || (p === v) || (p === w) ) continue;
  16393. px = contour[ verts[ p ] ].x
  16394. py = contour[ verts[ p ] ].y
  16395. apx = px - ax; apy = py - ay;
  16396. bpx = px - bx; bpy = py - by;
  16397. cpx = px - cx; cpy = py - cy;
  16398. // see if p is inside triangle abc
  16399. aCROSSbp = aX*bpy - aY*bpx;
  16400. cCROSSap = cX*apy - cY*apx;
  16401. bCROSScp = bX*cpy - bY*cpx;
  16402. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16403. }
  16404. return true;
  16405. };
  16406. namespace.Triangulate = process;
  16407. namespace.Triangulate.area = area;
  16408. return namespace;
  16409. })(THREE.FontUtils);
  16410. // To use the typeface.js face files, hook up the API
  16411. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16412. THREE.typeface_js = self._typeface_js;
  16413. /**
  16414. * @author zz85 / http://www.lab4games.net/zz85/blog
  16415. * Extensible curve object
  16416. *
  16417. * Some common of Curve methods
  16418. * .getPoint(t), getTangent(t)
  16419. * .getPointAt(u), getTagentAt(u)
  16420. * .getPoints(), .getSpacedPoints()
  16421. * .getLength()
  16422. * .updateArcLengths()
  16423. *
  16424. * This file contains following classes:
  16425. *
  16426. * -- 2d classes --
  16427. * THREE.Curve
  16428. * THREE.LineCurve
  16429. * THREE.QuadraticBezierCurve
  16430. * THREE.CubicBezierCurve
  16431. * THREE.SplineCurve
  16432. * THREE.ArcCurve
  16433. * THREE.EllipseCurve
  16434. *
  16435. * -- 3d classes --
  16436. * THREE.LineCurve3
  16437. * THREE.QuadraticBezierCurve3
  16438. * THREE.CubicBezierCurve3
  16439. * THREE.SplineCurve3
  16440. * THREE.ClosedSplineCurve3
  16441. *
  16442. * A series of curves can be represented as a THREE.CurvePath
  16443. *
  16444. **/
  16445. /**************************************************************
  16446. * Abstract Curve base class
  16447. **************************************************************/
  16448. THREE.Curve = function () {
  16449. };
  16450. // Virtual base class method to overwrite and implement in subclasses
  16451. // - t [0 .. 1]
  16452. THREE.Curve.prototype.getPoint = function ( t ) {
  16453. console.log( "Warning, getPoint() not implemented!" );
  16454. return null;
  16455. };
  16456. // Get point at relative position in curve according to arc length
  16457. // - u [0 .. 1]
  16458. THREE.Curve.prototype.getPointAt = function ( u ) {
  16459. var t = this.getUtoTmapping( u );
  16460. return this.getPoint( t );
  16461. };
  16462. // Get sequence of points using getPoint( t )
  16463. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16464. if ( !divisions ) divisions = 5;
  16465. var d, pts = [];
  16466. for ( d = 0; d <= divisions; d ++ ) {
  16467. pts.push( this.getPoint( d / divisions ) );
  16468. }
  16469. return pts;
  16470. };
  16471. // Get sequence of points using getPointAt( u )
  16472. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16473. if ( !divisions ) divisions = 5;
  16474. var d, pts = [];
  16475. for ( d = 0; d <= divisions; d ++ ) {
  16476. pts.push( this.getPointAt( d / divisions ) );
  16477. }
  16478. return pts;
  16479. };
  16480. // Get total curve arc length
  16481. THREE.Curve.prototype.getLength = function () {
  16482. var lengths = this.getLengths();
  16483. return lengths[ lengths.length - 1 ];
  16484. };
  16485. // Get list of cumulative segment lengths
  16486. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16487. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16488. if ( this.cacheArcLengths
  16489. && ( this.cacheArcLengths.length == divisions + 1 )
  16490. && !this.needsUpdate) {
  16491. //console.log( "cached", this.cacheArcLengths );
  16492. return this.cacheArcLengths;
  16493. }
  16494. this.needsUpdate = false;
  16495. var cache = [];
  16496. var current, last = this.getPoint( 0 );
  16497. var p, sum = 0;
  16498. cache.push( 0 );
  16499. for ( p = 1; p <= divisions; p ++ ) {
  16500. current = this.getPoint ( p / divisions );
  16501. sum += current.distanceTo( last );
  16502. cache.push( sum );
  16503. last = current;
  16504. }
  16505. this.cacheArcLengths = cache;
  16506. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16507. };
  16508. THREE.Curve.prototype.updateArcLengths = function() {
  16509. this.needsUpdate = true;
  16510. this.getLengths();
  16511. };
  16512. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16513. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16514. var arcLengths = this.getLengths();
  16515. var i = 0, il = arcLengths.length;
  16516. var targetArcLength; // The targeted u distance value to get
  16517. if ( distance ) {
  16518. targetArcLength = distance;
  16519. } else {
  16520. targetArcLength = u * arcLengths[ il - 1 ];
  16521. }
  16522. //var time = Date.now();
  16523. // binary search for the index with largest value smaller than target u distance
  16524. var low = 0, high = il - 1, comparison;
  16525. while ( low <= high ) {
  16526. 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
  16527. comparison = arcLengths[ i ] - targetArcLength;
  16528. if ( comparison < 0 ) {
  16529. low = i + 1;
  16530. continue;
  16531. } else if ( comparison > 0 ) {
  16532. high = i - 1;
  16533. continue;
  16534. } else {
  16535. high = i;
  16536. break;
  16537. // DONE
  16538. }
  16539. }
  16540. i = high;
  16541. //console.log('b' , i, low, high, Date.now()- time);
  16542. if ( arcLengths[ i ] == targetArcLength ) {
  16543. var t = i / ( il - 1 );
  16544. return t;
  16545. }
  16546. // we could get finer grain at lengths, or use simple interpolatation between two points
  16547. var lengthBefore = arcLengths[ i ];
  16548. var lengthAfter = arcLengths[ i + 1 ];
  16549. var segmentLength = lengthAfter - lengthBefore;
  16550. // determine where we are between the 'before' and 'after' points
  16551. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16552. // add that fractional amount to t
  16553. var t = ( i + segmentFraction ) / ( il -1 );
  16554. return t;
  16555. };
  16556. // Returns a unit vector tangent at t
  16557. // In case any sub curve does not implement its tangent derivation,
  16558. // 2 points a small delta apart will be used to find its gradient
  16559. // which seems to give a reasonable approximation
  16560. THREE.Curve.prototype.getTangent = function( t ) {
  16561. var delta = 0.0001;
  16562. var t1 = t - delta;
  16563. var t2 = t + delta;
  16564. // Capping in case of danger
  16565. if ( t1 < 0 ) t1 = 0;
  16566. if ( t2 > 1 ) t2 = 1;
  16567. var pt1 = this.getPoint( t1 );
  16568. var pt2 = this.getPoint( t2 );
  16569. var vec = pt2.clone().sub(pt1);
  16570. return vec.normalize();
  16571. };
  16572. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16573. var t = this.getUtoTmapping( u );
  16574. return this.getTangent( t );
  16575. };
  16576. /**************************************************************
  16577. * Line
  16578. **************************************************************/
  16579. THREE.LineCurve = function ( v1, v2 ) {
  16580. this.v1 = v1;
  16581. this.v2 = v2;
  16582. };
  16583. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16584. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16585. var point = this.v2.clone().sub(this.v1);
  16586. point.multiplyScalar( t ).add( this.v1 );
  16587. return point;
  16588. };
  16589. // Line curve is linear, so we can overwrite default getPointAt
  16590. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16591. return this.getPoint( u );
  16592. };
  16593. THREE.LineCurve.prototype.getTangent = function( t ) {
  16594. var tangent = this.v2.clone().sub(this.v1);
  16595. return tangent.normalize();
  16596. };
  16597. /**************************************************************
  16598. * Quadratic Bezier curve
  16599. **************************************************************/
  16600. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16601. this.v0 = v0;
  16602. this.v1 = v1;
  16603. this.v2 = v2;
  16604. };
  16605. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16606. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16607. var tx, ty;
  16608. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16609. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16610. return new THREE.Vector2( tx, ty );
  16611. };
  16612. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16613. var tx, ty;
  16614. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16615. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16616. // returns unit vector
  16617. var tangent = new THREE.Vector2( tx, ty );
  16618. tangent.normalize();
  16619. return tangent;
  16620. };
  16621. /**************************************************************
  16622. * Cubic Bezier curve
  16623. **************************************************************/
  16624. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16625. this.v0 = v0;
  16626. this.v1 = v1;
  16627. this.v2 = v2;
  16628. this.v3 = v3;
  16629. };
  16630. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16631. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16632. var tx, ty;
  16633. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16634. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16635. return new THREE.Vector2( tx, ty );
  16636. };
  16637. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16638. var tx, ty;
  16639. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16640. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16641. var tangent = new THREE.Vector2( tx, ty );
  16642. tangent.normalize();
  16643. return tangent;
  16644. };
  16645. /**************************************************************
  16646. * Spline curve
  16647. **************************************************************/
  16648. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16649. this.points = (points == undefined) ? [] : points;
  16650. };
  16651. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16652. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16653. var v = new THREE.Vector2();
  16654. var c = [];
  16655. var points = this.points, point, intPoint, weight;
  16656. point = ( points.length - 1 ) * t;
  16657. intPoint = Math.floor( point );
  16658. weight = point - intPoint;
  16659. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16660. c[ 1 ] = intPoint;
  16661. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16662. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16663. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16664. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16665. return v;
  16666. };
  16667. /**************************************************************
  16668. * Ellipse curve
  16669. **************************************************************/
  16670. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16671. aStartAngle, aEndAngle,
  16672. aClockwise ) {
  16673. this.aX = aX;
  16674. this.aY = aY;
  16675. this.xRadius = xRadius;
  16676. this.yRadius = yRadius;
  16677. this.aStartAngle = aStartAngle;
  16678. this.aEndAngle = aEndAngle;
  16679. this.aClockwise = aClockwise;
  16680. };
  16681. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16682. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16683. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16684. if ( !this.aClockwise ) {
  16685. t = 1 - t;
  16686. }
  16687. var angle = this.aStartAngle + t * deltaAngle;
  16688. var tx = this.aX + this.xRadius * Math.cos( angle );
  16689. var ty = this.aY + this.yRadius * Math.sin( angle );
  16690. return new THREE.Vector2( tx, ty );
  16691. };
  16692. /**************************************************************
  16693. * Arc curve
  16694. **************************************************************/
  16695. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16696. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16697. };
  16698. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16699. /**************************************************************
  16700. * Utils
  16701. **************************************************************/
  16702. THREE.Curve.Utils = {
  16703. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16704. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16705. },
  16706. // Puay Bing, thanks for helping with this derivative!
  16707. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16708. return -3 * p0 * (1 - t) * (1 - t) +
  16709. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16710. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16711. 3 * t * t * p3;
  16712. },
  16713. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16714. // To check if my formulas are correct
  16715. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16716. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16717. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16718. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16719. return h00 + h10 + h01 + h11;
  16720. },
  16721. // Catmull-Rom
  16722. interpolate: function( p0, p1, p2, p3, t ) {
  16723. var v0 = ( p2 - p0 ) * 0.5;
  16724. var v1 = ( p3 - p1 ) * 0.5;
  16725. var t2 = t * t;
  16726. var t3 = t * t2;
  16727. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16728. }
  16729. };
  16730. // TODO: Transformation for Curves?
  16731. /**************************************************************
  16732. * 3D Curves
  16733. **************************************************************/
  16734. // A Factory method for creating new curve subclasses
  16735. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16736. constructor.prototype = Object.create( THREE.Curve.prototype );
  16737. constructor.prototype.getPoint = getPointFunc;
  16738. return constructor;
  16739. };
  16740. /**************************************************************
  16741. * Line3D
  16742. **************************************************************/
  16743. THREE.LineCurve3 = THREE.Curve.create(
  16744. function ( v1, v2 ) {
  16745. this.v1 = v1;
  16746. this.v2 = v2;
  16747. },
  16748. function ( t ) {
  16749. var r = new THREE.Vector3();
  16750. r.subVectors( this.v2, this.v1 ); // diff
  16751. r.multiplyScalar( t );
  16752. r.add( this.v1 );
  16753. return r;
  16754. }
  16755. );
  16756. /**************************************************************
  16757. * Quadratic Bezier 3D curve
  16758. **************************************************************/
  16759. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16760. function ( v0, v1, v2 ) {
  16761. this.v0 = v0;
  16762. this.v1 = v1;
  16763. this.v2 = v2;
  16764. },
  16765. function ( t ) {
  16766. var tx, ty, tz;
  16767. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16768. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16769. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16770. return new THREE.Vector3( tx, ty, tz );
  16771. }
  16772. );
  16773. /**************************************************************
  16774. * Cubic Bezier 3D curve
  16775. **************************************************************/
  16776. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16777. function ( v0, v1, v2, v3 ) {
  16778. this.v0 = v0;
  16779. this.v1 = v1;
  16780. this.v2 = v2;
  16781. this.v3 = v3;
  16782. },
  16783. function ( t ) {
  16784. var tx, ty, tz;
  16785. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16786. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16787. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16788. return new THREE.Vector3( tx, ty, tz );
  16789. }
  16790. );
  16791. /**************************************************************
  16792. * Spline 3D curve
  16793. **************************************************************/
  16794. THREE.SplineCurve3 = THREE.Curve.create(
  16795. function ( points /* array of Vector3 */) {
  16796. this.points = (points == undefined) ? [] : points;
  16797. },
  16798. function ( t ) {
  16799. var v = new THREE.Vector3();
  16800. var c = [];
  16801. var points = this.points, point, intPoint, weight;
  16802. point = ( points.length - 1 ) * t;
  16803. intPoint = Math.floor( point );
  16804. weight = point - intPoint;
  16805. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16806. c[ 1 ] = intPoint;
  16807. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16808. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16809. var pt0 = points[ c[0] ],
  16810. pt1 = points[ c[1] ],
  16811. pt2 = points[ c[2] ],
  16812. pt3 = points[ c[3] ];
  16813. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16814. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16815. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16816. return v;
  16817. }
  16818. );
  16819. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16820. // var v = new THREE.Vector3();
  16821. // var c = [];
  16822. // var points = this.points, point, intPoint, weight;
  16823. // point = ( points.length - 1 ) * t;
  16824. // intPoint = Math.floor( point );
  16825. // weight = point - intPoint;
  16826. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16827. // c[ 1 ] = intPoint;
  16828. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16829. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16830. // var pt0 = points[ c[0] ],
  16831. // pt1 = points[ c[1] ],
  16832. // pt2 = points[ c[2] ],
  16833. // pt3 = points[ c[3] ];
  16834. // // t = weight;
  16835. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16836. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16837. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16838. // return v;
  16839. // }
  16840. /**************************************************************
  16841. * Closed Spline 3D curve
  16842. **************************************************************/
  16843. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16844. function ( points /* array of Vector3 */) {
  16845. this.points = (points == undefined) ? [] : points;
  16846. },
  16847. function ( t ) {
  16848. var v = new THREE.Vector3();
  16849. var c = [];
  16850. var points = this.points, point, intPoint, weight;
  16851. point = ( points.length - 0 ) * t;
  16852. // This needs to be from 0-length +1
  16853. intPoint = Math.floor( point );
  16854. weight = point - intPoint;
  16855. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16856. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16857. c[ 1 ] = ( intPoint ) % points.length;
  16858. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16859. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16860. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16861. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16862. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16863. return v;
  16864. }
  16865. );
  16866. /**
  16867. * @author zz85 / http://www.lab4games.net/zz85/blog
  16868. *
  16869. **/
  16870. /**************************************************************
  16871. * Curved Path - a curve path is simply a array of connected
  16872. * curves, but retains the api of a curve
  16873. **************************************************************/
  16874. THREE.CurvePath = function () {
  16875. this.curves = [];
  16876. this.bends = [];
  16877. this.autoClose = false; // Automatically closes the path
  16878. };
  16879. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16880. THREE.CurvePath.prototype.add = function ( curve ) {
  16881. this.curves.push( curve );
  16882. };
  16883. THREE.CurvePath.prototype.checkConnection = function() {
  16884. // TODO
  16885. // If the ending of curve is not connected to the starting
  16886. // or the next curve, then, this is not a real path
  16887. };
  16888. THREE.CurvePath.prototype.closePath = function() {
  16889. // TODO Test
  16890. // and verify for vector3 (needs to implement equals)
  16891. // Add a line curve if start and end of lines are not connected
  16892. var startPoint = this.curves[0].getPoint(0);
  16893. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16894. if (!startPoint.equals(endPoint)) {
  16895. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16896. }
  16897. };
  16898. // To get accurate point with reference to
  16899. // entire path distance at time t,
  16900. // following has to be done:
  16901. // 1. Length of each sub path have to be known
  16902. // 2. Locate and identify type of curve
  16903. // 3. Get t for the curve
  16904. // 4. Return curve.getPointAt(t')
  16905. THREE.CurvePath.prototype.getPoint = function( t ) {
  16906. var d = t * this.getLength();
  16907. var curveLengths = this.getCurveLengths();
  16908. var i = 0, diff, curve;
  16909. // To think about boundaries points.
  16910. while ( i < curveLengths.length ) {
  16911. if ( curveLengths[ i ] >= d ) {
  16912. diff = curveLengths[ i ] - d;
  16913. curve = this.curves[ i ];
  16914. var u = 1 - diff / curve.getLength();
  16915. return curve.getPointAt( u );
  16916. break;
  16917. }
  16918. i ++;
  16919. }
  16920. return null;
  16921. // loop where sum != 0, sum > d , sum+1 <d
  16922. };
  16923. /*
  16924. THREE.CurvePath.prototype.getTangent = function( t ) {
  16925. };*/
  16926. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16927. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16928. // getPoint() depends on getLength
  16929. THREE.CurvePath.prototype.getLength = function() {
  16930. var lens = this.getCurveLengths();
  16931. return lens[ lens.length - 1 ];
  16932. };
  16933. // Compute lengths and cache them
  16934. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16935. THREE.CurvePath.prototype.getCurveLengths = function() {
  16936. // We use cache values if curves and cache array are same length
  16937. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16938. return this.cacheLengths;
  16939. };
  16940. // Get length of subsurve
  16941. // Push sums into cached array
  16942. var lengths = [], sums = 0;
  16943. var i, il = this.curves.length;
  16944. for ( i = 0; i < il; i ++ ) {
  16945. sums += this.curves[ i ].getLength();
  16946. lengths.push( sums );
  16947. }
  16948. this.cacheLengths = lengths;
  16949. return lengths;
  16950. };
  16951. // Returns min and max coordinates, as well as centroid
  16952. THREE.CurvePath.prototype.getBoundingBox = function () {
  16953. var points = this.getPoints();
  16954. var maxX, maxY, maxZ;
  16955. var minX, minY, minZ;
  16956. maxX = maxY = Number.NEGATIVE_INFINITY;
  16957. minX = minY = Number.POSITIVE_INFINITY;
  16958. var p, i, il, sum;
  16959. var v3 = points[0] instanceof THREE.Vector3;
  16960. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16961. for ( i = 0, il = points.length; i < il; i ++ ) {
  16962. p = points[ i ];
  16963. if ( p.x > maxX ) maxX = p.x;
  16964. else if ( p.x < minX ) minX = p.x;
  16965. if ( p.y > maxY ) maxY = p.y;
  16966. else if ( p.y < minY ) minY = p.y;
  16967. if ( v3 ) {
  16968. if ( p.z > maxZ ) maxZ = p.z;
  16969. else if ( p.z < minZ ) minZ = p.z;
  16970. }
  16971. sum.add( p );
  16972. }
  16973. var ret = {
  16974. minX: minX,
  16975. minY: minY,
  16976. maxX: maxX,
  16977. maxY: maxY,
  16978. centroid: sum.divideScalar( il )
  16979. };
  16980. if ( v3 ) {
  16981. ret.maxZ = maxZ;
  16982. ret.minZ = minZ;
  16983. }
  16984. return ret;
  16985. };
  16986. /**************************************************************
  16987. * Create Geometries Helpers
  16988. **************************************************************/
  16989. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16990. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16991. var pts = this.getPoints( divisions, true );
  16992. return this.createGeometry( pts );
  16993. };
  16994. // Generate geometry from equidistance sampling along the path
  16995. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16996. var pts = this.getSpacedPoints( divisions, true );
  16997. return this.createGeometry( pts );
  16998. };
  16999. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17000. var geometry = new THREE.Geometry();
  17001. for ( var i = 0; i < points.length; i ++ ) {
  17002. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17003. }
  17004. return geometry;
  17005. };
  17006. /**************************************************************
  17007. * Bend / Wrap Helper Methods
  17008. **************************************************************/
  17009. // Wrap path / Bend modifiers?
  17010. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17011. this.bends.push( bendpath );
  17012. };
  17013. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17014. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17015. var i, il;
  17016. if ( !bends ) {
  17017. bends = this.bends;
  17018. }
  17019. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17020. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17021. }
  17022. return oldPts;
  17023. };
  17024. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17025. var oldPts = this.getSpacedPoints( segments );
  17026. var i, il;
  17027. if ( !bends ) {
  17028. bends = this.bends;
  17029. }
  17030. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17031. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17032. }
  17033. return oldPts;
  17034. };
  17035. // This returns getPoints() bend/wrapped around the contour of a path.
  17036. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17037. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17038. var bounds = this.getBoundingBox();
  17039. var i, il, p, oldX, oldY, xNorm;
  17040. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17041. p = oldPts[ i ];
  17042. oldX = p.x;
  17043. oldY = p.y;
  17044. xNorm = oldX / bounds.maxX;
  17045. // If using actual distance, for length > path, requires line extrusions
  17046. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17047. xNorm = path.getUtoTmapping( xNorm, oldX );
  17048. // check for out of bounds?
  17049. var pathPt = path.getPoint( xNorm );
  17050. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  17051. p.x = pathPt.x + normal.x;
  17052. p.y = pathPt.y + normal.y;
  17053. }
  17054. return oldPts;
  17055. };
  17056. /**
  17057. * @author alteredq / http://alteredqualia.com/
  17058. */
  17059. THREE.Gyroscope = function () {
  17060. THREE.Object3D.call( this );
  17061. };
  17062. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17063. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17064. this.matrixAutoUpdate && this.updateMatrix();
  17065. // update matrixWorld
  17066. if ( this.matrixWorldNeedsUpdate || force ) {
  17067. if ( this.parent ) {
  17068. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17069. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  17070. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  17071. this.matrixWorld.makeFromPositionQuaternionScale( this.translationWorld, this.rotationObject, this.scaleWorld );
  17072. } else {
  17073. this.matrixWorld.copy( this.matrix );
  17074. }
  17075. this.matrixWorldNeedsUpdate = false;
  17076. force = true;
  17077. }
  17078. // update children
  17079. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17080. this.children[ i ].updateMatrixWorld( force );
  17081. }
  17082. };
  17083. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17084. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17085. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  17086. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  17087. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17088. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17089. /**
  17090. * @author zz85 / http://www.lab4games.net/zz85/blog
  17091. * Creates free form 2d path using series of points, lines or curves.
  17092. *
  17093. **/
  17094. THREE.Path = function ( points ) {
  17095. THREE.CurvePath.call(this);
  17096. this.actions = [];
  17097. if ( points ) {
  17098. this.fromPoints( points );
  17099. }
  17100. };
  17101. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17102. THREE.PathActions = {
  17103. MOVE_TO: 'moveTo',
  17104. LINE_TO: 'lineTo',
  17105. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17106. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17107. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17108. ARC: 'arc', // Circle
  17109. ELLIPSE: 'ellipse'
  17110. };
  17111. // TODO Clean up PATH API
  17112. // Create path using straight lines to connect all points
  17113. // - vectors: array of Vector2
  17114. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17115. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17116. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17117. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17118. };
  17119. };
  17120. // startPath() endPath()?
  17121. THREE.Path.prototype.moveTo = function ( x, y ) {
  17122. var args = Array.prototype.slice.call( arguments );
  17123. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17124. };
  17125. THREE.Path.prototype.lineTo = function ( x, y ) {
  17126. var args = Array.prototype.slice.call( arguments );
  17127. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17128. var x0 = lastargs[ lastargs.length - 2 ];
  17129. var y0 = lastargs[ lastargs.length - 1 ];
  17130. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17131. this.curves.push( curve );
  17132. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17133. };
  17134. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17135. var args = Array.prototype.slice.call( arguments );
  17136. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17137. var x0 = lastargs[ lastargs.length - 2 ];
  17138. var y0 = lastargs[ lastargs.length - 1 ];
  17139. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17140. new THREE.Vector2( aCPx, aCPy ),
  17141. new THREE.Vector2( aX, aY ) );
  17142. this.curves.push( curve );
  17143. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17144. };
  17145. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17146. aCP2x, aCP2y,
  17147. aX, aY ) {
  17148. var args = Array.prototype.slice.call( arguments );
  17149. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17150. var x0 = lastargs[ lastargs.length - 2 ];
  17151. var y0 = lastargs[ lastargs.length - 1 ];
  17152. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17153. new THREE.Vector2( aCP1x, aCP1y ),
  17154. new THREE.Vector2( aCP2x, aCP2y ),
  17155. new THREE.Vector2( aX, aY ) );
  17156. this.curves.push( curve );
  17157. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17158. };
  17159. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17160. var args = Array.prototype.slice.call( arguments );
  17161. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17162. var x0 = lastargs[ lastargs.length - 2 ];
  17163. var y0 = lastargs[ lastargs.length - 1 ];
  17164. //---
  17165. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17166. Array.prototype.push.apply( npts, pts );
  17167. var curve = new THREE.SplineCurve( npts );
  17168. this.curves.push( curve );
  17169. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17170. };
  17171. // FUTURE: Change the API or follow canvas API?
  17172. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17173. aStartAngle, aEndAngle, aClockwise ) {
  17174. var lastargs = this.actions[ this.actions.length - 1].args;
  17175. var x0 = lastargs[ lastargs.length - 2 ];
  17176. var y0 = lastargs[ lastargs.length - 1 ];
  17177. this.absarc(aX + x0, aY + y0, aRadius,
  17178. aStartAngle, aEndAngle, aClockwise );
  17179. };
  17180. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17181. aStartAngle, aEndAngle, aClockwise ) {
  17182. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17183. };
  17184. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17185. aStartAngle, aEndAngle, aClockwise ) {
  17186. var lastargs = this.actions[ this.actions.length - 1].args;
  17187. var x0 = lastargs[ lastargs.length - 2 ];
  17188. var y0 = lastargs[ lastargs.length - 1 ];
  17189. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17190. aStartAngle, aEndAngle, aClockwise );
  17191. };
  17192. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17193. aStartAngle, aEndAngle, aClockwise ) {
  17194. var args = Array.prototype.slice.call( arguments );
  17195. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17196. aStartAngle, aEndAngle, aClockwise );
  17197. this.curves.push( curve );
  17198. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17199. args.push(lastPoint.x);
  17200. args.push(lastPoint.y);
  17201. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17202. };
  17203. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17204. if ( ! divisions ) divisions = 40;
  17205. var points = [];
  17206. for ( var i = 0; i < divisions; i ++ ) {
  17207. points.push( this.getPoint( i / divisions ) );
  17208. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17209. }
  17210. // if ( closedPath ) {
  17211. //
  17212. // points.push( points[ 0 ] );
  17213. //
  17214. // }
  17215. return points;
  17216. };
  17217. /* Return an array of vectors based on contour of the path */
  17218. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17219. if (this.useSpacedPoints) {
  17220. console.log('tata');
  17221. return this.getSpacedPoints( divisions, closedPath );
  17222. }
  17223. divisions = divisions || 12;
  17224. var points = [];
  17225. var i, il, item, action, args;
  17226. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17227. laste, j,
  17228. t, tx, ty;
  17229. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17230. item = this.actions[ i ];
  17231. action = item.action;
  17232. args = item.args;
  17233. switch( action ) {
  17234. case THREE.PathActions.MOVE_TO:
  17235. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17236. break;
  17237. case THREE.PathActions.LINE_TO:
  17238. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17239. break;
  17240. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17241. cpx = args[ 2 ];
  17242. cpy = args[ 3 ];
  17243. cpx1 = args[ 0 ];
  17244. cpy1 = args[ 1 ];
  17245. if ( points.length > 0 ) {
  17246. laste = points[ points.length - 1 ];
  17247. cpx0 = laste.x;
  17248. cpy0 = laste.y;
  17249. } else {
  17250. laste = this.actions[ i - 1 ].args;
  17251. cpx0 = laste[ laste.length - 2 ];
  17252. cpy0 = laste[ laste.length - 1 ];
  17253. }
  17254. for ( j = 1; j <= divisions; j ++ ) {
  17255. t = j / divisions;
  17256. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17257. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17258. points.push( new THREE.Vector2( tx, ty ) );
  17259. }
  17260. break;
  17261. case THREE.PathActions.BEZIER_CURVE_TO:
  17262. cpx = args[ 4 ];
  17263. cpy = args[ 5 ];
  17264. cpx1 = args[ 0 ];
  17265. cpy1 = args[ 1 ];
  17266. cpx2 = args[ 2 ];
  17267. cpy2 = args[ 3 ];
  17268. if ( points.length > 0 ) {
  17269. laste = points[ points.length - 1 ];
  17270. cpx0 = laste.x;
  17271. cpy0 = laste.y;
  17272. } else {
  17273. laste = this.actions[ i - 1 ].args;
  17274. cpx0 = laste[ laste.length - 2 ];
  17275. cpy0 = laste[ laste.length - 1 ];
  17276. }
  17277. for ( j = 1; j <= divisions; j ++ ) {
  17278. t = j / divisions;
  17279. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17280. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17281. points.push( new THREE.Vector2( tx, ty ) );
  17282. }
  17283. break;
  17284. case THREE.PathActions.CSPLINE_THRU:
  17285. laste = this.actions[ i - 1 ].args;
  17286. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17287. var spts = [ last ];
  17288. var n = divisions * args[ 0 ].length;
  17289. spts = spts.concat( args[ 0 ] );
  17290. var spline = new THREE.SplineCurve( spts );
  17291. for ( j = 1; j <= n; j ++ ) {
  17292. points.push( spline.getPointAt( j / n ) ) ;
  17293. }
  17294. break;
  17295. case THREE.PathActions.ARC:
  17296. var aX = args[ 0 ], aY = args[ 1 ],
  17297. aRadius = args[ 2 ],
  17298. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17299. aClockwise = !!args[ 5 ];
  17300. var deltaAngle = aEndAngle - aStartAngle;
  17301. var angle;
  17302. var tdivisions = divisions * 2;
  17303. for ( j = 1; j <= tdivisions; j ++ ) {
  17304. t = j / tdivisions;
  17305. if ( ! aClockwise ) {
  17306. t = 1 - t;
  17307. }
  17308. angle = aStartAngle + t * deltaAngle;
  17309. tx = aX + aRadius * Math.cos( angle );
  17310. ty = aY + aRadius * Math.sin( angle );
  17311. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17312. points.push( new THREE.Vector2( tx, ty ) );
  17313. }
  17314. //console.log(points);
  17315. break;
  17316. case THREE.PathActions.ELLIPSE:
  17317. var aX = args[ 0 ], aY = args[ 1 ],
  17318. xRadius = args[ 2 ],
  17319. yRadius = args[ 3 ],
  17320. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17321. aClockwise = !!args[ 6 ];
  17322. var deltaAngle = aEndAngle - aStartAngle;
  17323. var angle;
  17324. var tdivisions = divisions * 2;
  17325. for ( j = 1; j <= tdivisions; j ++ ) {
  17326. t = j / tdivisions;
  17327. if ( ! aClockwise ) {
  17328. t = 1 - t;
  17329. }
  17330. angle = aStartAngle + t * deltaAngle;
  17331. tx = aX + xRadius * Math.cos( angle );
  17332. ty = aY + yRadius * Math.sin( angle );
  17333. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17334. points.push( new THREE.Vector2( tx, ty ) );
  17335. }
  17336. //console.log(points);
  17337. break;
  17338. } // end switch
  17339. }
  17340. // Normalize to remove the closing point by default.
  17341. var lastPoint = points[ points.length - 1];
  17342. var EPSILON = 0.0000000001;
  17343. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17344. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17345. points.splice( points.length - 1, 1);
  17346. if ( closedPath ) {
  17347. points.push( points[ 0 ] );
  17348. }
  17349. return points;
  17350. };
  17351. // Breaks path into shapes
  17352. THREE.Path.prototype.toShapes = function() {
  17353. var i, il, item, action, args;
  17354. var subPaths = [], lastPath = new THREE.Path();
  17355. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17356. item = this.actions[ i ];
  17357. args = item.args;
  17358. action = item.action;
  17359. if ( action == THREE.PathActions.MOVE_TO ) {
  17360. if ( lastPath.actions.length != 0 ) {
  17361. subPaths.push( lastPath );
  17362. lastPath = new THREE.Path();
  17363. }
  17364. }
  17365. lastPath[ action ].apply( lastPath, args );
  17366. }
  17367. if ( lastPath.actions.length != 0 ) {
  17368. subPaths.push( lastPath );
  17369. }
  17370. // console.log(subPaths);
  17371. if ( subPaths.length == 0 ) return [];
  17372. var tmpPath, tmpShape, shapes = [];
  17373. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17374. // console.log("Holes first", holesFirst);
  17375. if ( subPaths.length == 1) {
  17376. tmpPath = subPaths[0];
  17377. tmpShape = new THREE.Shape();
  17378. tmpShape.actions = tmpPath.actions;
  17379. tmpShape.curves = tmpPath.curves;
  17380. shapes.push( tmpShape );
  17381. return shapes;
  17382. };
  17383. if ( holesFirst ) {
  17384. tmpShape = new THREE.Shape();
  17385. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17386. tmpPath = subPaths[ i ];
  17387. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17388. tmpShape.actions = tmpPath.actions;
  17389. tmpShape.curves = tmpPath.curves;
  17390. shapes.push( tmpShape );
  17391. tmpShape = new THREE.Shape();
  17392. //console.log('cw', i);
  17393. } else {
  17394. tmpShape.holes.push( tmpPath );
  17395. //console.log('ccw', i);
  17396. }
  17397. }
  17398. } else {
  17399. // Shapes first
  17400. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17401. tmpPath = subPaths[ i ];
  17402. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17403. if ( tmpShape ) shapes.push( tmpShape );
  17404. tmpShape = new THREE.Shape();
  17405. tmpShape.actions = tmpPath.actions;
  17406. tmpShape.curves = tmpPath.curves;
  17407. } else {
  17408. tmpShape.holes.push( tmpPath );
  17409. }
  17410. }
  17411. shapes.push( tmpShape );
  17412. }
  17413. //console.log("shape", shapes);
  17414. return shapes;
  17415. };
  17416. /**
  17417. * @author zz85 / http://www.lab4games.net/zz85/blog
  17418. * Defines a 2d shape plane using paths.
  17419. **/
  17420. // STEP 1 Create a path.
  17421. // STEP 2 Turn path into shape.
  17422. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17423. // STEP 3a - Extract points from each shape, turn to vertices
  17424. // STEP 3b - Triangulate each shape, add faces.
  17425. THREE.Shape = function () {
  17426. THREE.Path.apply( this, arguments );
  17427. this.holes = [];
  17428. };
  17429. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17430. // Convenience method to return ExtrudeGeometry
  17431. THREE.Shape.prototype.extrude = function ( options ) {
  17432. var extruded = new THREE.ExtrudeGeometry( this, options );
  17433. return extruded;
  17434. };
  17435. // Convenience method to return ShapeGeometry
  17436. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17437. var geometry = new THREE.ShapeGeometry( this, options );
  17438. return geometry;
  17439. };
  17440. // Get points of holes
  17441. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17442. var i, il = this.holes.length, holesPts = [];
  17443. for ( i = 0; i < il; i ++ ) {
  17444. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17445. }
  17446. return holesPts;
  17447. };
  17448. // Get points of holes (spaced by regular distance)
  17449. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17450. var i, il = this.holes.length, holesPts = [];
  17451. for ( i = 0; i < il; i ++ ) {
  17452. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17453. }
  17454. return holesPts;
  17455. };
  17456. // Get points of shape and holes (keypoints based on segments parameter)
  17457. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17458. return {
  17459. shape: this.getTransformedPoints( divisions ),
  17460. holes: this.getPointsHoles( divisions )
  17461. };
  17462. };
  17463. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17464. if (this.useSpacedPoints) {
  17465. return this.extractAllSpacedPoints(divisions);
  17466. }
  17467. return this.extractAllPoints(divisions);
  17468. };
  17469. //
  17470. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17471. //
  17472. // return {
  17473. //
  17474. // shape: this.transform( bend, divisions ),
  17475. // holes: this.getPointsHoles( divisions, bend )
  17476. //
  17477. // };
  17478. //
  17479. // };
  17480. // Get points of shape and holes (spaced by regular distance)
  17481. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17482. return {
  17483. shape: this.getTransformedSpacedPoints( divisions ),
  17484. holes: this.getSpacedPointsHoles( divisions )
  17485. };
  17486. };
  17487. /**************************************************************
  17488. * Utils
  17489. **************************************************************/
  17490. THREE.Shape.Utils = {
  17491. /*
  17492. contour - array of vector2 for contour
  17493. holes - array of array of vector2
  17494. */
  17495. removeHoles: function ( contour, holes ) {
  17496. var shape = contour.concat(); // work on this shape
  17497. var allpoints = shape.concat();
  17498. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17499. var prevShapeVert, nextShapeVert,
  17500. prevHoleVert, nextHoleVert,
  17501. holeIndex, shapeIndex,
  17502. shapeId, shapeGroup,
  17503. h, h2,
  17504. hole, shortest, d,
  17505. p, pts1, pts2,
  17506. tmpShape1, tmpShape2,
  17507. tmpHole1, tmpHole2,
  17508. verts = [];
  17509. for ( h = 0; h < holes.length; h ++ ) {
  17510. hole = holes[ h ];
  17511. /*
  17512. shapeholes[ h ].concat(); // preserves original
  17513. holes.push( hole );
  17514. */
  17515. Array.prototype.push.apply( allpoints, hole );
  17516. shortest = Number.POSITIVE_INFINITY;
  17517. // Find the shortest pair of pts between shape and hole
  17518. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17519. // Using distanceToSquared() intead of distanceTo() should speed a little
  17520. // since running square roots operations are reduced.
  17521. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17522. pts1 = hole[ h2 ];
  17523. var dist = [];
  17524. for ( p = 0; p < shape.length; p++ ) {
  17525. pts2 = shape[ p ];
  17526. d = pts1.distanceToSquared( pts2 );
  17527. dist.push( d );
  17528. if ( d < shortest ) {
  17529. shortest = d;
  17530. holeIndex = h2;
  17531. shapeIndex = p;
  17532. }
  17533. }
  17534. }
  17535. //console.log("shortest", shortest, dist);
  17536. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17537. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17538. var areaapts = [
  17539. hole[ holeIndex ],
  17540. shape[ shapeIndex ],
  17541. shape[ prevShapeVert ]
  17542. ];
  17543. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17544. var areabpts = [
  17545. hole[ holeIndex ],
  17546. hole[ prevHoleVert ],
  17547. shape[ shapeIndex ]
  17548. ];
  17549. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17550. var shapeOffset = 1;
  17551. var holeOffset = -1;
  17552. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17553. shapeIndex += shapeOffset;
  17554. holeIndex += holeOffset;
  17555. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17556. shapeIndex %= shape.length;
  17557. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17558. holeIndex %= hole.length;
  17559. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17560. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17561. areaapts = [
  17562. hole[ holeIndex ],
  17563. shape[ shapeIndex ],
  17564. shape[ prevShapeVert ]
  17565. ];
  17566. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17567. areabpts = [
  17568. hole[ holeIndex ],
  17569. hole[ prevHoleVert ],
  17570. shape[ shapeIndex ]
  17571. ];
  17572. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17573. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17574. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17575. // In case areas are not correct.
  17576. //console.log("USE THIS");
  17577. shapeIndex = oldShapeIndex;
  17578. holeIndex = oldHoleIndex ;
  17579. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17580. shapeIndex %= shape.length;
  17581. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17582. holeIndex %= hole.length;
  17583. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17584. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17585. } else {
  17586. //console.log("USE THAT ")
  17587. }
  17588. tmpShape1 = shape.slice( 0, shapeIndex );
  17589. tmpShape2 = shape.slice( shapeIndex );
  17590. tmpHole1 = hole.slice( holeIndex );
  17591. tmpHole2 = hole.slice( 0, holeIndex );
  17592. // Should check orders here again?
  17593. var trianglea = [
  17594. hole[ holeIndex ],
  17595. shape[ shapeIndex ],
  17596. shape[ prevShapeVert ]
  17597. ];
  17598. var triangleb = [
  17599. hole[ holeIndex ] ,
  17600. hole[ prevHoleVert ],
  17601. shape[ shapeIndex ]
  17602. ];
  17603. verts.push( trianglea );
  17604. verts.push( triangleb );
  17605. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17606. }
  17607. return {
  17608. shape:shape, /* shape with no holes */
  17609. isolatedPts: verts, /* isolated faces */
  17610. allpoints: allpoints
  17611. }
  17612. },
  17613. triangulateShape: function ( contour, holes ) {
  17614. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17615. var shape = shapeWithoutHoles.shape,
  17616. allpoints = shapeWithoutHoles.allpoints,
  17617. isolatedPts = shapeWithoutHoles.isolatedPts;
  17618. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17619. // 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.
  17620. //console.log( "triangles",triangles, triangles.length );
  17621. //console.log( "allpoints",allpoints, allpoints.length );
  17622. var i, il, f, face,
  17623. key, index,
  17624. allPointsMap = {},
  17625. isolatedPointsMap = {};
  17626. // prepare all points map
  17627. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17628. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17629. if ( allPointsMap[ key ] !== undefined ) {
  17630. console.log( "Duplicate point", key );
  17631. }
  17632. allPointsMap[ key ] = i;
  17633. }
  17634. // check all face vertices against all points map
  17635. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17636. face = triangles[ i ];
  17637. for ( f = 0; f < 3; f ++ ) {
  17638. key = face[ f ].x + ":" + face[ f ].y;
  17639. index = allPointsMap[ key ];
  17640. if ( index !== undefined ) {
  17641. face[ f ] = index;
  17642. }
  17643. }
  17644. }
  17645. // check isolated points vertices against all points map
  17646. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17647. face = isolatedPts[ i ];
  17648. for ( f = 0; f < 3; f ++ ) {
  17649. key = face[ f ].x + ":" + face[ f ].y;
  17650. index = allPointsMap[ key ];
  17651. if ( index !== undefined ) {
  17652. face[ f ] = index;
  17653. }
  17654. }
  17655. }
  17656. return triangles.concat( isolatedPts );
  17657. }, // end triangulate shapes
  17658. /*
  17659. triangulate2 : function( pts, holes ) {
  17660. // For use with Poly2Tri.js
  17661. var allpts = pts.concat();
  17662. var shape = [];
  17663. for (var p in pts) {
  17664. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17665. }
  17666. var swctx = new js.poly2tri.SweepContext(shape);
  17667. for (var h in holes) {
  17668. var aHole = holes[h];
  17669. var newHole = []
  17670. for (i in aHole) {
  17671. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17672. allpts.push(aHole[i]);
  17673. }
  17674. swctx.AddHole(newHole);
  17675. }
  17676. var find;
  17677. var findIndexForPt = function (pt) {
  17678. find = new THREE.Vector2(pt.x, pt.y);
  17679. var p;
  17680. for (p=0, pl = allpts.length; p<pl; p++) {
  17681. if (allpts[p].equals(find)) return p;
  17682. }
  17683. return -1;
  17684. };
  17685. // triangulate
  17686. js.poly2tri.sweep.Triangulate(swctx);
  17687. var triangles = swctx.GetTriangles();
  17688. var tr ;
  17689. var facesPts = [];
  17690. for (var t in triangles) {
  17691. tr = triangles[t];
  17692. facesPts.push([
  17693. findIndexForPt(tr.GetPoint(0)),
  17694. findIndexForPt(tr.GetPoint(1)),
  17695. findIndexForPt(tr.GetPoint(2))
  17696. ]);
  17697. }
  17698. // console.log(facesPts);
  17699. // console.log("triangles", triangles.length, triangles);
  17700. // Returns array of faces with 3 element each
  17701. return facesPts;
  17702. },
  17703. */
  17704. isClockWise: function ( pts ) {
  17705. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17706. },
  17707. // Bezier Curves formulas obtained from
  17708. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17709. // Quad Bezier Functions
  17710. b2p0: function ( t, p ) {
  17711. var k = 1 - t;
  17712. return k * k * p;
  17713. },
  17714. b2p1: function ( t, p ) {
  17715. return 2 * ( 1 - t ) * t * p;
  17716. },
  17717. b2p2: function ( t, p ) {
  17718. return t * t * p;
  17719. },
  17720. b2: function ( t, p0, p1, p2 ) {
  17721. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17722. },
  17723. // Cubic Bezier Functions
  17724. b3p0: function ( t, p ) {
  17725. var k = 1 - t;
  17726. return k * k * k * p;
  17727. },
  17728. b3p1: function ( t, p ) {
  17729. var k = 1 - t;
  17730. return 3 * k * k * t * p;
  17731. },
  17732. b3p2: function ( t, p ) {
  17733. var k = 1 - t;
  17734. return 3 * k * t * t * p;
  17735. },
  17736. b3p3: function ( t, p ) {
  17737. return t * t * t * p;
  17738. },
  17739. b3: function ( t, p0, p1, p2, p3 ) {
  17740. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17741. }
  17742. };
  17743. /**
  17744. * @author mikael emtinger / http://gomo.se/
  17745. */
  17746. THREE.AnimationHandler = (function() {
  17747. var playing = [];
  17748. var library = {};
  17749. var that = {};
  17750. //--- update ---
  17751. that.update = function( deltaTimeMS ) {
  17752. for( var i = 0; i < playing.length; i ++ )
  17753. playing[ i ].update( deltaTimeMS );
  17754. };
  17755. //--- add ---
  17756. that.addToUpdate = function( animation ) {
  17757. if ( playing.indexOf( animation ) === -1 )
  17758. playing.push( animation );
  17759. };
  17760. //--- remove ---
  17761. that.removeFromUpdate = function( animation ) {
  17762. var index = playing.indexOf( animation );
  17763. if( index !== -1 )
  17764. playing.splice( index, 1 );
  17765. };
  17766. //--- add ---
  17767. that.add = function( data ) {
  17768. if ( library[ data.name ] !== undefined )
  17769. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17770. library[ data.name ] = data;
  17771. initData( data );
  17772. };
  17773. //--- get ---
  17774. that.get = function( name ) {
  17775. if ( typeof name === "string" ) {
  17776. if ( library[ name ] ) {
  17777. return library[ name ];
  17778. } else {
  17779. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17780. return null;
  17781. }
  17782. } else {
  17783. // todo: add simple tween library
  17784. }
  17785. };
  17786. //--- parse ---
  17787. that.parse = function( root ) {
  17788. // setup hierarchy
  17789. var hierarchy = [];
  17790. if ( root instanceof THREE.SkinnedMesh ) {
  17791. for( var b = 0; b < root.bones.length; b++ ) {
  17792. hierarchy.push( root.bones[ b ] );
  17793. }
  17794. } else {
  17795. parseRecurseHierarchy( root, hierarchy );
  17796. }
  17797. return hierarchy;
  17798. };
  17799. var parseRecurseHierarchy = function( root, hierarchy ) {
  17800. hierarchy.push( root );
  17801. for( var c = 0; c < root.children.length; c++ )
  17802. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17803. }
  17804. //--- init data ---
  17805. var initData = function( data ) {
  17806. if( data.initialized === true )
  17807. return;
  17808. // loop through all keys
  17809. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17810. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17811. // remove minus times
  17812. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17813. data.hierarchy[ h ].keys[ k ].time = 0;
  17814. // create quaternions
  17815. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17816. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17817. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17818. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17819. }
  17820. }
  17821. // prepare morph target keys
  17822. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17823. // get all used
  17824. var usedMorphTargets = {};
  17825. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17826. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17827. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17828. usedMorphTargets[ morphTargetName ] = -1;
  17829. }
  17830. }
  17831. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17832. // set all used on all frames
  17833. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17834. var influences = {};
  17835. for ( var morphTargetName in usedMorphTargets ) {
  17836. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17837. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17838. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17839. break;
  17840. }
  17841. }
  17842. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17843. influences[ morphTargetName ] = 0;
  17844. }
  17845. }
  17846. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17847. }
  17848. }
  17849. // remove all keys that are on the same time
  17850. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17851. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17852. data.hierarchy[ h ].keys.splice( k, 1 );
  17853. k --;
  17854. }
  17855. }
  17856. // set index
  17857. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17858. data.hierarchy[ h ].keys[ k ].index = k;
  17859. }
  17860. }
  17861. // JIT
  17862. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17863. data.JIT = {};
  17864. data.JIT.hierarchy = [];
  17865. for( var h = 0; h < data.hierarchy.length; h ++ )
  17866. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17867. // done
  17868. data.initialized = true;
  17869. };
  17870. // interpolation types
  17871. that.LINEAR = 0;
  17872. that.CATMULLROM = 1;
  17873. that.CATMULLROM_FORWARD = 2;
  17874. return that;
  17875. }());
  17876. /**
  17877. * @author mikael emtinger / http://gomo.se/
  17878. * @author mrdoob / http://mrdoob.com/
  17879. * @author alteredq / http://alteredqualia.com/
  17880. */
  17881. THREE.Animation = function ( root, name, interpolationType ) {
  17882. this.root = root;
  17883. this.data = THREE.AnimationHandler.get( name );
  17884. this.hierarchy = THREE.AnimationHandler.parse( root );
  17885. this.currentTime = 0;
  17886. this.timeScale = 1;
  17887. this.isPlaying = false;
  17888. this.isPaused = true;
  17889. this.loop = true;
  17890. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17891. this.points = [];
  17892. this.target = new THREE.Vector3();
  17893. };
  17894. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17895. if ( this.isPlaying === false ) {
  17896. this.isPlaying = true;
  17897. this.loop = loop !== undefined ? loop : true;
  17898. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17899. // reset key cache
  17900. var h, hl = this.hierarchy.length,
  17901. object;
  17902. for ( h = 0; h < hl; h ++ ) {
  17903. object = this.hierarchy[ h ];
  17904. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17905. object.useQuaternion = true;
  17906. }
  17907. object.matrixAutoUpdate = true;
  17908. if ( object.animationCache === undefined ) {
  17909. object.animationCache = {};
  17910. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17911. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17912. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17913. }
  17914. var prevKey = object.animationCache.prevKey;
  17915. var nextKey = object.animationCache.nextKey;
  17916. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17917. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17918. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17919. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17920. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17921. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17922. }
  17923. this.update( 0 );
  17924. }
  17925. this.isPaused = false;
  17926. THREE.AnimationHandler.addToUpdate( this );
  17927. };
  17928. THREE.Animation.prototype.pause = function() {
  17929. if ( this.isPaused === true ) {
  17930. THREE.AnimationHandler.addToUpdate( this );
  17931. } else {
  17932. THREE.AnimationHandler.removeFromUpdate( this );
  17933. }
  17934. this.isPaused = !this.isPaused;
  17935. };
  17936. THREE.Animation.prototype.stop = function() {
  17937. this.isPlaying = false;
  17938. this.isPaused = false;
  17939. THREE.AnimationHandler.removeFromUpdate( this );
  17940. };
  17941. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17942. // early out
  17943. if ( this.isPlaying === false ) return;
  17944. // vars
  17945. var types = [ "pos", "rot", "scl" ];
  17946. var type;
  17947. var scale;
  17948. var vector;
  17949. var prevXYZ, nextXYZ;
  17950. var prevKey, nextKey;
  17951. var object;
  17952. var animationCache;
  17953. var frame;
  17954. var JIThierarchy = this.data.JIT.hierarchy;
  17955. var currentTime, unloopedCurrentTime;
  17956. var currentPoint, forwardPoint, angle;
  17957. this.currentTime += deltaTimeMS * this.timeScale;
  17958. unloopedCurrentTime = this.currentTime;
  17959. currentTime = this.currentTime = this.currentTime % this.data.length;
  17960. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17961. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17962. object = this.hierarchy[ h ];
  17963. animationCache = object.animationCache;
  17964. // loop through pos/rot/scl
  17965. for ( var t = 0; t < 3; t ++ ) {
  17966. // get keys
  17967. type = types[ t ];
  17968. prevKey = animationCache.prevKey[ type ];
  17969. nextKey = animationCache.nextKey[ type ];
  17970. // switch keys?
  17971. if ( nextKey.time <= unloopedCurrentTime ) {
  17972. // did we loop?
  17973. if ( currentTime < unloopedCurrentTime ) {
  17974. if ( this.loop ) {
  17975. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17976. nextKey = this.getNextKeyWith( type, h, 1 );
  17977. while( nextKey.time < currentTime ) {
  17978. prevKey = nextKey;
  17979. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17980. }
  17981. } else {
  17982. this.stop();
  17983. return;
  17984. }
  17985. } else {
  17986. do {
  17987. prevKey = nextKey;
  17988. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17989. } while( nextKey.time < currentTime )
  17990. }
  17991. animationCache.prevKey[ type ] = prevKey;
  17992. animationCache.nextKey[ type ] = nextKey;
  17993. }
  17994. object.matrixAutoUpdate = true;
  17995. object.matrixWorldNeedsUpdate = true;
  17996. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17997. prevXYZ = prevKey[ type ];
  17998. nextXYZ = nextKey[ type ];
  17999. // check scale error
  18000. if ( scale < 0 || scale > 1 ) {
  18001. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18002. scale = scale < 0 ? 0 : 1;
  18003. }
  18004. // interpolate
  18005. if ( type === "pos" ) {
  18006. vector = object.position;
  18007. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18008. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18009. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18010. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18011. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18012. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18013. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18014. this.points[ 1 ] = prevXYZ;
  18015. this.points[ 2 ] = nextXYZ;
  18016. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18017. scale = scale * 0.33 + 0.33;
  18018. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18019. vector.x = currentPoint[ 0 ];
  18020. vector.y = currentPoint[ 1 ];
  18021. vector.z = currentPoint[ 2 ];
  18022. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18023. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18024. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18025. this.target.sub( vector );
  18026. this.target.y = 0;
  18027. this.target.normalize();
  18028. angle = Math.atan2( this.target.x, this.target.z );
  18029. object.rotation.set( 0, angle, 0 );
  18030. }
  18031. }
  18032. } else if ( type === "rot" ) {
  18033. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18034. } else if ( type === "scl" ) {
  18035. vector = object.scale;
  18036. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18037. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18038. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18039. }
  18040. }
  18041. }
  18042. };
  18043. // Catmull-Rom spline
  18044. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18045. var c = [], v3 = [],
  18046. point, intPoint, weight, w2, w3,
  18047. pa, pb, pc, pd;
  18048. point = ( points.length - 1 ) * scale;
  18049. intPoint = Math.floor( point );
  18050. weight = point - intPoint;
  18051. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18052. c[ 1 ] = intPoint;
  18053. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18054. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18055. pa = points[ c[ 0 ] ];
  18056. pb = points[ c[ 1 ] ];
  18057. pc = points[ c[ 2 ] ];
  18058. pd = points[ c[ 3 ] ];
  18059. w2 = weight * weight;
  18060. w3 = weight * w2;
  18061. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18062. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18063. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18064. return v3;
  18065. };
  18066. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18067. var v0 = ( p2 - p0 ) * 0.5,
  18068. v1 = ( p3 - p1 ) * 0.5;
  18069. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18070. };
  18071. // Get next key with
  18072. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18073. var keys = this.data.hierarchy[ h ].keys;
  18074. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18075. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18076. key = key < keys.length - 1 ? key : keys.length - 1;
  18077. } else {
  18078. key = key % keys.length;
  18079. }
  18080. for ( ; key < keys.length; key++ ) {
  18081. if ( keys[ key ][ type ] !== undefined ) {
  18082. return keys[ key ];
  18083. }
  18084. }
  18085. return this.data.hierarchy[ h ].keys[ 0 ];
  18086. };
  18087. // Get previous key with
  18088. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18089. var keys = this.data.hierarchy[ h ].keys;
  18090. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18091. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18092. key = key > 0 ? key : 0;
  18093. } else {
  18094. key = key >= 0 ? key : key + keys.length;
  18095. }
  18096. for ( ; key >= 0; key -- ) {
  18097. if ( keys[ key ][ type ] !== undefined ) {
  18098. return keys[ key ];
  18099. }
  18100. }
  18101. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18102. };
  18103. /**
  18104. * @author mikael emtinger / http://gomo.se/
  18105. * @author mrdoob / http://mrdoob.com/
  18106. * @author alteredq / http://alteredqualia.com/
  18107. * @author khang duong
  18108. * @author erik kitson
  18109. */
  18110. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18111. this.root = root;
  18112. this.data = THREE.AnimationHandler.get( data );
  18113. this.hierarchy = THREE.AnimationHandler.parse( root );
  18114. this.currentTime = 0;
  18115. this.timeScale = 0.001;
  18116. this.isPlaying = false;
  18117. this.isPaused = true;
  18118. this.loop = true;
  18119. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18120. // initialize to first keyframes
  18121. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18122. var keys = this.data.hierarchy[h].keys,
  18123. sids = this.data.hierarchy[h].sids,
  18124. obj = this.hierarchy[h];
  18125. if ( keys.length && sids ) {
  18126. for ( var s = 0; s < sids.length; s++ ) {
  18127. var sid = sids[ s ],
  18128. next = this.getNextKeyWith( sid, h, 0 );
  18129. if ( next ) {
  18130. next.apply( sid );
  18131. }
  18132. }
  18133. obj.matrixAutoUpdate = false;
  18134. this.data.hierarchy[h].node.updateMatrix();
  18135. obj.matrixWorldNeedsUpdate = true;
  18136. }
  18137. }
  18138. };
  18139. // Play
  18140. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18141. if( !this.isPlaying ) {
  18142. this.isPlaying = true;
  18143. this.loop = loop !== undefined ? loop : true;
  18144. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18145. this.startTimeMs = startTimeMS;
  18146. this.startTime = 10000000;
  18147. this.endTime = -this.startTime;
  18148. // reset key cache
  18149. var h, hl = this.hierarchy.length,
  18150. object,
  18151. node;
  18152. for ( h = 0; h < hl; h++ ) {
  18153. object = this.hierarchy[ h ];
  18154. node = this.data.hierarchy[ h ];
  18155. object.useQuaternion = true;
  18156. if ( node.animationCache === undefined ) {
  18157. node.animationCache = {};
  18158. node.animationCache.prevKey = null;
  18159. node.animationCache.nextKey = null;
  18160. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18161. }
  18162. var keys = this.data.hierarchy[h].keys;
  18163. if (keys.length) {
  18164. node.animationCache.prevKey = keys[ 0 ];
  18165. node.animationCache.nextKey = keys[ 1 ];
  18166. this.startTime = Math.min( keys[0].time, this.startTime );
  18167. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18168. }
  18169. }
  18170. this.update( 0 );
  18171. }
  18172. this.isPaused = false;
  18173. THREE.AnimationHandler.addToUpdate( this );
  18174. };
  18175. // Pause
  18176. THREE.KeyFrameAnimation.prototype.pause = function() {
  18177. if( this.isPaused ) {
  18178. THREE.AnimationHandler.addToUpdate( this );
  18179. } else {
  18180. THREE.AnimationHandler.removeFromUpdate( this );
  18181. }
  18182. this.isPaused = !this.isPaused;
  18183. };
  18184. // Stop
  18185. THREE.KeyFrameAnimation.prototype.stop = function() {
  18186. this.isPlaying = false;
  18187. this.isPaused = false;
  18188. THREE.AnimationHandler.removeFromUpdate( this );
  18189. // reset JIT matrix and remove cache
  18190. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18191. var obj = this.hierarchy[ h ];
  18192. var node = this.data.hierarchy[ h ];
  18193. if ( node.animationCache !== undefined ) {
  18194. var original = node.animationCache.originalMatrix;
  18195. if( obj instanceof THREE.Bone ) {
  18196. original.copy( obj.skinMatrix );
  18197. obj.skinMatrix = original;
  18198. } else {
  18199. original.copy( obj.matrix );
  18200. obj.matrix = original;
  18201. }
  18202. delete node.animationCache;
  18203. }
  18204. }
  18205. };
  18206. // Update
  18207. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18208. // early out
  18209. if( !this.isPlaying ) return;
  18210. // vars
  18211. var prevKey, nextKey;
  18212. var object;
  18213. var node;
  18214. var frame;
  18215. var JIThierarchy = this.data.JIT.hierarchy;
  18216. var currentTime, unloopedCurrentTime;
  18217. var looped;
  18218. // update
  18219. this.currentTime += deltaTimeMS * this.timeScale;
  18220. unloopedCurrentTime = this.currentTime;
  18221. currentTime = this.currentTime = this.currentTime % this.data.length;
  18222. // if looped around, the current time should be based on the startTime
  18223. if ( currentTime < this.startTimeMs ) {
  18224. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18225. }
  18226. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18227. looped = currentTime < unloopedCurrentTime;
  18228. if ( looped && !this.loop ) {
  18229. // Set the animation to the last keyframes and stop
  18230. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18231. var keys = this.data.hierarchy[h].keys,
  18232. sids = this.data.hierarchy[h].sids,
  18233. end = keys.length-1,
  18234. obj = this.hierarchy[h];
  18235. if ( keys.length ) {
  18236. for ( var s = 0; s < sids.length; s++ ) {
  18237. var sid = sids[ s ],
  18238. prev = this.getPrevKeyWith( sid, h, end );
  18239. if ( prev ) {
  18240. prev.apply( sid );
  18241. }
  18242. }
  18243. this.data.hierarchy[h].node.updateMatrix();
  18244. obj.matrixWorldNeedsUpdate = true;
  18245. }
  18246. }
  18247. this.stop();
  18248. return;
  18249. }
  18250. // check pre-infinity
  18251. if ( currentTime < this.startTime ) {
  18252. return;
  18253. }
  18254. // update
  18255. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18256. object = this.hierarchy[ h ];
  18257. node = this.data.hierarchy[ h ];
  18258. var keys = node.keys,
  18259. animationCache = node.animationCache;
  18260. // use JIT?
  18261. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18262. if( object instanceof THREE.Bone ) {
  18263. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18264. object.matrixWorldNeedsUpdate = false;
  18265. } else {
  18266. object.matrix = JIThierarchy[ h ][ frame ];
  18267. object.matrixWorldNeedsUpdate = true;
  18268. }
  18269. // use interpolation
  18270. } else if ( keys.length ) {
  18271. // make sure so original matrix and not JIT matrix is set
  18272. if ( this.JITCompile && animationCache ) {
  18273. if( object instanceof THREE.Bone ) {
  18274. object.skinMatrix = animationCache.originalMatrix;
  18275. } else {
  18276. object.matrix = animationCache.originalMatrix;
  18277. }
  18278. }
  18279. prevKey = animationCache.prevKey;
  18280. nextKey = animationCache.nextKey;
  18281. if ( prevKey && nextKey ) {
  18282. // switch keys?
  18283. if ( nextKey.time <= unloopedCurrentTime ) {
  18284. // did we loop?
  18285. if ( looped && this.loop ) {
  18286. prevKey = keys[ 0 ];
  18287. nextKey = keys[ 1 ];
  18288. while ( nextKey.time < currentTime ) {
  18289. prevKey = nextKey;
  18290. nextKey = keys[ prevKey.index + 1 ];
  18291. }
  18292. } else if ( !looped ) {
  18293. var lastIndex = keys.length - 1;
  18294. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18295. prevKey = nextKey;
  18296. nextKey = keys[ prevKey.index + 1 ];
  18297. }
  18298. }
  18299. animationCache.prevKey = prevKey;
  18300. animationCache.nextKey = nextKey;
  18301. }
  18302. if(nextKey.time >= currentTime)
  18303. prevKey.interpolate( nextKey, currentTime );
  18304. else
  18305. prevKey.interpolate( nextKey, nextKey.time);
  18306. }
  18307. this.data.hierarchy[h].node.updateMatrix();
  18308. object.matrixWorldNeedsUpdate = true;
  18309. }
  18310. }
  18311. // update JIT?
  18312. if ( this.JITCompile ) {
  18313. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18314. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18315. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18316. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18317. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18318. } else {
  18319. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18320. }
  18321. }
  18322. }
  18323. }
  18324. };
  18325. // Get next key with
  18326. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18327. var keys = this.data.hierarchy[ h ].keys;
  18328. key = key % keys.length;
  18329. for ( ; key < keys.length; key++ ) {
  18330. if ( keys[ key ].hasTarget( sid ) ) {
  18331. return keys[ key ];
  18332. }
  18333. }
  18334. return keys[ 0 ];
  18335. };
  18336. // Get previous key with
  18337. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18338. var keys = this.data.hierarchy[ h ].keys;
  18339. key = key >= 0 ? key : key + keys.length;
  18340. for ( ; key >= 0; key-- ) {
  18341. if ( keys[ key ].hasTarget( sid ) ) {
  18342. return keys[ key ];
  18343. }
  18344. }
  18345. return keys[ keys.length - 1 ];
  18346. };
  18347. /**
  18348. * Camera for rendering cube maps
  18349. * - renders scene into axis-aligned cube
  18350. *
  18351. * @author alteredq / http://alteredqualia.com/
  18352. */
  18353. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18354. THREE.Object3D.call( this );
  18355. var fov = 90, aspect = 1;
  18356. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18357. cameraPX.up.set( 0, -1, 0 );
  18358. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18359. this.add( cameraPX );
  18360. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18361. cameraNX.up.set( 0, -1, 0 );
  18362. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18363. this.add( cameraNX );
  18364. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18365. cameraPY.up.set( 0, 0, 1 );
  18366. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18367. this.add( cameraPY );
  18368. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18369. cameraNY.up.set( 0, 0, -1 );
  18370. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18371. this.add( cameraNY );
  18372. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18373. cameraPZ.up.set( 0, -1, 0 );
  18374. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18375. this.add( cameraPZ );
  18376. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18377. cameraNZ.up.set( 0, -1, 0 );
  18378. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18379. this.add( cameraNZ );
  18380. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18381. this.updateCubeMap = function ( renderer, scene ) {
  18382. var renderTarget = this.renderTarget;
  18383. var generateMipmaps = renderTarget.generateMipmaps;
  18384. renderTarget.generateMipmaps = false;
  18385. renderTarget.activeCubeFace = 0;
  18386. renderer.render( scene, cameraPX, renderTarget );
  18387. renderTarget.activeCubeFace = 1;
  18388. renderer.render( scene, cameraNX, renderTarget );
  18389. renderTarget.activeCubeFace = 2;
  18390. renderer.render( scene, cameraPY, renderTarget );
  18391. renderTarget.activeCubeFace = 3;
  18392. renderer.render( scene, cameraNY, renderTarget );
  18393. renderTarget.activeCubeFace = 4;
  18394. renderer.render( scene, cameraPZ, renderTarget );
  18395. renderTarget.generateMipmaps = generateMipmaps;
  18396. renderTarget.activeCubeFace = 5;
  18397. renderer.render( scene, cameraNZ, renderTarget );
  18398. };
  18399. };
  18400. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18401. /*
  18402. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18403. *
  18404. * A general perpose camera, for setting FOV, Lens Focal Length,
  18405. * and switching between perspective and orthographic views easily.
  18406. * Use this only if you do not wish to manage
  18407. * both a Orthographic and Perspective Camera
  18408. *
  18409. */
  18410. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18411. THREE.Camera.call( this );
  18412. this.fov = fov;
  18413. this.left = -width / 2;
  18414. this.right = width / 2
  18415. this.top = height / 2;
  18416. this.bottom = -height / 2;
  18417. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18418. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18419. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18420. this.zoom = 1;
  18421. this.toPerspective();
  18422. var aspect = width/height;
  18423. };
  18424. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18425. THREE.CombinedCamera.prototype.toPerspective = function () {
  18426. // Switches to the Perspective Camera
  18427. this.near = this.cameraP.near;
  18428. this.far = this.cameraP.far;
  18429. this.cameraP.fov = this.fov / this.zoom ;
  18430. this.cameraP.updateProjectionMatrix();
  18431. this.projectionMatrix = this.cameraP.projectionMatrix;
  18432. this.inPerspectiveMode = true;
  18433. this.inOrthographicMode = false;
  18434. };
  18435. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18436. // Switches to the Orthographic camera estimating viewport from Perspective
  18437. var fov = this.fov;
  18438. var aspect = this.cameraP.aspect;
  18439. var near = this.cameraP.near;
  18440. var far = this.cameraP.far;
  18441. // The size that we set is the mid plane of the viewing frustum
  18442. var hyperfocus = ( near + far ) / 2;
  18443. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18444. var planeHeight = 2 * halfHeight;
  18445. var planeWidth = planeHeight * aspect;
  18446. var halfWidth = planeWidth / 2;
  18447. halfHeight /= this.zoom;
  18448. halfWidth /= this.zoom;
  18449. this.cameraO.left = -halfWidth;
  18450. this.cameraO.right = halfWidth;
  18451. this.cameraO.top = halfHeight;
  18452. this.cameraO.bottom = -halfHeight;
  18453. // this.cameraO.left = -farHalfWidth;
  18454. // this.cameraO.right = farHalfWidth;
  18455. // this.cameraO.top = farHalfHeight;
  18456. // this.cameraO.bottom = -farHalfHeight;
  18457. // this.cameraO.left = this.left / this.zoom;
  18458. // this.cameraO.right = this.right / this.zoom;
  18459. // this.cameraO.top = this.top / this.zoom;
  18460. // this.cameraO.bottom = this.bottom / this.zoom;
  18461. this.cameraO.updateProjectionMatrix();
  18462. this.near = this.cameraO.near;
  18463. this.far = this.cameraO.far;
  18464. this.projectionMatrix = this.cameraO.projectionMatrix;
  18465. this.inPerspectiveMode = false;
  18466. this.inOrthographicMode = true;
  18467. };
  18468. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18469. this.cameraP.aspect = width / height;
  18470. this.left = -width / 2;
  18471. this.right = width / 2
  18472. this.top = height / 2;
  18473. this.bottom = -height / 2;
  18474. };
  18475. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18476. this.fov = fov;
  18477. if ( this.inPerspectiveMode ) {
  18478. this.toPerspective();
  18479. } else {
  18480. this.toOrthographic();
  18481. }
  18482. };
  18483. // For mantaining similar API with PerspectiveCamera
  18484. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18485. if ( this.inPerspectiveMode ) {
  18486. this.toPerspective();
  18487. } else {
  18488. this.toPerspective();
  18489. this.toOrthographic();
  18490. }
  18491. };
  18492. /*
  18493. * Uses Focal Length (in mm) to estimate and set FOV
  18494. * 35mm (fullframe) camera is used if frame size is not specified;
  18495. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18496. */
  18497. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18498. if ( frameHeight === undefined ) frameHeight = 24;
  18499. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18500. this.setFov( fov );
  18501. return fov;
  18502. };
  18503. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18504. this.zoom = zoom;
  18505. if ( this.inPerspectiveMode ) {
  18506. this.toPerspective();
  18507. } else {
  18508. this.toOrthographic();
  18509. }
  18510. };
  18511. THREE.CombinedCamera.prototype.toFrontView = function() {
  18512. this.rotation.x = 0;
  18513. this.rotation.y = 0;
  18514. this.rotation.z = 0;
  18515. // should we be modifing the matrix instead?
  18516. this.rotationAutoUpdate = false;
  18517. };
  18518. THREE.CombinedCamera.prototype.toBackView = function() {
  18519. this.rotation.x = 0;
  18520. this.rotation.y = Math.PI;
  18521. this.rotation.z = 0;
  18522. this.rotationAutoUpdate = false;
  18523. };
  18524. THREE.CombinedCamera.prototype.toLeftView = function() {
  18525. this.rotation.x = 0;
  18526. this.rotation.y = - Math.PI / 2;
  18527. this.rotation.z = 0;
  18528. this.rotationAutoUpdate = false;
  18529. };
  18530. THREE.CombinedCamera.prototype.toRightView = function() {
  18531. this.rotation.x = 0;
  18532. this.rotation.y = Math.PI / 2;
  18533. this.rotation.z = 0;
  18534. this.rotationAutoUpdate = false;
  18535. };
  18536. THREE.CombinedCamera.prototype.toTopView = function() {
  18537. this.rotation.x = - Math.PI / 2;
  18538. this.rotation.y = 0;
  18539. this.rotation.z = 0;
  18540. this.rotationAutoUpdate = false;
  18541. };
  18542. THREE.CombinedCamera.prototype.toBottomView = function() {
  18543. this.rotation.x = Math.PI / 2;
  18544. this.rotation.y = 0;
  18545. this.rotation.z = 0;
  18546. this.rotationAutoUpdate = false;
  18547. };
  18548. /**
  18549. * @author hughes
  18550. */
  18551. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18552. THREE.Geometry.call( this );
  18553. radius = radius || 50;
  18554. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18555. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18556. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18557. var i, uvs = [],
  18558. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18559. this.vertices.push(center);
  18560. uvs.push( centerUV );
  18561. for ( i = 0; i <= segments; i ++ ) {
  18562. var vertex = new THREE.Vector3();
  18563. var segment = thetaStart + i / segments * thetaLength;
  18564. vertex.x = radius * Math.cos( segment );
  18565. vertex.y = radius * Math.sin( segment );
  18566. this.vertices.push( vertex );
  18567. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18568. }
  18569. var n = new THREE.Vector3( 0, 0, 1 );
  18570. for ( i = 1; i <= segments; i ++ ) {
  18571. var v1 = i;
  18572. var v2 = i + 1 ;
  18573. var v3 = 0;
  18574. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18575. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18576. }
  18577. this.computeCentroids();
  18578. this.computeFaceNormals();
  18579. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18580. };
  18581. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18582. /**
  18583. * @author mrdoob / http://mrdoob.com/
  18584. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18585. */
  18586. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18587. THREE.Geometry.call( this );
  18588. var scope = this;
  18589. this.width = width;
  18590. this.height = height;
  18591. this.depth = depth;
  18592. this.widthSegments = widthSegments || 1;
  18593. this.heightSegments = heightSegments || 1;
  18594. this.depthSegments = depthSegments || 1;
  18595. var width_half = this.width / 2;
  18596. var height_half = this.height / 2;
  18597. var depth_half = this.depth / 2;
  18598. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18599. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18600. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18601. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18602. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18603. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18604. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18605. var w, ix, iy,
  18606. gridX = scope.widthSegments,
  18607. gridY = scope.heightSegments,
  18608. width_half = width / 2,
  18609. height_half = height / 2,
  18610. offset = scope.vertices.length;
  18611. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18612. w = 'z';
  18613. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18614. w = 'y';
  18615. gridY = scope.depthSegments;
  18616. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18617. w = 'x';
  18618. gridX = scope.depthSegments;
  18619. }
  18620. var gridX1 = gridX + 1,
  18621. gridY1 = gridY + 1,
  18622. segment_width = width / gridX,
  18623. segment_height = height / gridY,
  18624. normal = new THREE.Vector3();
  18625. normal[ w ] = depth > 0 ? 1 : - 1;
  18626. for ( iy = 0; iy < gridY1; iy ++ ) {
  18627. for ( ix = 0; ix < gridX1; ix ++ ) {
  18628. var vector = new THREE.Vector3();
  18629. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18630. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18631. vector[ w ] = depth;
  18632. scope.vertices.push( vector );
  18633. }
  18634. }
  18635. for ( iy = 0; iy < gridY; iy++ ) {
  18636. for ( ix = 0; ix < gridX; ix++ ) {
  18637. var a = ix + gridX1 * iy;
  18638. var b = ix + gridX1 * ( iy + 1 );
  18639. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18640. var d = ( ix + 1 ) + gridX1 * iy;
  18641. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18642. face.normal.copy( normal );
  18643. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18644. face.materialIndex = materialIndex;
  18645. scope.faces.push( face );
  18646. scope.faceVertexUvs[ 0 ].push( [
  18647. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18648. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18649. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18650. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18651. ] );
  18652. }
  18653. }
  18654. }
  18655. this.computeCentroids();
  18656. this.mergeVertices();
  18657. };
  18658. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18659. /**
  18660. * @author mrdoob / http://mrdoob.com/
  18661. */
  18662. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18663. THREE.Geometry.call( this );
  18664. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18665. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18666. this.height = height = height !== undefined ? height : 100;
  18667. this.radiusSegments = radiusSegments = radiusSegments || 8;
  18668. this.heightSegments = heightSegments = heightSegments || 1;
  18669. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  18670. var heightHalf = height / 2;
  18671. var x, y, vertices = [], uvs = [];
  18672. for ( y = 0; y <= heightSegments; y ++ ) {
  18673. var verticesRow = [];
  18674. var uvsRow = [];
  18675. var v = y / heightSegments;
  18676. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18677. for ( x = 0; x <= radiusSegments; x ++ ) {
  18678. var u = x / radiusSegments;
  18679. var vertex = new THREE.Vector3();
  18680. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18681. vertex.y = - v * height + heightHalf;
  18682. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18683. this.vertices.push( vertex );
  18684. verticesRow.push( this.vertices.length - 1 );
  18685. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18686. }
  18687. vertices.push( verticesRow );
  18688. uvs.push( uvsRow );
  18689. }
  18690. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18691. var na, nb;
  18692. for ( x = 0; x < radiusSegments; x ++ ) {
  18693. if ( radiusTop !== 0 ) {
  18694. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18695. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18696. } else {
  18697. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18698. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18699. }
  18700. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18701. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18702. for ( y = 0; y < heightSegments; y ++ ) {
  18703. var v1 = vertices[ y ][ x ];
  18704. var v2 = vertices[ y + 1 ][ x ];
  18705. var v3 = vertices[ y + 1 ][ x + 1 ];
  18706. var v4 = vertices[ y ][ x + 1 ];
  18707. var n1 = na.clone();
  18708. var n2 = na.clone();
  18709. var n3 = nb.clone();
  18710. var n4 = nb.clone();
  18711. var uv1 = uvs[ y ][ x ].clone();
  18712. var uv2 = uvs[ y + 1 ][ x ].clone();
  18713. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18714. var uv4 = uvs[ y ][ x + 1 ].clone();
  18715. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18716. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18717. }
  18718. }
  18719. // top cap
  18720. if ( openEnded === false && radiusTop > 0 ) {
  18721. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18722. for ( x = 0; x < radiusSegments; x ++ ) {
  18723. var v1 = vertices[ 0 ][ x ];
  18724. var v2 = vertices[ 0 ][ x + 1 ];
  18725. var v3 = this.vertices.length - 1;
  18726. var n1 = new THREE.Vector3( 0, 1, 0 );
  18727. var n2 = new THREE.Vector3( 0, 1, 0 );
  18728. var n3 = new THREE.Vector3( 0, 1, 0 );
  18729. var uv1 = uvs[ 0 ][ x ].clone();
  18730. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18731. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18732. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18733. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18734. }
  18735. }
  18736. // bottom cap
  18737. if ( openEnded === false && radiusBottom > 0 ) {
  18738. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18739. for ( x = 0; x < radiusSegments; x ++ ) {
  18740. var v1 = vertices[ y ][ x + 1 ];
  18741. var v2 = vertices[ y ][ x ];
  18742. var v3 = this.vertices.length - 1;
  18743. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18744. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18745. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18746. var uv1 = uvs[ y ][ x + 1 ].clone();
  18747. var uv2 = uvs[ y ][ x ].clone();
  18748. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18749. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18750. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18751. }
  18752. }
  18753. this.computeCentroids();
  18754. this.computeFaceNormals();
  18755. }
  18756. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18757. /**
  18758. * @author zz85 / http://www.lab4games.net/zz85/blog
  18759. *
  18760. * Creates extruded geometry from a path shape.
  18761. *
  18762. * parameters = {
  18763. *
  18764. * size: <float>, // size of the text
  18765. * height: <float>, // thickness to extrude text
  18766. * curveSegments: <int>, // number of points on the curves
  18767. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18768. * amount: <int>, // Amount
  18769. *
  18770. * bevelEnabled: <bool>, // turn on bevel
  18771. * bevelThickness: <float>, // how deep into text bevel goes
  18772. * bevelSize: <float>, // how far from text outline is bevel
  18773. * bevelSegments: <int>, // number of bevel layers
  18774. *
  18775. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18776. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18777. *
  18778. * material: <int> // material index for front and back faces
  18779. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18780. * uvGenerator: <Object> // object that provides UV generator functions
  18781. *
  18782. * }
  18783. **/
  18784. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18785. if ( typeof( shapes ) === "undefined" ) {
  18786. shapes = [];
  18787. return;
  18788. }
  18789. THREE.Geometry.call( this );
  18790. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18791. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18792. this.addShapeList( shapes, options );
  18793. this.computeCentroids();
  18794. this.computeFaceNormals();
  18795. // can't really use automatic vertex normals
  18796. // as then front and back sides get smoothed too
  18797. // should do separate smoothing just for sides
  18798. //this.computeVertexNormals();
  18799. //console.log( "took", ( Date.now() - startTime ) );
  18800. };
  18801. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18802. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18803. var sl = shapes.length;
  18804. for ( var s = 0; s < sl; s ++ ) {
  18805. var shape = shapes[ s ];
  18806. this.addShape( shape, options );
  18807. }
  18808. };
  18809. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18810. var amount = options.amount !== undefined ? options.amount : 100;
  18811. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18812. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18813. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18814. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18815. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18816. var steps = options.steps !== undefined ? options.steps : 1;
  18817. var extrudePath = options.extrudePath;
  18818. var extrudePts, extrudeByPath = false;
  18819. var material = options.material;
  18820. var extrudeMaterial = options.extrudeMaterial;
  18821. // Use default WorldUVGenerator if no UV generators are specified.
  18822. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18823. var shapebb = this.shapebb;
  18824. //shapebb = shape.getBoundingBox();
  18825. var splineTube, binormal, normal, position2;
  18826. if ( extrudePath ) {
  18827. extrudePts = extrudePath.getSpacedPoints( steps );
  18828. extrudeByPath = true;
  18829. bevelEnabled = false; // bevels not supported for path extrusion
  18830. // SETUP TNB variables
  18831. // Reuse TNB from TubeGeomtry for now.
  18832. // TODO1 - have a .isClosed in spline?
  18833. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18834. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18835. binormal = new THREE.Vector3();
  18836. normal = new THREE.Vector3();
  18837. position2 = new THREE.Vector3();
  18838. }
  18839. // Safeguards if bevels are not enabled
  18840. if ( ! bevelEnabled ) {
  18841. bevelSegments = 0;
  18842. bevelThickness = 0;
  18843. bevelSize = 0;
  18844. }
  18845. // Variables initalization
  18846. var ahole, h, hl; // looping of holes
  18847. var scope = this;
  18848. var bevelPoints = [];
  18849. var shapesOffset = this.vertices.length;
  18850. var shapePoints = shape.extractPoints( curveSegments );
  18851. var vertices = shapePoints.shape;
  18852. var holes = shapePoints.holes;
  18853. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18854. if ( reverse ) {
  18855. vertices = vertices.reverse();
  18856. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18857. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18858. ahole = holes[ h ];
  18859. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18860. holes[ h ] = ahole.reverse();
  18861. }
  18862. }
  18863. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18864. }
  18865. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18866. /* Vertices */
  18867. var contour = vertices; // vertices has all points but contour has only points of circumference
  18868. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18869. ahole = holes[ h ];
  18870. vertices = vertices.concat( ahole );
  18871. }
  18872. function scalePt2 ( pt, vec, size ) {
  18873. if ( !vec ) console.log( "die" );
  18874. return vec.clone().multiplyScalar( size ).add( pt );
  18875. }
  18876. var b, bs, t, z,
  18877. vert, vlen = vertices.length,
  18878. face, flen = faces.length,
  18879. cont, clen = contour.length;
  18880. // Find directions for point movement
  18881. var RAD_TO_DEGREES = 180 / Math.PI;
  18882. function getBevelVec( pt_i, pt_j, pt_k ) {
  18883. // Algorithm 2
  18884. return getBevelVec2( pt_i, pt_j, pt_k );
  18885. }
  18886. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18887. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18888. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18889. if ( anglea > angleb ) {
  18890. angleb += Math.PI * 2;
  18891. }
  18892. var anglec = ( anglea + angleb ) / 2;
  18893. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18894. var x = - Math.cos( anglec );
  18895. var y = - Math.sin( anglec );
  18896. var vec = new THREE.Vector2( x, y ); //.normalize();
  18897. return vec;
  18898. }
  18899. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18900. var a = THREE.ExtrudeGeometry.__v1,
  18901. b = THREE.ExtrudeGeometry.__v2,
  18902. v_hat = THREE.ExtrudeGeometry.__v3,
  18903. w_hat = THREE.ExtrudeGeometry.__v4,
  18904. p = THREE.ExtrudeGeometry.__v5,
  18905. q = THREE.ExtrudeGeometry.__v6,
  18906. v, w,
  18907. v_dot_w_hat, q_sub_p_dot_w_hat,
  18908. s, intersection;
  18909. // good reading for line-line intersection
  18910. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18911. // define a as vector j->i
  18912. // define b as vectot k->i
  18913. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18914. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18915. // get unit vectors
  18916. v = a.normalize();
  18917. w = b.normalize();
  18918. // normals from pt i
  18919. v_hat.set( -v.y, v.x );
  18920. w_hat.set( w.y, -w.x );
  18921. // pts from i
  18922. p.copy( pt_i ).add( v_hat );
  18923. q.copy( pt_i ).add( w_hat );
  18924. if ( p.equals( q ) ) {
  18925. //console.log("Warning: lines are straight");
  18926. return w_hat.clone();
  18927. }
  18928. // Points from j, k. helps prevents points cross overover most of the time
  18929. p.copy( pt_j ).add( v_hat );
  18930. q.copy( pt_k ).add( w_hat );
  18931. v_dot_w_hat = v.dot( w_hat );
  18932. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18933. // We should not reach these conditions
  18934. if ( v_dot_w_hat === 0 ) {
  18935. console.log( "Either infinite or no solutions!" );
  18936. if ( q_sub_p_dot_w_hat === 0 ) {
  18937. console.log( "Its finite solutions." );
  18938. } else {
  18939. console.log( "Too bad, no solutions." );
  18940. }
  18941. }
  18942. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18943. if ( s < 0 ) {
  18944. // in case of emergecy, revert to algorithm 1.
  18945. return getBevelVec1( pt_i, pt_j, pt_k );
  18946. }
  18947. intersection = v.multiplyScalar( s ).add( p );
  18948. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18949. }
  18950. var contourMovements = [];
  18951. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18952. if ( j === il ) j = 0;
  18953. if ( k === il ) k = 0;
  18954. // (j)---(i)---(k)
  18955. // console.log('i,j,k', i, j , k)
  18956. var pt_i = contour[ i ];
  18957. var pt_j = contour[ j ];
  18958. var pt_k = contour[ k ];
  18959. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18960. }
  18961. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18962. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18963. ahole = holes[ h ];
  18964. oneHoleMovements = [];
  18965. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18966. if ( j === il ) j = 0;
  18967. if ( k === il ) k = 0;
  18968. // (j)---(i)---(k)
  18969. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18970. }
  18971. holesMovements.push( oneHoleMovements );
  18972. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18973. }
  18974. // Loop bevelSegments, 1 for the front, 1 for the back
  18975. for ( b = 0; b < bevelSegments; b ++ ) {
  18976. //for ( b = bevelSegments; b > 0; b -- ) {
  18977. t = b / bevelSegments;
  18978. z = bevelThickness * ( 1 - t );
  18979. //z = bevelThickness * t;
  18980. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18981. //bs = bevelSize * t ; // linear
  18982. // contract shape
  18983. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18984. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18985. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18986. v( vert.x, vert.y, - z );
  18987. }
  18988. // expand holes
  18989. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18990. ahole = holes[ h ];
  18991. oneHoleMovements = holesMovements[ h ];
  18992. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18993. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18994. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18995. v( vert.x, vert.y, -z );
  18996. }
  18997. }
  18998. }
  18999. bs = bevelSize;
  19000. // Back facing vertices
  19001. for ( i = 0; i < vlen; i ++ ) {
  19002. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19003. if ( !extrudeByPath ) {
  19004. v( vert.x, vert.y, 0 );
  19005. } else {
  19006. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19007. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19008. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19009. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19010. v( position2.x, position2.y, position2.z );
  19011. }
  19012. }
  19013. // Add stepped vertices...
  19014. // Including front facing vertices
  19015. var s;
  19016. for ( s = 1; s <= steps; s ++ ) {
  19017. for ( i = 0; i < vlen; i ++ ) {
  19018. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19019. if ( !extrudeByPath ) {
  19020. v( vert.x, vert.y, amount / steps * s );
  19021. } else {
  19022. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19023. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19024. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19025. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19026. v( position2.x, position2.y, position2.z );
  19027. }
  19028. }
  19029. }
  19030. // Add bevel segments planes
  19031. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19032. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19033. t = b / bevelSegments;
  19034. z = bevelThickness * ( 1 - t );
  19035. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19036. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19037. // contract shape
  19038. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19039. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19040. v( vert.x, vert.y, amount + z );
  19041. }
  19042. // expand holes
  19043. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19044. ahole = holes[ h ];
  19045. oneHoleMovements = holesMovements[ h ];
  19046. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19047. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19048. if ( !extrudeByPath ) {
  19049. v( vert.x, vert.y, amount + z );
  19050. } else {
  19051. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19052. }
  19053. }
  19054. }
  19055. }
  19056. /* Faces */
  19057. // Top and bottom faces
  19058. buildLidFaces();
  19059. // Sides faces
  19060. buildSideFaces();
  19061. ///// Internal functions
  19062. function buildLidFaces() {
  19063. if ( bevelEnabled ) {
  19064. var layer = 0 ; // steps + 1
  19065. var offset = vlen * layer;
  19066. // Bottom faces
  19067. for ( i = 0; i < flen; i ++ ) {
  19068. face = faces[ i ];
  19069. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19070. }
  19071. layer = steps + bevelSegments * 2;
  19072. offset = vlen * layer;
  19073. // Top faces
  19074. for ( i = 0; i < flen; i ++ ) {
  19075. face = faces[ i ];
  19076. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19077. }
  19078. } else {
  19079. // Bottom faces
  19080. for ( i = 0; i < flen; i++ ) {
  19081. face = faces[ i ];
  19082. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19083. }
  19084. // Top faces
  19085. for ( i = 0; i < flen; i ++ ) {
  19086. face = faces[ i ];
  19087. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19088. }
  19089. }
  19090. }
  19091. // Create faces for the z-sides of the shape
  19092. function buildSideFaces() {
  19093. var layeroffset = 0;
  19094. sidewalls( contour, layeroffset );
  19095. layeroffset += contour.length;
  19096. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19097. ahole = holes[ h ];
  19098. sidewalls( ahole, layeroffset );
  19099. //, true
  19100. layeroffset += ahole.length;
  19101. }
  19102. }
  19103. function sidewalls( contour, layeroffset ) {
  19104. var j, k;
  19105. i = contour.length;
  19106. while ( --i >= 0 ) {
  19107. j = i;
  19108. k = i - 1;
  19109. if ( k < 0 ) k = contour.length - 1;
  19110. //console.log('b', i,j, i-1, k,vertices.length);
  19111. var s = 0, sl = steps + bevelSegments * 2;
  19112. for ( s = 0; s < sl; s ++ ) {
  19113. var slen1 = vlen * s;
  19114. var slen2 = vlen * ( s + 1 );
  19115. var a = layeroffset + j + slen1,
  19116. b = layeroffset + k + slen1,
  19117. c = layeroffset + k + slen2,
  19118. d = layeroffset + j + slen2;
  19119. f4( a, b, c, d, contour, s, sl, j, k );
  19120. }
  19121. }
  19122. }
  19123. function v( x, y, z ) {
  19124. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19125. }
  19126. function f3( a, b, c, isBottom ) {
  19127. a += shapesOffset;
  19128. b += shapesOffset;
  19129. c += shapesOffset;
  19130. // normal, color, material
  19131. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19132. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19133. scope.faceVertexUvs[ 0 ].push( uvs );
  19134. }
  19135. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19136. a += shapesOffset;
  19137. b += shapesOffset;
  19138. c += shapesOffset;
  19139. d += shapesOffset;
  19140. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19141. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19142. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19143. scope.faceVertexUvs[ 0 ].push( uvs );
  19144. }
  19145. };
  19146. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19147. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19148. var ax = geometry.vertices[ indexA ].x,
  19149. ay = geometry.vertices[ indexA ].y,
  19150. bx = geometry.vertices[ indexB ].x,
  19151. by = geometry.vertices[ indexB ].y,
  19152. cx = geometry.vertices[ indexC ].x,
  19153. cy = geometry.vertices[ indexC ].y;
  19154. return [
  19155. new THREE.Vector2( ax, ay ),
  19156. new THREE.Vector2( bx, by ),
  19157. new THREE.Vector2( cx, cy )
  19158. ];
  19159. },
  19160. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19161. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19162. },
  19163. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19164. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19165. contourIndex1, contourIndex2 ) {
  19166. var ax = geometry.vertices[ indexA ].x,
  19167. ay = geometry.vertices[ indexA ].y,
  19168. az = geometry.vertices[ indexA ].z,
  19169. bx = geometry.vertices[ indexB ].x,
  19170. by = geometry.vertices[ indexB ].y,
  19171. bz = geometry.vertices[ indexB ].z,
  19172. cx = geometry.vertices[ indexC ].x,
  19173. cy = geometry.vertices[ indexC ].y,
  19174. cz = geometry.vertices[ indexC ].z,
  19175. dx = geometry.vertices[ indexD ].x,
  19176. dy = geometry.vertices[ indexD ].y,
  19177. dz = geometry.vertices[ indexD ].z;
  19178. if ( Math.abs( ay - by ) < 0.01 ) {
  19179. return [
  19180. new THREE.Vector2( ax, 1 - az ),
  19181. new THREE.Vector2( bx, 1 - bz ),
  19182. new THREE.Vector2( cx, 1 - cz ),
  19183. new THREE.Vector2( dx, 1 - dz )
  19184. ];
  19185. } else {
  19186. return [
  19187. new THREE.Vector2( ay, 1 - az ),
  19188. new THREE.Vector2( by, 1 - bz ),
  19189. new THREE.Vector2( cy, 1 - cz ),
  19190. new THREE.Vector2( dy, 1 - dz )
  19191. ];
  19192. }
  19193. }
  19194. };
  19195. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19196. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19197. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19198. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19199. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19200. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19201. /**
  19202. * @author jonobr1 / http://jonobr1.com
  19203. *
  19204. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19205. * ExtrudeGeometry.
  19206. *
  19207. * parameters = {
  19208. *
  19209. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19210. *
  19211. * material: <int> // material index for front and back faces
  19212. * uvGenerator: <Object> // object that provides UV generator functions
  19213. *
  19214. * }
  19215. **/
  19216. THREE.ShapeGeometry = function ( shapes, options ) {
  19217. THREE.Geometry.call( this );
  19218. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19219. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19220. this.addShapeList( shapes, options );
  19221. this.computeCentroids();
  19222. this.computeFaceNormals();
  19223. };
  19224. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19225. /**
  19226. * Add an array of shapes to THREE.ShapeGeometry.
  19227. */
  19228. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19229. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19230. this.addShape( shapes[ i ], options );
  19231. }
  19232. return this;
  19233. };
  19234. /**
  19235. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19236. */
  19237. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19238. if ( options === undefined ) options = {};
  19239. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19240. var material = options.material;
  19241. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19242. var shapebb = this.shapebb;
  19243. //
  19244. var i, l, hole, s;
  19245. var shapesOffset = this.vertices.length;
  19246. var shapePoints = shape.extractPoints( curveSegments );
  19247. var vertices = shapePoints.shape;
  19248. var holes = shapePoints.holes;
  19249. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19250. if ( reverse ) {
  19251. vertices = vertices.reverse();
  19252. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19253. for ( i = 0, l = holes.length; i < l; i++ ) {
  19254. hole = holes[ i ];
  19255. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19256. holes[ i ] = hole.reverse();
  19257. }
  19258. }
  19259. reverse = false;
  19260. }
  19261. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19262. // Vertices
  19263. var contour = vertices;
  19264. for ( i = 0, l = holes.length; i < l; i++ ) {
  19265. hole = holes[ i ];
  19266. vertices = vertices.concat( hole );
  19267. }
  19268. //
  19269. var vert, vlen = vertices.length;
  19270. var face, flen = faces.length;
  19271. var cont, clen = contour.length;
  19272. for ( i = 0; i < vlen; i++ ) {
  19273. vert = vertices[ i ];
  19274. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19275. }
  19276. for ( i = 0; i < flen; i++ ) {
  19277. face = faces[ i ];
  19278. var a = face[ 0 ] + shapesOffset;
  19279. var b = face[ 1 ] + shapesOffset;
  19280. var c = face[ 2 ] + shapesOffset;
  19281. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19282. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19283. }
  19284. };
  19285. /**
  19286. * @author astrodud / http://astrodud.isgreat.org/
  19287. * @author zz85 / https://github.com/zz85
  19288. * @author bhouston / http://exocortex.com
  19289. */
  19290. // points - to create a closed torus, one must use a set of points
  19291. // like so: [ a, b, c, d, a ], see first is the same as last.
  19292. // segments - the number of circumference segments to create
  19293. // phiStart - the starting radian
  19294. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19295. // 2*pi is a closed lathe, less than 2PI is a portion.
  19296. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19297. THREE.Geometry.call( this );
  19298. segments = segments || 12;
  19299. phiStart = phiStart || 0;
  19300. phiLength = phiLength || 2 * Math.PI;
  19301. var inversePointLength = 1.0 / ( points.length - 1 );
  19302. var inverseSegments = 1.0 / segments;
  19303. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19304. var phi = phiStart + i * inverseSegments * phiLength;
  19305. var c = Math.cos( phi ),
  19306. s = Math.sin( phi );
  19307. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19308. var pt = points[ j ];
  19309. var vertex = new THREE.Vector3();
  19310. vertex.x = c * pt.x - s * pt.y;
  19311. vertex.y = s * pt.x + c * pt.y;
  19312. vertex.z = pt.z;
  19313. this.vertices.push( vertex );
  19314. }
  19315. }
  19316. var np = points.length;
  19317. for ( var i = 0, il = segments; i < il; i ++ ) {
  19318. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19319. var base = j + np * i;
  19320. var a = base;
  19321. var b = base + np;
  19322. var c = base + 1 + np;
  19323. var d = base + 1;
  19324. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19325. var u0 = i * inverseSegments;
  19326. var v0 = j * inversePointLength;
  19327. var u1 = u0 + inverseSegments;
  19328. var v1 = v0 + inversePointLength;
  19329. this.faceVertexUvs[ 0 ].push( [
  19330. new THREE.Vector2( u0, v0 ),
  19331. new THREE.Vector2( u1, v0 ),
  19332. new THREE.Vector2( u1, v1 ),
  19333. new THREE.Vector2( u0, v1 )
  19334. ] );
  19335. }
  19336. }
  19337. this.mergeVertices();
  19338. this.computeCentroids();
  19339. this.computeFaceNormals();
  19340. this.computeVertexNormals();
  19341. };
  19342. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19343. /**
  19344. * @author mrdoob / http://mrdoob.com/
  19345. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19346. */
  19347. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19348. THREE.Geometry.call( this );
  19349. this.width = width;
  19350. this.height = height;
  19351. this.widthSegments = widthSegments || 1;
  19352. this.heightSegments = heightSegments || 1;
  19353. var ix, iz;
  19354. var width_half = width / 2;
  19355. var height_half = height / 2;
  19356. var gridX = this.widthSegments;
  19357. var gridZ = this.heightSegments;
  19358. var gridX1 = gridX + 1;
  19359. var gridZ1 = gridZ + 1;
  19360. var segment_width = this.width / gridX;
  19361. var segment_height = this.height / gridZ;
  19362. var normal = new THREE.Vector3( 0, 0, 1 );
  19363. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19364. for ( ix = 0; ix < gridX1; ix ++ ) {
  19365. var x = ix * segment_width - width_half;
  19366. var y = iz * segment_height - height_half;
  19367. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19368. }
  19369. }
  19370. for ( iz = 0; iz < gridZ; iz ++ ) {
  19371. for ( ix = 0; ix < gridX; ix ++ ) {
  19372. var a = ix + gridX1 * iz;
  19373. var b = ix + gridX1 * ( iz + 1 );
  19374. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19375. var d = ( ix + 1 ) + gridX1 * iz;
  19376. var face = new THREE.Face4( a, b, c, d );
  19377. face.normal.copy( normal );
  19378. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19379. this.faces.push( face );
  19380. this.faceVertexUvs[ 0 ].push( [
  19381. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19382. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19383. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19384. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19385. ] );
  19386. }
  19387. }
  19388. this.computeCentroids();
  19389. };
  19390. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19391. /**
  19392. * @author Kaleb Murphy
  19393. */
  19394. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19395. THREE.Geometry.call( this );
  19396. innerRadius = innerRadius || 0;
  19397. outerRadius = outerRadius || 50;
  19398. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19399. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19400. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19401. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19402. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19403. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19404. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19405. var vertex = new THREE.Vector3();
  19406. var segment = thetaStart + o / thetaSegments * thetaLength;
  19407. vertex.x = radius * Math.cos( segment );
  19408. vertex.y = radius * Math.sin( segment );
  19409. this.vertices.push( vertex );
  19410. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19411. }
  19412. radius += radiusStep;
  19413. }
  19414. var n = new THREE.Vector3( 0, 0, 1 );
  19415. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19416. var thetaSegment = i * thetaSegments;
  19417. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19418. var segment = o + thetaSegment;
  19419. var v1 = segment + i;
  19420. var v2 = segment + thetaSegments + i;
  19421. var v3 = segment + thetaSegments + 1 + i;
  19422. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19423. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19424. v1 = segment + i;
  19425. v2 = segment + thetaSegments + 1 + i;
  19426. v3 = segment + 1 + i;
  19427. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19428. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19429. }
  19430. }
  19431. this.computeCentroids();
  19432. this.computeFaceNormals();
  19433. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19434. };
  19435. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19436. /**
  19437. * @author mrdoob / http://mrdoob.com/
  19438. */
  19439. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19440. THREE.Geometry.call( this );
  19441. this.radius = radius = radius || 50;
  19442. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19443. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19444. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19445. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19446. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19447. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19448. var x, y, vertices = [], uvs = [];
  19449. for ( y = 0; y <= heightSegments; y ++ ) {
  19450. var verticesRow = [];
  19451. var uvsRow = [];
  19452. for ( x = 0; x <= widthSegments; x ++ ) {
  19453. var u = x / widthSegments;
  19454. var v = y / heightSegments;
  19455. var vertex = new THREE.Vector3();
  19456. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19457. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19458. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19459. this.vertices.push( vertex );
  19460. verticesRow.push( this.vertices.length - 1 );
  19461. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19462. }
  19463. vertices.push( verticesRow );
  19464. uvs.push( uvsRow );
  19465. }
  19466. for ( y = 0; y < this.heightSegments; y ++ ) {
  19467. for ( x = 0; x < this.widthSegments; x ++ ) {
  19468. var v1 = vertices[ y ][ x + 1 ];
  19469. var v2 = vertices[ y ][ x ];
  19470. var v3 = vertices[ y + 1 ][ x ];
  19471. var v4 = vertices[ y + 1 ][ x + 1 ];
  19472. var n1 = this.vertices[ v1 ].clone().normalize();
  19473. var n2 = this.vertices[ v2 ].clone().normalize();
  19474. var n3 = this.vertices[ v3 ].clone().normalize();
  19475. var n4 = this.vertices[ v4 ].clone().normalize();
  19476. var uv1 = uvs[ y ][ x + 1 ].clone();
  19477. var uv2 = uvs[ y ][ x ].clone();
  19478. var uv3 = uvs[ y + 1 ][ x ].clone();
  19479. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19480. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19481. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19482. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19483. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19484. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19485. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19486. } else {
  19487. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19488. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19489. }
  19490. }
  19491. }
  19492. this.computeCentroids();
  19493. this.computeFaceNormals();
  19494. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19495. };
  19496. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19497. /**
  19498. * @author zz85 / http://www.lab4games.net/zz85/blog
  19499. * @author alteredq / http://alteredqualia.com/
  19500. *
  19501. * For creating 3D text geometry in three.js
  19502. *
  19503. * Text = 3D Text
  19504. *
  19505. * parameters = {
  19506. * size: <float>, // size of the text
  19507. * height: <float>, // thickness to extrude text
  19508. * curveSegments: <int>, // number of points on the curves
  19509. *
  19510. * font: <string>, // font name
  19511. * weight: <string>, // font weight (normal, bold)
  19512. * style: <string>, // font style (normal, italics)
  19513. *
  19514. * bevelEnabled: <bool>, // turn on bevel
  19515. * bevelThickness: <float>, // how deep into text bevel goes
  19516. * bevelSize: <float>, // how far from text outline is bevel
  19517. * }
  19518. *
  19519. */
  19520. /* Usage Examples
  19521. // TextGeometry wrapper
  19522. var text3d = new TextGeometry( text, options );
  19523. // Complete manner
  19524. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19525. var text3d = new ExtrudeGeometry( textShapes, options );
  19526. */
  19527. THREE.TextGeometry = function ( text, parameters ) {
  19528. parameters = parameters || {};
  19529. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19530. // translate parameters to ExtrudeGeometry API
  19531. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19532. // defaults
  19533. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19534. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19535. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19536. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19537. };
  19538. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19539. /**
  19540. * @author oosmoxiecode
  19541. * @author mrdoob / http://mrdoob.com/
  19542. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19543. */
  19544. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19545. THREE.Geometry.call( this );
  19546. var scope = this;
  19547. this.radius = radius || 100;
  19548. this.tube = tube || 40;
  19549. this.radialSegments = radialSegments || 8;
  19550. this.tubularSegments = tubularSegments || 6;
  19551. this.arc = arc || Math.PI * 2;
  19552. var center = new THREE.Vector3(), uvs = [], normals = [];
  19553. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19554. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19555. var u = i / this.tubularSegments * this.arc;
  19556. var v = j / this.radialSegments * Math.PI * 2;
  19557. center.x = this.radius * Math.cos( u );
  19558. center.y = this.radius * Math.sin( u );
  19559. var vertex = new THREE.Vector3();
  19560. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19561. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19562. vertex.z = this.tube * Math.sin( v );
  19563. this.vertices.push( vertex );
  19564. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19565. normals.push( vertex.clone().sub( center ).normalize() );
  19566. }
  19567. }
  19568. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19569. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19570. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19571. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19572. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19573. var d = ( this.tubularSegments + 1 ) * j + i;
  19574. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19575. face.normal.add( normals[ a ] );
  19576. face.normal.add( normals[ b ] );
  19577. face.normal.add( normals[ c ] );
  19578. face.normal.add( normals[ d ] );
  19579. face.normal.normalize();
  19580. this.faces.push( face );
  19581. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19582. }
  19583. }
  19584. this.computeCentroids();
  19585. };
  19586. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19587. /**
  19588. * @author oosmoxiecode
  19589. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19590. */
  19591. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19592. THREE.Geometry.call( this );
  19593. var scope = this;
  19594. this.radius = radius || 100;
  19595. this.tube = tube || 40;
  19596. this.radialSegments = radialSegments || 64;
  19597. this.tubularSegments = tubularSegments || 8;
  19598. this.p = p || 2;
  19599. this.q = q || 3;
  19600. this.heightScale = heightScale || 1;
  19601. this.grid = new Array( this.radialSegments );
  19602. var tang = new THREE.Vector3();
  19603. var n = new THREE.Vector3();
  19604. var bitan = new THREE.Vector3();
  19605. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19606. this.grid[ i ] = new Array( this.tubularSegments );
  19607. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19608. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19609. var v = j / this.tubularSegments * 2 * Math.PI;
  19610. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19611. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19612. var cx, cy;
  19613. tang.subVectors( p2, p1 );
  19614. n.addVectors( p2, p1 );
  19615. bitan.crossVectors( tang, n );
  19616. n.crossVectors( bitan, tang );
  19617. bitan.normalize();
  19618. n.normalize();
  19619. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19620. cy = this.tube * Math.sin( v );
  19621. p1.x += cx * n.x + cy * bitan.x;
  19622. p1.y += cx * n.y + cy * bitan.y;
  19623. p1.z += cx * n.z + cy * bitan.z;
  19624. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19625. }
  19626. }
  19627. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19628. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19629. var ip = ( i + 1 ) % this.radialSegments;
  19630. var jp = ( j + 1 ) % this.tubularSegments;
  19631. var a = this.grid[ i ][ j ];
  19632. var b = this.grid[ ip ][ j ];
  19633. var c = this.grid[ ip ][ jp ];
  19634. var d = this.grid[ i ][ jp ];
  19635. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19636. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19637. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19638. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19639. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19640. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19641. }
  19642. }
  19643. this.computeCentroids();
  19644. this.computeFaceNormals();
  19645. this.computeVertexNormals();
  19646. function vert( x, y, z ) {
  19647. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19648. }
  19649. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19650. var cu = Math.cos( u );
  19651. var cv = Math.cos( v );
  19652. var su = Math.sin( u );
  19653. var quOverP = in_q / in_p * u;
  19654. var cs = Math.cos( quOverP );
  19655. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19656. var ty = radius * ( 2 + cs ) * su * 0.5;
  19657. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19658. return new THREE.Vector3( tx, ty, tz );
  19659. }
  19660. };
  19661. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19662. /**
  19663. * @author WestLangley / https://github.com/WestLangley
  19664. * @author zz85 / https://github.com/zz85
  19665. * @author miningold / https://github.com/miningold
  19666. *
  19667. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19668. *
  19669. * Creates a tube which extrudes along a 3d spline
  19670. *
  19671. * Uses parallel transport frames as described in
  19672. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19673. */
  19674. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19675. THREE.Geometry.call( this );
  19676. this.path = path;
  19677. this.segments = segments || 64;
  19678. this.radius = radius || 1;
  19679. this.radiusSegments = radiusSegments || 8;
  19680. this.closed = closed || false;
  19681. if ( debug ) this.debug = new THREE.Object3D();
  19682. this.grid = [];
  19683. var scope = this,
  19684. tangent,
  19685. normal,
  19686. binormal,
  19687. numpoints = this.segments + 1,
  19688. x, y, z,
  19689. tx, ty, tz,
  19690. u, v,
  19691. cx, cy,
  19692. pos, pos2 = new THREE.Vector3(),
  19693. i, j,
  19694. ip, jp,
  19695. a, b, c, d,
  19696. uva, uvb, uvc, uvd;
  19697. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19698. tangents = frames.tangents,
  19699. normals = frames.normals,
  19700. binormals = frames.binormals;
  19701. // proxy internals
  19702. this.tangents = tangents;
  19703. this.normals = normals;
  19704. this.binormals = binormals;
  19705. function vert( x, y, z ) {
  19706. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19707. }
  19708. // consruct the grid
  19709. for ( i = 0; i < numpoints; i++ ) {
  19710. this.grid[ i ] = [];
  19711. u = i / ( numpoints - 1 );
  19712. pos = path.getPointAt( u );
  19713. tangent = tangents[ i ];
  19714. normal = normals[ i ];
  19715. binormal = binormals[ i ];
  19716. if ( this.debug ) {
  19717. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19718. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19719. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19720. }
  19721. for ( j = 0; j < this.radiusSegments; j++ ) {
  19722. v = j / this.radiusSegments * 2 * Math.PI;
  19723. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19724. cy = this.radius * Math.sin( v );
  19725. pos2.copy( pos );
  19726. pos2.x += cx * normal.x + cy * binormal.x;
  19727. pos2.y += cx * normal.y + cy * binormal.y;
  19728. pos2.z += cx * normal.z + cy * binormal.z;
  19729. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19730. }
  19731. }
  19732. // construct the mesh
  19733. for ( i = 0; i < this.segments; i++ ) {
  19734. for ( j = 0; j < this.radiusSegments; j++ ) {
  19735. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19736. jp = (j + 1) % this.radiusSegments;
  19737. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19738. b = this.grid[ ip ][ j ];
  19739. c = this.grid[ ip ][ jp ];
  19740. d = this.grid[ i ][ jp ];
  19741. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19742. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19743. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19744. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19745. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19746. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19747. }
  19748. }
  19749. this.computeCentroids();
  19750. this.computeFaceNormals();
  19751. this.computeVertexNormals();
  19752. };
  19753. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19754. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19755. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19756. var tangent = new THREE.Vector3(),
  19757. normal = new THREE.Vector3(),
  19758. binormal = new THREE.Vector3(),
  19759. tangents = [],
  19760. normals = [],
  19761. binormals = [],
  19762. vec = new THREE.Vector3(),
  19763. mat = new THREE.Matrix4(),
  19764. numpoints = segments + 1,
  19765. theta,
  19766. epsilon = 0.0001,
  19767. smallest,
  19768. tx, ty, tz,
  19769. i, u, v;
  19770. // expose internals
  19771. this.tangents = tangents;
  19772. this.normals = normals;
  19773. this.binormals = binormals;
  19774. // compute the tangent vectors for each segment on the path
  19775. for ( i = 0; i < numpoints; i++ ) {
  19776. u = i / ( numpoints - 1 );
  19777. tangents[ i ] = path.getTangentAt( u );
  19778. tangents[ i ].normalize();
  19779. }
  19780. initialNormal3();
  19781. function initialNormal1(lastBinormal) {
  19782. // fixed start binormal. Has dangers of 0 vectors
  19783. normals[ 0 ] = new THREE.Vector3();
  19784. binormals[ 0 ] = new THREE.Vector3();
  19785. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19786. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19787. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19788. }
  19789. function initialNormal2() {
  19790. // This uses the Frenet-Serret formula for deriving binormal
  19791. var t2 = path.getTangentAt( epsilon );
  19792. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19793. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19794. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19795. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19796. }
  19797. function initialNormal3() {
  19798. // select an initial normal vector perpenicular to the first tangent vector,
  19799. // and in the direction of the smallest tangent xyz component
  19800. normals[ 0 ] = new THREE.Vector3();
  19801. binormals[ 0 ] = new THREE.Vector3();
  19802. smallest = Number.MAX_VALUE;
  19803. tx = Math.abs( tangents[ 0 ].x );
  19804. ty = Math.abs( tangents[ 0 ].y );
  19805. tz = Math.abs( tangents[ 0 ].z );
  19806. if ( tx <= smallest ) {
  19807. smallest = tx;
  19808. normal.set( 1, 0, 0 );
  19809. }
  19810. if ( ty <= smallest ) {
  19811. smallest = ty;
  19812. normal.set( 0, 1, 0 );
  19813. }
  19814. if ( tz <= smallest ) {
  19815. normal.set( 0, 0, 1 );
  19816. }
  19817. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19818. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19819. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19820. }
  19821. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19822. for ( i = 1; i < numpoints; i++ ) {
  19823. normals[ i ] = normals[ i-1 ].clone();
  19824. binormals[ i ] = binormals[ i-1 ].clone();
  19825. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19826. if ( vec.length() > epsilon ) {
  19827. vec.normalize();
  19828. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19829. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19830. }
  19831. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19832. }
  19833. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19834. if ( closed ) {
  19835. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19836. theta /= ( numpoints - 1 );
  19837. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19838. theta = -theta;
  19839. }
  19840. for ( i = 1; i < numpoints; i++ ) {
  19841. // twist a little...
  19842. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19843. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19844. }
  19845. }
  19846. };
  19847. /**
  19848. * @author clockworkgeek / https://github.com/clockworkgeek
  19849. * @author timothypratley / https://github.com/timothypratley
  19850. * @author WestLangley / http://github.com/WestLangley
  19851. */
  19852. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19853. THREE.Geometry.call( this );
  19854. radius = radius || 1;
  19855. detail = detail || 0;
  19856. var that = this;
  19857. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19858. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19859. }
  19860. var midpoints = [], p = this.vertices;
  19861. var f = [];
  19862. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19863. var v1 = p[ faces[ i ][ 0 ] ];
  19864. var v2 = p[ faces[ i ][ 1 ] ];
  19865. var v3 = p[ faces[ i ][ 2 ] ];
  19866. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19867. }
  19868. for ( var i = 0, l = f.length; i < l; i ++ ) {
  19869. subdivide(f[ i ], detail);
  19870. }
  19871. // Handle case when face straddles the seam
  19872. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19873. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19874. var x0 = uvs[ 0 ].x;
  19875. var x1 = uvs[ 1 ].x;
  19876. var x2 = uvs[ 2 ].x;
  19877. var max = Math.max( x0, Math.max( x1, x2 ) );
  19878. var min = Math.min( x0, Math.min( x1, x2 ) );
  19879. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19880. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19881. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19882. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19883. }
  19884. }
  19885. // Merge vertices
  19886. this.mergeVertices();
  19887. // Apply radius
  19888. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19889. this.vertices[ i ].multiplyScalar( radius );
  19890. }
  19891. // Project vector onto sphere's surface
  19892. function prepare( vector ) {
  19893. var vertex = vector.normalize().clone();
  19894. vertex.index = that.vertices.push( vertex ) - 1;
  19895. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19896. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19897. var v = inclination( vector ) / Math.PI + 0.5;
  19898. vertex.uv = new THREE.Vector2( u, 1 - v );
  19899. return vertex;
  19900. }
  19901. // Approximate a curved face with recursively sub-divided triangles.
  19902. function make( v1, v2, v3 ) {
  19903. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19904. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19905. face.normal.copy( face.centroid ).normalize();
  19906. that.faces.push( face );
  19907. var azi = azimuth( face.centroid );
  19908. that.faceVertexUvs[ 0 ].push( [
  19909. correctUV( v1.uv, v1, azi ),
  19910. correctUV( v2.uv, v2, azi ),
  19911. correctUV( v3.uv, v3, azi )
  19912. ] );
  19913. }
  19914. // Analytically subdivide a face to the required detail level.
  19915. function subdivide(face, detail ) {
  19916. var cols = Math.pow(2, detail);
  19917. var cells = Math.pow(4, detail);
  19918. var a = prepare( that.vertices[ face.a ] );
  19919. var b = prepare( that.vertices[ face.b ] );
  19920. var c = prepare( that.vertices[ face.c ] );
  19921. var v = [];
  19922. // Construct all of the vertices for this subdivision.
  19923. for ( var i = 0 ; i <= cols; i ++ ) {
  19924. v[ i ] = [];
  19925. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19926. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19927. var rows = cols - i;
  19928. for ( var j = 0; j <= rows; j ++) {
  19929. if ( j == 0 && i == cols ) {
  19930. v[ i ][ j ] = aj;
  19931. } else {
  19932. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19933. }
  19934. }
  19935. }
  19936. // Construct all of the faces.
  19937. for ( var i = 0; i < cols ; i ++ ) {
  19938. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19939. var k = Math.floor( j / 2 );
  19940. if ( j % 2 == 0 ) {
  19941. make(
  19942. v[ i ][ k + 1],
  19943. v[ i + 1 ][ k ],
  19944. v[ i ][ k ]
  19945. );
  19946. } else {
  19947. make(
  19948. v[ i ][ k + 1 ],
  19949. v[ i + 1][ k + 1],
  19950. v[ i + 1 ][ k ]
  19951. );
  19952. }
  19953. }
  19954. }
  19955. }
  19956. // Angle around the Y axis, counter-clockwise when looking from above.
  19957. function azimuth( vector ) {
  19958. return Math.atan2( vector.z, -vector.x );
  19959. }
  19960. // Angle above the XZ plane.
  19961. function inclination( vector ) {
  19962. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19963. }
  19964. // Texture fixing helper. Spheres have some odd behaviours.
  19965. function correctUV( uv, vector, azimuth ) {
  19966. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19967. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19968. return uv.clone();
  19969. }
  19970. this.computeCentroids();
  19971. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19972. };
  19973. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19974. /**
  19975. * @author timothypratley / https://github.com/timothypratley
  19976. */
  19977. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19978. this.radius = radius;
  19979. this.detail = detail;
  19980. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19981. var vertices = [
  19982. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19983. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19984. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19985. ];
  19986. var faces = [
  19987. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19988. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19989. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19990. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19991. ];
  19992. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19993. };
  19994. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19995. /**
  19996. * @author timothypratley / https://github.com/timothypratley
  19997. */
  19998. THREE.OctahedronGeometry = function ( radius, detail ) {
  19999. var vertices = [
  20000. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20001. ];
  20002. var faces = [
  20003. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20004. ];
  20005. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20006. };
  20007. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20008. /**
  20009. * @author timothypratley / https://github.com/timothypratley
  20010. */
  20011. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20012. var vertices = [
  20013. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20014. ];
  20015. var faces = [
  20016. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20017. ];
  20018. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20019. };
  20020. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20021. /**
  20022. * @author zz85 / https://github.com/zz85
  20023. * Parametric Surfaces Geometry
  20024. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20025. *
  20026. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  20027. *
  20028. */
  20029. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  20030. THREE.Geometry.call( this );
  20031. var verts = this.vertices;
  20032. var faces = this.faces;
  20033. var uvs = this.faceVertexUvs[ 0 ];
  20034. useTris = (useTris === undefined) ? false : useTris;
  20035. var i, il, j, p;
  20036. var u, v;
  20037. var stackCount = stacks + 1;
  20038. var sliceCount = slices + 1;
  20039. for ( i = 0; i <= stacks; i ++ ) {
  20040. v = i / stacks;
  20041. for ( j = 0; j <= slices; j ++ ) {
  20042. u = j / slices;
  20043. p = func( u, v );
  20044. verts.push( p );
  20045. }
  20046. }
  20047. var a, b, c, d;
  20048. var uva, uvb, uvc, uvd;
  20049. for ( i = 0; i < stacks; i ++ ) {
  20050. for ( j = 0; j < slices; j ++ ) {
  20051. a = i * sliceCount + j;
  20052. b = i * sliceCount + j + 1;
  20053. c = (i + 1) * sliceCount + j;
  20054. d = (i + 1) * sliceCount + j + 1;
  20055. uva = new THREE.Vector2( j / slices, i / stacks );
  20056. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20057. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20058. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20059. if ( useTris ) {
  20060. faces.push( new THREE.Face3( a, b, c ) );
  20061. faces.push( new THREE.Face3( b, d, c ) );
  20062. uvs.push( [ uva, uvb, uvc ] );
  20063. uvs.push( [ uvb, uvd, uvc ] );
  20064. } else {
  20065. faces.push( new THREE.Face4( a, b, d, c ) );
  20066. uvs.push( [ uva, uvb, uvd, uvc ] );
  20067. }
  20068. }
  20069. }
  20070. // console.log(this);
  20071. // magic bullet
  20072. // var diff = this.mergeVertices();
  20073. // console.log('removed ', diff, ' vertices by merging');
  20074. this.computeCentroids();
  20075. this.computeFaceNormals();
  20076. this.computeVertexNormals();
  20077. };
  20078. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20079. /**
  20080. * @author qiao / https://github.com/qiao
  20081. * @fileoverview This is a convex hull generator using the incremental method.
  20082. * The complexity is O(n^2) where n is the number of vertices.
  20083. * O(nlogn) algorithms do exist, but they are much more complicated.
  20084. *
  20085. * Benchmark:
  20086. *
  20087. * Platform: CPU: P7350 @2.00GHz Engine: V8
  20088. *
  20089. * Num Vertices Time(ms)
  20090. *
  20091. * 10 1
  20092. * 20 3
  20093. * 30 19
  20094. * 40 48
  20095. * 50 107
  20096. */
  20097. THREE.ConvexGeometry = function( vertices ) {
  20098. THREE.Geometry.call( this );
  20099. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  20100. for ( var i = 3; i < vertices.length; i++ ) {
  20101. addPoint( i );
  20102. }
  20103. function addPoint( vertexId ) {
  20104. var vertex = vertices[ vertexId ].clone();
  20105. var mag = vertex.length();
  20106. vertex.x += mag * randomOffset();
  20107. vertex.y += mag * randomOffset();
  20108. vertex.z += mag * randomOffset();
  20109. var hole = [];
  20110. for ( var f = 0; f < faces.length; ) {
  20111. var face = faces[ f ];
  20112. // for each face, if the vertex can see it,
  20113. // then we try to add the face's edges into the hole.
  20114. if ( visible( face, vertex ) ) {
  20115. for ( var e = 0; e < 3; e++ ) {
  20116. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20117. var boundary = true;
  20118. // remove duplicated edges.
  20119. for ( var h = 0; h < hole.length; h++ ) {
  20120. if ( equalEdge( hole[ h ], edge ) ) {
  20121. hole[ h ] = hole[ hole.length - 1 ];
  20122. hole.pop();
  20123. boundary = false;
  20124. break;
  20125. }
  20126. }
  20127. if ( boundary ) {
  20128. hole.push( edge );
  20129. }
  20130. }
  20131. // remove faces[ f ]
  20132. faces[ f ] = faces[ faces.length - 1 ];
  20133. faces.pop();
  20134. } else { // not visible
  20135. f++;
  20136. }
  20137. }
  20138. // construct the new faces formed by the edges of the hole and the vertex
  20139. for ( var h = 0; h < hole.length; h++ ) {
  20140. faces.push( [
  20141. hole[ h ][ 0 ],
  20142. hole[ h ][ 1 ],
  20143. vertexId
  20144. ] );
  20145. }
  20146. }
  20147. /**
  20148. * Whether the face is visible from the vertex
  20149. */
  20150. function visible( face, vertex ) {
  20151. var va = vertices[ face[ 0 ] ];
  20152. var vb = vertices[ face[ 1 ] ];
  20153. var vc = vertices[ face[ 2 ] ];
  20154. var n = normal( va, vb, vc );
  20155. // distance from face to origin
  20156. var dist = n.dot( va );
  20157. return n.dot( vertex ) >= dist;
  20158. }
  20159. /**
  20160. * Face normal
  20161. */
  20162. function normal( va, vb, vc ) {
  20163. var cb = new THREE.Vector3();
  20164. var ab = new THREE.Vector3();
  20165. cb.subVectors( vc, vb );
  20166. ab.subVectors( va, vb );
  20167. cb.cross( ab );
  20168. cb.normalize();
  20169. return cb;
  20170. }
  20171. /**
  20172. * Detect whether two edges are equal.
  20173. * Note that when constructing the convex hull, two same edges can only
  20174. * be of the negative direction.
  20175. */
  20176. function equalEdge( ea, eb ) {
  20177. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20178. }
  20179. /**
  20180. * Create a random offset between -1e-6 and 1e-6.
  20181. */
  20182. function randomOffset() {
  20183. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20184. }
  20185. /**
  20186. * XXX: Not sure if this is the correct approach. Need someone to review.
  20187. */
  20188. function vertexUv( vertex ) {
  20189. var mag = vertex.length();
  20190. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20191. }
  20192. // Push vertices into `this.vertices`, skipping those inside the hull
  20193. var id = 0;
  20194. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20195. for ( var i = 0; i < faces.length; i++ ) {
  20196. var face = faces[ i ];
  20197. for ( var j = 0; j < 3; j++ ) {
  20198. if ( newId[ face[ j ] ] === undefined ) {
  20199. newId[ face[ j ] ] = id++;
  20200. this.vertices.push( vertices[ face[ j ] ] );
  20201. }
  20202. face[ j ] = newId[ face[ j ] ];
  20203. }
  20204. }
  20205. // Convert faces into instances of THREE.Face3
  20206. for ( var i = 0; i < faces.length; i++ ) {
  20207. this.faces.push( new THREE.Face3(
  20208. faces[ i ][ 0 ],
  20209. faces[ i ][ 1 ],
  20210. faces[ i ][ 2 ]
  20211. ) );
  20212. }
  20213. // Compute UVs
  20214. for ( var i = 0; i < this.faces.length; i++ ) {
  20215. var face = this.faces[ i ];
  20216. this.faceVertexUvs[ 0 ].push( [
  20217. vertexUv( this.vertices[ face.a ] ),
  20218. vertexUv( this.vertices[ face.b ] ),
  20219. vertexUv( this.vertices[ face.c ])
  20220. ] );
  20221. }
  20222. this.computeCentroids();
  20223. this.computeFaceNormals();
  20224. this.computeVertexNormals();
  20225. };
  20226. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20227. /**
  20228. * @author sroucheray / http://sroucheray.org/
  20229. * @author mrdoob / http://mrdoob.com/
  20230. */
  20231. THREE.AxisHelper = function ( size ) {
  20232. size = size || 1;
  20233. var geometry = new THREE.Geometry();
  20234. geometry.vertices.push(
  20235. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20236. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20237. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20238. );
  20239. geometry.colors.push(
  20240. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20241. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20242. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20243. );
  20244. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20245. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20246. };
  20247. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20248. /**
  20249. * @author WestLangley / http://github.com/WestLangley
  20250. * @author zz85 / http://github.com/zz85
  20251. * @author bhouston / http://exocortex.com
  20252. *
  20253. * Creates an arrow for visualizing directions
  20254. *
  20255. * Parameters:
  20256. * dir - Vector3
  20257. * origin - Vector3
  20258. * length - Number
  20259. * hex - color in hex value
  20260. */
  20261. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20262. // dir is assumed to be normalized
  20263. THREE.Object3D.call( this );
  20264. if ( hex === undefined ) hex = 0xffff00;
  20265. if ( length === undefined ) length = 1;
  20266. this.position = origin;
  20267. this.useQuaternion = true;
  20268. var lineGeometry = new THREE.Geometry();
  20269. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20270. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20271. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20272. this.line.matrixAutoUpdate = false;
  20273. this.add( this.line );
  20274. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20275. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20276. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20277. this.cone.matrixAutoUpdate = false;
  20278. this.add( this.cone );
  20279. this.setDirection( dir );
  20280. this.setLength( length );
  20281. };
  20282. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20283. THREE.ArrowHelper.prototype.setDirection = function () {
  20284. var axis = new THREE.Vector3();
  20285. var radians;
  20286. return function ( dir ) {
  20287. // dir is assumed to be normalized
  20288. if ( dir.y > 0.999 ) {
  20289. this.quaternion.set( 0, 0, 0, 1 );
  20290. } else if ( dir.y < - 0.999 ) {
  20291. this.quaternion.set( 1, 0, 0, 0 );
  20292. } else {
  20293. axis.set( dir.z, 0, - dir.x ).normalize();
  20294. radians = Math.acos( dir.y );
  20295. this.quaternion.setFromAxisAngle( axis, radians );
  20296. }
  20297. };
  20298. }();
  20299. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20300. this.scale.set( length, length, length );
  20301. };
  20302. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20303. this.line.material.color.setHex( hex );
  20304. this.cone.material.color.setHex( hex );
  20305. };
  20306. /**
  20307. * @author mrdoob / http://mrdoob.com/
  20308. */
  20309. THREE.BoxHelper = function ( size ) {
  20310. size = size || 1;
  20311. var geometry = new THREE.Geometry();
  20312. // 5____4
  20313. // 1/___0/|
  20314. // | 6__|_7
  20315. // 2/___3/
  20316. var vertices = [
  20317. new THREE.Vector3( size, size, size ),
  20318. new THREE.Vector3( - size, size, size ),
  20319. new THREE.Vector3( - size, - size, size ),
  20320. new THREE.Vector3( size, - size, size ),
  20321. new THREE.Vector3( size, size, - size ),
  20322. new THREE.Vector3( - size, size, - size ),
  20323. new THREE.Vector3( - size, - size, - size ),
  20324. new THREE.Vector3( size, - size, - size )
  20325. ];
  20326. // TODO: Wouldn't be nice if Line had .segments?
  20327. geometry.vertices.push(
  20328. vertices[ 0 ], vertices[ 1 ],
  20329. vertices[ 1 ], vertices[ 2 ],
  20330. vertices[ 2 ], vertices[ 3 ],
  20331. vertices[ 3 ], vertices[ 0 ],
  20332. vertices[ 4 ], vertices[ 5 ],
  20333. vertices[ 5 ], vertices[ 6 ],
  20334. vertices[ 6 ], vertices[ 7 ],
  20335. vertices[ 7 ], vertices[ 4 ],
  20336. vertices[ 0 ], vertices[ 4 ],
  20337. vertices[ 1 ], vertices[ 5 ],
  20338. vertices[ 2 ], vertices[ 6 ],
  20339. vertices[ 3 ], vertices[ 7 ]
  20340. );
  20341. this.vertices = vertices;
  20342. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial(), THREE.LinePieces );
  20343. };
  20344. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20345. THREE.BoxHelper.prototype.update = function ( object ) {
  20346. var geometry = object.geometry;
  20347. if ( geometry.boundingBox === null ) {
  20348. geometry.computeBoundingBox();
  20349. }
  20350. var min = geometry.boundingBox.min;
  20351. var max = geometry.boundingBox.max;
  20352. var vertices = this.vertices;
  20353. vertices[ 0 ].set( max.x, max.y, max.z );
  20354. vertices[ 1 ].set( min.x, max.y, max.z );
  20355. vertices[ 2 ].set( min.x, min.y, max.z );
  20356. vertices[ 3 ].set( max.x, min.y, max.z );
  20357. vertices[ 4 ].set( max.x, max.y, min.z );
  20358. vertices[ 5 ].set( min.x, max.y, min.z );
  20359. vertices[ 6 ].set( min.x, min.y, min.z );
  20360. vertices[ 7 ].set( max.x, min.y, min.z );
  20361. this.geometry.computeBoundingSphere();
  20362. this.geometry.verticesNeedUpdate = true;
  20363. this.matrixAutoUpdate = false;
  20364. this.matrixWorld = object.matrixWorld;
  20365. };
  20366. /**
  20367. * @author alteredq / http://alteredqualia.com/
  20368. *
  20369. * - shows frustum, line of sight and up of the camera
  20370. * - suitable for fast updates
  20371. * - based on frustum visualization in lightgl.js shadowmap example
  20372. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20373. */
  20374. THREE.CameraHelper = function ( camera ) {
  20375. THREE.Line.call( this );
  20376. var geometry = new THREE.Geometry();
  20377. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20378. var pointMap = {};
  20379. // colors
  20380. var hexFrustum = 0xffaa00;
  20381. var hexCone = 0xff0000;
  20382. var hexUp = 0x00aaff;
  20383. var hexTarget = 0xffffff;
  20384. var hexCross = 0x333333;
  20385. // near
  20386. addLine( "n1", "n2", hexFrustum );
  20387. addLine( "n2", "n4", hexFrustum );
  20388. addLine( "n4", "n3", hexFrustum );
  20389. addLine( "n3", "n1", hexFrustum );
  20390. // far
  20391. addLine( "f1", "f2", hexFrustum );
  20392. addLine( "f2", "f4", hexFrustum );
  20393. addLine( "f4", "f3", hexFrustum );
  20394. addLine( "f3", "f1", hexFrustum );
  20395. // sides
  20396. addLine( "n1", "f1", hexFrustum );
  20397. addLine( "n2", "f2", hexFrustum );
  20398. addLine( "n3", "f3", hexFrustum );
  20399. addLine( "n4", "f4", hexFrustum );
  20400. // cone
  20401. addLine( "p", "n1", hexCone );
  20402. addLine( "p", "n2", hexCone );
  20403. addLine( "p", "n3", hexCone );
  20404. addLine( "p", "n4", hexCone );
  20405. // up
  20406. addLine( "u1", "u2", hexUp );
  20407. addLine( "u2", "u3", hexUp );
  20408. addLine( "u3", "u1", hexUp );
  20409. // target
  20410. addLine( "c", "t", hexTarget );
  20411. addLine( "p", "c", hexCross );
  20412. // cross
  20413. addLine( "cn1", "cn2", hexCross );
  20414. addLine( "cn3", "cn4", hexCross );
  20415. addLine( "cf1", "cf2", hexCross );
  20416. addLine( "cf3", "cf4", hexCross );
  20417. function addLine( a, b, hex ) {
  20418. addPoint( a, hex );
  20419. addPoint( b, hex );
  20420. }
  20421. function addPoint( id, hex ) {
  20422. geometry.vertices.push( new THREE.Vector3() );
  20423. geometry.colors.push( new THREE.Color( hex ) );
  20424. if ( pointMap[ id ] === undefined ) {
  20425. pointMap[ id ] = [];
  20426. }
  20427. pointMap[ id ].push( geometry.vertices.length - 1 );
  20428. }
  20429. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20430. this.camera = camera;
  20431. this.matrixWorld = camera.matrixWorld;
  20432. this.matrixAutoUpdate = false;
  20433. this.pointMap = pointMap;
  20434. this.update();
  20435. };
  20436. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20437. THREE.CameraHelper.prototype.update = function () {
  20438. var vector = new THREE.Vector3();
  20439. var camera = new THREE.Camera();
  20440. var projector = new THREE.Projector();
  20441. return function () {
  20442. var scope = this;
  20443. var w = 1, h = 1;
  20444. // we need just camera projection matrix
  20445. // world matrix must be identity
  20446. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20447. // center / target
  20448. setPoint( "c", 0, 0, -1 );
  20449. setPoint( "t", 0, 0, 1 );
  20450. // near
  20451. setPoint( "n1", -w, -h, -1 );
  20452. setPoint( "n2", w, -h, -1 );
  20453. setPoint( "n3", -w, h, -1 );
  20454. setPoint( "n4", w, h, -1 );
  20455. // far
  20456. setPoint( "f1", -w, -h, 1 );
  20457. setPoint( "f2", w, -h, 1 );
  20458. setPoint( "f3", -w, h, 1 );
  20459. setPoint( "f4", w, h, 1 );
  20460. // up
  20461. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20462. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20463. setPoint( "u3", 0, h * 2, -1 );
  20464. // cross
  20465. setPoint( "cf1", -w, 0, 1 );
  20466. setPoint( "cf2", w, 0, 1 );
  20467. setPoint( "cf3", 0, -h, 1 );
  20468. setPoint( "cf4", 0, h, 1 );
  20469. setPoint( "cn1", -w, 0, -1 );
  20470. setPoint( "cn2", w, 0, -1 );
  20471. setPoint( "cn3", 0, -h, -1 );
  20472. setPoint( "cn4", 0, h, -1 );
  20473. function setPoint( point, x, y, z ) {
  20474. vector.set( x, y, z );
  20475. projector.unprojectVector( vector, camera );
  20476. var points = scope.pointMap[ point ];
  20477. if ( points !== undefined ) {
  20478. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20479. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20480. }
  20481. }
  20482. }
  20483. this.geometry.verticesNeedUpdate = true;
  20484. };
  20485. }();
  20486. /**
  20487. * @author alteredq / http://alteredqualia.com/
  20488. * @author mrdoob / http://mrdoob.com/
  20489. */
  20490. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20491. THREE.Object3D.call( this );
  20492. this.matrixAutoUpdate = false;
  20493. this.light = light;
  20494. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20495. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20496. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20497. this.lightSphere = new THREE.Mesh( geometry, material );
  20498. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20499. this.lightSphere.matrixAutoUpdate = false;
  20500. this.add( this.lightSphere );
  20501. /*
  20502. this.targetSphere = new THREE.Mesh( geometry, material );
  20503. this.targetSphere.position = this.light.target.position;
  20504. this.add( this.targetSphere );
  20505. */
  20506. geometry = new THREE.Geometry();
  20507. geometry.vertices.push( this.light.position );
  20508. geometry.vertices.push( this.light.target.position );
  20509. geometry.computeLineDistances();
  20510. material = new THREE.LineDashedMaterial( { dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20511. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20512. this.targetLine = new THREE.Line( geometry, material );
  20513. this.add( this.targetLine );
  20514. }
  20515. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20516. THREE.DirectionalLightHelper.prototype.update = function () {
  20517. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20518. this.targetLine.geometry.computeLineDistances();
  20519. this.targetLine.geometry.verticesNeedUpdate = true;
  20520. this.targetLine.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20521. };
  20522. /**
  20523. * @author mrdoob / http://mrdoob.com/
  20524. */
  20525. THREE.GridHelper = function ( size, step ) {
  20526. var geometry = new THREE.Geometry();
  20527. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20528. var color1 = new THREE.Color( 0x444444 ), color2 = new THREE.Color( 0x888888 );
  20529. for ( var i = - size; i <= size; i += step ) {
  20530. geometry.vertices.push( new THREE.Vector3( -size, 0, i ) );
  20531. geometry.vertices.push( new THREE.Vector3( size, 0, i ) );
  20532. geometry.vertices.push( new THREE.Vector3( i, 0, -size ) );
  20533. geometry.vertices.push( new THREE.Vector3( i, 0, size ) );
  20534. var color = i === 0 ? color1 : color2;
  20535. geometry.colors.push( color, color, color, color );
  20536. }
  20537. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20538. };
  20539. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20540. /**
  20541. * @author alteredq / http://alteredqualia.com/
  20542. * @author mrdoob / http://mrdoob.com/
  20543. */
  20544. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20545. THREE.Object3D.call( this );
  20546. this.light = light;
  20547. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20548. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20549. for ( var i = 0, il = 8; i < il; i ++ ) {
  20550. geometry.faces[ i ].materialIndex = i < 4 ? 0 : 1;
  20551. }
  20552. var materialSky = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20553. materialSky.color.copy( light.color ).multiplyScalar( light.intensity );
  20554. var materialGround = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20555. materialGround.color.copy( light.groundColor ).multiplyScalar( light.intensity );
  20556. this.lightSphere = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ materialSky, materialGround ] ) );
  20557. this.lightSphere.position = light.position;
  20558. this.lightSphere.lookAt( new THREE.Vector3() );
  20559. this.add( this.lightSphere );
  20560. };
  20561. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20562. THREE.HemisphereLightHelper.prototype.update = function () {
  20563. this.lightSphere.lookAt( new THREE.Vector3() );
  20564. this.lightSphere.material.materials[ 0 ].color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20565. this.lightSphere.material.materials[ 1 ].color.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20566. };
  20567. /**
  20568. * @author alteredq / http://alteredqualia.com/
  20569. * @author mrdoob / http://mrdoob.com/
  20570. */
  20571. THREE.PointLightHelper = function ( light, sphereSize ) {
  20572. THREE.Object3D.call( this );
  20573. this.matrixAutoUpdate = false;
  20574. this.light = light;
  20575. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20576. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20577. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20578. this.lightSphere = new THREE.Mesh( geometry, material );
  20579. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20580. this.lightSphere.matrixAutoUpdate = false;
  20581. this.add( this.lightSphere );
  20582. /*
  20583. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20584. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20585. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20586. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20587. var d = light.distance;
  20588. if ( d === 0.0 ) {
  20589. this.lightDistance.visible = false;
  20590. } else {
  20591. this.lightDistance.scale.set( d, d, d );
  20592. }
  20593. this.add( this.lightDistance );
  20594. */
  20595. };
  20596. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20597. THREE.PointLightHelper.prototype.update = function () {
  20598. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20599. /*
  20600. this.lightDistance.material.color.copy( this.color );
  20601. var d = this.light.distance;
  20602. if ( d === 0.0 ) {
  20603. this.lightDistance.visible = false;
  20604. } else {
  20605. this.lightDistance.visible = true;
  20606. this.lightDistance.scale.set( d, d, d );
  20607. }
  20608. */
  20609. };
  20610. /**
  20611. * @author alteredq / http://alteredqualia.com/
  20612. * @author mrdoob / http://mrdoob.com/
  20613. * @author WestLangley / http://github.com/WestLangley
  20614. */
  20615. THREE.SpotLightHelper = function ( light, sphereSize ) {
  20616. THREE.Object3D.call( this );
  20617. this.matrixAutoUpdate = false;
  20618. this.light = light;
  20619. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20620. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20621. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20622. this.lightSphere = new THREE.Mesh( geometry, material );
  20623. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20624. this.lightSphere.matrixAutoUpdate = false;
  20625. this.add( this.lightSphere );
  20626. geometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20627. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20628. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20629. material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20630. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20631. this.lightCone = new THREE.Mesh( geometry, material );
  20632. this.lightCone.position = this.light.position;
  20633. var coneLength = light.distance ? light.distance : 10000;
  20634. var coneWidth = coneLength * Math.tan( light.angle );
  20635. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20636. this.lightCone.lookAt( this.light.target.position );
  20637. this.add( this.lightCone );
  20638. };
  20639. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20640. THREE.SpotLightHelper.prototype.update = function () {
  20641. var coneLength = this.light.distance ? this.light.distance : 10000;
  20642. var coneWidth = coneLength * Math.tan( this.light.angle );
  20643. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20644. this.lightCone.lookAt( this.light.target.position );
  20645. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20646. this.lightCone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20647. };
  20648. /**
  20649. * @author alteredq / http://alteredqualia.com/
  20650. */
  20651. THREE.ImmediateRenderObject = function () {
  20652. THREE.Object3D.call( this );
  20653. this.render = function ( renderCallback ) { };
  20654. };
  20655. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20656. /**
  20657. * @author mikael emtinger / http://gomo.se/
  20658. * @author alteredq / http://alteredqualia.com/
  20659. */
  20660. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20661. THREE.Object3D.call( this );
  20662. this.lensFlares = [];
  20663. this.positionScreen = new THREE.Vector3();
  20664. this.customUpdateCallback = undefined;
  20665. if( texture !== undefined ) {
  20666. this.add( texture, size, distance, blending, color );
  20667. }
  20668. };
  20669. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20670. /*
  20671. * Add: adds another flare
  20672. */
  20673. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20674. if( size === undefined ) size = -1;
  20675. if( distance === undefined ) distance = 0;
  20676. if( opacity === undefined ) opacity = 1;
  20677. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20678. if( blending === undefined ) blending = THREE.NormalBlending;
  20679. distance = Math.min( distance, Math.max( 0, distance ) );
  20680. this.lensFlares.push( { texture: texture, // THREE.Texture
  20681. size: size, // size in pixels (-1 = use texture.width)
  20682. distance: distance, // distance (0-1) from light source (0=at light source)
  20683. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20684. scale: 1, // scale
  20685. rotation: 1, // rotation
  20686. opacity: opacity, // opacity
  20687. color: color, // color
  20688. blending: blending } ); // blending
  20689. };
  20690. /*
  20691. * Update lens flares update positions on all flares based on the screen position
  20692. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20693. */
  20694. THREE.LensFlare.prototype.updateLensFlares = function () {
  20695. var f, fl = this.lensFlares.length;
  20696. var flare;
  20697. var vecX = -this.positionScreen.x * 2;
  20698. var vecY = -this.positionScreen.y * 2;
  20699. for( f = 0; f < fl; f ++ ) {
  20700. flare = this.lensFlares[ f ];
  20701. flare.x = this.positionScreen.x + vecX * flare.distance;
  20702. flare.y = this.positionScreen.y + vecY * flare.distance;
  20703. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20704. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20705. }
  20706. };
  20707. /**
  20708. * @author alteredq / http://alteredqualia.com/
  20709. */
  20710. THREE.MorphBlendMesh = function( geometry, material ) {
  20711. THREE.Mesh.call( this, geometry, material );
  20712. this.animationsMap = {};
  20713. this.animationsList = [];
  20714. // prepare default animation
  20715. // (all frames played together in 1 second)
  20716. var numFrames = this.geometry.morphTargets.length;
  20717. var name = "__default";
  20718. var startFrame = 0;
  20719. var endFrame = numFrames - 1;
  20720. var fps = numFrames / 1;
  20721. this.createAnimation( name, startFrame, endFrame, fps );
  20722. this.setAnimationWeight( name, 1 );
  20723. };
  20724. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20725. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20726. var animation = {
  20727. startFrame: start,
  20728. endFrame: end,
  20729. length: end - start + 1,
  20730. fps: fps,
  20731. duration: ( end - start ) / fps,
  20732. lastFrame: 0,
  20733. currentFrame: 0,
  20734. active: false,
  20735. time: 0,
  20736. direction: 1,
  20737. weight: 1,
  20738. directionBackwards: false,
  20739. mirroredLoop: false
  20740. };
  20741. this.animationsMap[ name ] = animation;
  20742. this.animationsList.push( animation );
  20743. };
  20744. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20745. var pattern = /([a-z]+)(\d+)/;
  20746. var firstAnimation, frameRanges = {};
  20747. var geometry = this.geometry;
  20748. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20749. var morph = geometry.morphTargets[ i ];
  20750. var chunks = morph.name.match( pattern );
  20751. if ( chunks && chunks.length > 1 ) {
  20752. var name = chunks[ 1 ];
  20753. var num = chunks[ 2 ];
  20754. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20755. var range = frameRanges[ name ];
  20756. if ( i < range.start ) range.start = i;
  20757. if ( i > range.end ) range.end = i;
  20758. if ( ! firstAnimation ) firstAnimation = name;
  20759. }
  20760. }
  20761. for ( var name in frameRanges ) {
  20762. var range = frameRanges[ name ];
  20763. this.createAnimation( name, range.start, range.end, fps );
  20764. }
  20765. this.firstAnimation = firstAnimation;
  20766. };
  20767. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20768. var animation = this.animationsMap[ name ];
  20769. if ( animation ) {
  20770. animation.direction = 1;
  20771. animation.directionBackwards = false;
  20772. }
  20773. };
  20774. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20775. var animation = this.animationsMap[ name ];
  20776. if ( animation ) {
  20777. animation.direction = -1;
  20778. animation.directionBackwards = true;
  20779. }
  20780. };
  20781. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20782. var animation = this.animationsMap[ name ];
  20783. if ( animation ) {
  20784. animation.fps = fps;
  20785. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20786. }
  20787. };
  20788. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20789. var animation = this.animationsMap[ name ];
  20790. if ( animation ) {
  20791. animation.duration = duration;
  20792. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20793. }
  20794. };
  20795. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20796. var animation = this.animationsMap[ name ];
  20797. if ( animation ) {
  20798. animation.weight = weight;
  20799. }
  20800. };
  20801. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20802. var animation = this.animationsMap[ name ];
  20803. if ( animation ) {
  20804. animation.time = time;
  20805. }
  20806. };
  20807. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20808. var time = 0;
  20809. var animation = this.animationsMap[ name ];
  20810. if ( animation ) {
  20811. time = animation.time;
  20812. }
  20813. return time;
  20814. };
  20815. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20816. var duration = -1;
  20817. var animation = this.animationsMap[ name ];
  20818. if ( animation ) {
  20819. duration = animation.duration;
  20820. }
  20821. return duration;
  20822. };
  20823. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20824. var animation = this.animationsMap[ name ];
  20825. if ( animation ) {
  20826. animation.time = 0;
  20827. animation.active = true;
  20828. } else {
  20829. console.warn( "animation[" + name + "] undefined" );
  20830. }
  20831. };
  20832. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20833. var animation = this.animationsMap[ name ];
  20834. if ( animation ) {
  20835. animation.active = false;
  20836. }
  20837. };
  20838. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20839. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20840. var animation = this.animationsList[ i ];
  20841. if ( ! animation.active ) continue;
  20842. var frameTime = animation.duration / animation.length;
  20843. animation.time += animation.direction * delta;
  20844. if ( animation.mirroredLoop ) {
  20845. if ( animation.time > animation.duration || animation.time < 0 ) {
  20846. animation.direction *= -1;
  20847. if ( animation.time > animation.duration ) {
  20848. animation.time = animation.duration;
  20849. animation.directionBackwards = true;
  20850. }
  20851. if ( animation.time < 0 ) {
  20852. animation.time = 0;
  20853. animation.directionBackwards = false;
  20854. }
  20855. }
  20856. } else {
  20857. animation.time = animation.time % animation.duration;
  20858. if ( animation.time < 0 ) animation.time += animation.duration;
  20859. }
  20860. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20861. var weight = animation.weight;
  20862. if ( keyframe !== animation.currentFrame ) {
  20863. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20864. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20865. this.morphTargetInfluences[ keyframe ] = 0;
  20866. animation.lastFrame = animation.currentFrame;
  20867. animation.currentFrame = keyframe;
  20868. }
  20869. var mix = ( animation.time % frameTime ) / frameTime;
  20870. if ( animation.directionBackwards ) mix = 1 - mix;
  20871. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20872. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20873. }
  20874. };
  20875. /**
  20876. * @author mikael emtinger / http://gomo.se/
  20877. * @author alteredq / http://alteredqualia.com/
  20878. */
  20879. THREE.LensFlarePlugin = function () {
  20880. var _gl, _renderer, _precision, _lensFlare = {};
  20881. this.init = function ( renderer ) {
  20882. _gl = renderer.context;
  20883. _renderer = renderer;
  20884. _precision = renderer.getPrecision();
  20885. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20886. _lensFlare.faces = new Uint16Array( 6 );
  20887. var i = 0;
  20888. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20889. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20890. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20891. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20892. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20893. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20894. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20895. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20896. i = 0;
  20897. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20898. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20899. // buffers
  20900. _lensFlare.vertexBuffer = _gl.createBuffer();
  20901. _lensFlare.elementBuffer = _gl.createBuffer();
  20902. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20903. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20904. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20905. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20906. // textures
  20907. _lensFlare.tempTexture = _gl.createTexture();
  20908. _lensFlare.occlusionTexture = _gl.createTexture();
  20909. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20910. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20911. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20912. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20913. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20914. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20915. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20916. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20917. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20918. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20919. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20920. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20921. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20922. _lensFlare.hasVertexTexture = false;
  20923. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  20924. } else {
  20925. _lensFlare.hasVertexTexture = true;
  20926. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  20927. }
  20928. _lensFlare.attributes = {};
  20929. _lensFlare.uniforms = {};
  20930. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20931. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20932. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20933. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20934. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20935. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20936. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20937. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20938. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20939. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20940. };
  20941. /*
  20942. * Render lens flares
  20943. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20944. * reads these back and calculates occlusion.
  20945. * Then _lensFlare.update_lensFlares() is called to re-position and
  20946. * update transparency of flares. Then they are rendered.
  20947. *
  20948. */
  20949. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20950. var flares = scene.__webglFlares,
  20951. nFlares = flares.length;
  20952. if ( ! nFlares ) return;
  20953. var tempPosition = new THREE.Vector3();
  20954. var invAspect = viewportHeight / viewportWidth,
  20955. halfViewportWidth = viewportWidth * 0.5,
  20956. halfViewportHeight = viewportHeight * 0.5;
  20957. var size = 16 / viewportHeight,
  20958. scale = new THREE.Vector2( size * invAspect, size );
  20959. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20960. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20961. var uniforms = _lensFlare.uniforms,
  20962. attributes = _lensFlare.attributes;
  20963. // set _lensFlare program and reset blending
  20964. _gl.useProgram( _lensFlare.program );
  20965. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20966. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20967. // loop through all lens flares to update their occlusion and positions
  20968. // setup gl and common used attribs/unforms
  20969. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20970. _gl.uniform1i( uniforms.map, 1 );
  20971. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20972. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20973. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20974. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20975. _gl.disable( _gl.CULL_FACE );
  20976. _gl.depthMask( false );
  20977. var i, j, jl, flare, sprite;
  20978. for ( i = 0; i < nFlares; i ++ ) {
  20979. size = 16 / viewportHeight;
  20980. scale.set( size * invAspect, size );
  20981. // calc object screen position
  20982. flare = flares[ i ];
  20983. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20984. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  20985. tempPosition.applyProjection( camera.projectionMatrix );
  20986. // setup arrays for gl programs
  20987. screenPosition.copy( tempPosition )
  20988. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20989. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20990. // screen cull
  20991. if ( _lensFlare.hasVertexTexture || (
  20992. screenPositionPixels.x > 0 &&
  20993. screenPositionPixels.x < viewportWidth &&
  20994. screenPositionPixels.y > 0 &&
  20995. screenPositionPixels.y < viewportHeight ) ) {
  20996. // save current RGB to temp texture
  20997. _gl.activeTexture( _gl.TEXTURE1 );
  20998. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20999. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21000. // render pink quad
  21001. _gl.uniform1i( uniforms.renderType, 0 );
  21002. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21003. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21004. _gl.disable( _gl.BLEND );
  21005. _gl.enable( _gl.DEPTH_TEST );
  21006. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21007. // copy result to occlusionMap
  21008. _gl.activeTexture( _gl.TEXTURE0 );
  21009. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21010. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21011. // restore graphics
  21012. _gl.uniform1i( uniforms.renderType, 1 );
  21013. _gl.disable( _gl.DEPTH_TEST );
  21014. _gl.activeTexture( _gl.TEXTURE1 );
  21015. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21016. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21017. // update object positions
  21018. flare.positionScreen.copy( screenPosition )
  21019. if ( flare.customUpdateCallback ) {
  21020. flare.customUpdateCallback( flare );
  21021. } else {
  21022. flare.updateLensFlares();
  21023. }
  21024. // render flares
  21025. _gl.uniform1i( uniforms.renderType, 2 );
  21026. _gl.enable( _gl.BLEND );
  21027. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21028. sprite = flare.lensFlares[ j ];
  21029. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21030. screenPosition.x = sprite.x;
  21031. screenPosition.y = sprite.y;
  21032. screenPosition.z = sprite.z;
  21033. size = sprite.size * sprite.scale / viewportHeight;
  21034. scale.x = size * invAspect;
  21035. scale.y = size;
  21036. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21037. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21038. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21039. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21040. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21041. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21042. _renderer.setTexture( sprite.texture, 1 );
  21043. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21044. }
  21045. }
  21046. }
  21047. }
  21048. // restore gl
  21049. _gl.enable( _gl.CULL_FACE );
  21050. _gl.enable( _gl.DEPTH_TEST );
  21051. _gl.depthMask( true );
  21052. };
  21053. function createProgram ( shader, precision ) {
  21054. var program = _gl.createProgram();
  21055. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21056. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21057. var prefix = "precision " + precision + " float;\n";
  21058. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21059. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21060. _gl.compileShader( fragmentShader );
  21061. _gl.compileShader( vertexShader );
  21062. _gl.attachShader( program, fragmentShader );
  21063. _gl.attachShader( program, vertexShader );
  21064. _gl.linkProgram( program );
  21065. return program;
  21066. };
  21067. };
  21068. /**
  21069. * @author alteredq / http://alteredqualia.com/
  21070. */
  21071. THREE.ShadowMapPlugin = function () {
  21072. var _gl,
  21073. _renderer,
  21074. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21075. _frustum = new THREE.Frustum(),
  21076. _projScreenMatrix = new THREE.Matrix4(),
  21077. _min = new THREE.Vector3(),
  21078. _max = new THREE.Vector3(),
  21079. _matrixPosition = new THREE.Vector3();
  21080. this.init = function ( renderer ) {
  21081. _gl = renderer.context;
  21082. _renderer = renderer;
  21083. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21084. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21085. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21086. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21087. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21088. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21089. _depthMaterial._shadowPass = true;
  21090. _depthMaterialMorph._shadowPass = true;
  21091. _depthMaterialSkin._shadowPass = true;
  21092. _depthMaterialMorphSkin._shadowPass = true;
  21093. };
  21094. this.render = function ( scene, camera ) {
  21095. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21096. this.update( scene, camera );
  21097. };
  21098. this.update = function ( scene, camera ) {
  21099. var i, il, j, jl, n,
  21100. shadowMap, shadowMatrix, shadowCamera,
  21101. program, buffer, material,
  21102. webglObject, object, light,
  21103. renderList,
  21104. lights = [],
  21105. k = 0,
  21106. fog = null;
  21107. // set GL state for depth map
  21108. _gl.clearColor( 1, 1, 1, 1 );
  21109. _gl.disable( _gl.BLEND );
  21110. _gl.enable( _gl.CULL_FACE );
  21111. _gl.frontFace( _gl.CCW );
  21112. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21113. _gl.cullFace( _gl.FRONT );
  21114. } else {
  21115. _gl.cullFace( _gl.BACK );
  21116. }
  21117. _renderer.setDepthTest( true );
  21118. // preprocess lights
  21119. // - skip lights that are not casting shadows
  21120. // - create virtual lights for cascaded shadow maps
  21121. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21122. light = scene.__lights[ i ];
  21123. if ( ! light.castShadow ) continue;
  21124. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21125. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21126. var virtualLight;
  21127. if ( ! light.shadowCascadeArray[ n ] ) {
  21128. virtualLight = createVirtualLight( light, n );
  21129. virtualLight.originalCamera = camera;
  21130. var gyro = new THREE.Gyroscope();
  21131. gyro.position = light.shadowCascadeOffset;
  21132. gyro.add( virtualLight );
  21133. gyro.add( virtualLight.target );
  21134. camera.add( gyro );
  21135. light.shadowCascadeArray[ n ] = virtualLight;
  21136. console.log( "Created virtualLight", virtualLight );
  21137. } else {
  21138. virtualLight = light.shadowCascadeArray[ n ];
  21139. }
  21140. updateVirtualLight( light, n );
  21141. lights[ k ] = virtualLight;
  21142. k ++;
  21143. }
  21144. } else {
  21145. lights[ k ] = light;
  21146. k ++;
  21147. }
  21148. }
  21149. // render depth map
  21150. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21151. light = lights[ i ];
  21152. if ( ! light.shadowMap ) {
  21153. var shadowFilter = THREE.LinearFilter;
  21154. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21155. shadowFilter = THREE.NearestFilter;
  21156. }
  21157. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21158. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21159. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21160. light.shadowMatrix = new THREE.Matrix4();
  21161. }
  21162. if ( ! light.shadowCamera ) {
  21163. if ( light instanceof THREE.SpotLight ) {
  21164. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21165. } else if ( light instanceof THREE.DirectionalLight ) {
  21166. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21167. } else {
  21168. console.error( "Unsupported light type for shadow" );
  21169. continue;
  21170. }
  21171. scene.add( light.shadowCamera );
  21172. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21173. }
  21174. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21175. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21176. light.shadowCamera.add( light.cameraHelper );
  21177. }
  21178. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21179. updateShadowCamera( camera, light );
  21180. }
  21181. shadowMap = light.shadowMap;
  21182. shadowMatrix = light.shadowMatrix;
  21183. shadowCamera = light.shadowCamera;
  21184. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21185. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21186. shadowCamera.lookAt( _matrixPosition );
  21187. shadowCamera.updateMatrixWorld();
  21188. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21189. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21190. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21191. // compute shadow matrix
  21192. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21193. 0.0, 0.5, 0.0, 0.5,
  21194. 0.0, 0.0, 0.5, 0.5,
  21195. 0.0, 0.0, 0.0, 1.0 );
  21196. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21197. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21198. // update camera matrices and frustum
  21199. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21200. _frustum.setFromMatrix( _projScreenMatrix );
  21201. // render shadow map
  21202. _renderer.setRenderTarget( shadowMap );
  21203. _renderer.clear();
  21204. // set object matrices & frustum culling
  21205. renderList = scene.__webglObjects;
  21206. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21207. webglObject = renderList[ j ];
  21208. object = webglObject.object;
  21209. webglObject.render = false;
  21210. if ( object.visible && object.castShadow ) {
  21211. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21212. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21213. webglObject.render = true;
  21214. }
  21215. }
  21216. }
  21217. // render regular objects
  21218. var objectMaterial, useMorphing, useSkinning;
  21219. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21220. webglObject = renderList[ j ];
  21221. if ( webglObject.render ) {
  21222. object = webglObject.object;
  21223. buffer = webglObject.buffer;
  21224. // culling is overriden globally for all objects
  21225. // while rendering depth map
  21226. // need to deal with MeshFaceMaterial somehow
  21227. // in that case just use the first of material.materials for now
  21228. // (proper solution would require to break objects by materials
  21229. // similarly to regular rendering and then set corresponding
  21230. // depth materials per each chunk instead of just once per object)
  21231. objectMaterial = getObjectMaterial( object );
  21232. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21233. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21234. if ( object.customDepthMaterial ) {
  21235. material = object.customDepthMaterial;
  21236. } else if ( useSkinning ) {
  21237. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21238. } else if ( useMorphing ) {
  21239. material = _depthMaterialMorph;
  21240. } else {
  21241. material = _depthMaterial;
  21242. }
  21243. if ( buffer instanceof THREE.BufferGeometry ) {
  21244. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21245. } else {
  21246. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21247. }
  21248. }
  21249. }
  21250. // set matrices and render immediate objects
  21251. renderList = scene.__webglObjectsImmediate;
  21252. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21253. webglObject = renderList[ j ];
  21254. object = webglObject.object;
  21255. if ( object.visible && object.castShadow ) {
  21256. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21257. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21258. }
  21259. }
  21260. }
  21261. // restore GL state
  21262. var clearColor = _renderer.getClearColor(),
  21263. clearAlpha = _renderer.getClearAlpha();
  21264. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21265. _gl.enable( _gl.BLEND );
  21266. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21267. _gl.cullFace( _gl.BACK );
  21268. }
  21269. };
  21270. function createVirtualLight( light, cascade ) {
  21271. var virtualLight = new THREE.DirectionalLight();
  21272. virtualLight.isVirtual = true;
  21273. virtualLight.onlyShadow = true;
  21274. virtualLight.castShadow = true;
  21275. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21276. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21277. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21278. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21279. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21280. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21281. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21282. virtualLight.shadowDarkness = light.shadowDarkness;
  21283. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21284. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21285. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21286. virtualLight.pointsWorld = [];
  21287. virtualLight.pointsFrustum = [];
  21288. var pointsWorld = virtualLight.pointsWorld,
  21289. pointsFrustum = virtualLight.pointsFrustum;
  21290. for ( var i = 0; i < 8; i ++ ) {
  21291. pointsWorld[ i ] = new THREE.Vector3();
  21292. pointsFrustum[ i ] = new THREE.Vector3();
  21293. }
  21294. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21295. var farZ = light.shadowCascadeFarZ[ cascade ];
  21296. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21297. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21298. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21299. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21300. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21301. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21302. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21303. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21304. return virtualLight;
  21305. }
  21306. // Synchronize virtual light with the original light
  21307. function updateVirtualLight( light, cascade ) {
  21308. var virtualLight = light.shadowCascadeArray[ cascade ];
  21309. virtualLight.position.copy( light.position );
  21310. virtualLight.target.position.copy( light.target.position );
  21311. virtualLight.lookAt( virtualLight.target );
  21312. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21313. virtualLight.shadowDarkness = light.shadowDarkness;
  21314. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21315. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21316. var farZ = light.shadowCascadeFarZ[ cascade ];
  21317. var pointsFrustum = virtualLight.pointsFrustum;
  21318. pointsFrustum[ 0 ].z = nearZ;
  21319. pointsFrustum[ 1 ].z = nearZ;
  21320. pointsFrustum[ 2 ].z = nearZ;
  21321. pointsFrustum[ 3 ].z = nearZ;
  21322. pointsFrustum[ 4 ].z = farZ;
  21323. pointsFrustum[ 5 ].z = farZ;
  21324. pointsFrustum[ 6 ].z = farZ;
  21325. pointsFrustum[ 7 ].z = farZ;
  21326. }
  21327. // Fit shadow camera's ortho frustum to camera frustum
  21328. function updateShadowCamera( camera, light ) {
  21329. var shadowCamera = light.shadowCamera,
  21330. pointsFrustum = light.pointsFrustum,
  21331. pointsWorld = light.pointsWorld;
  21332. _min.set( Infinity, Infinity, Infinity );
  21333. _max.set( -Infinity, -Infinity, -Infinity );
  21334. for ( var i = 0; i < 8; i ++ ) {
  21335. var p = pointsWorld[ i ];
  21336. p.copy( pointsFrustum[ i ] );
  21337. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21338. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21339. if ( p.x < _min.x ) _min.x = p.x;
  21340. if ( p.x > _max.x ) _max.x = p.x;
  21341. if ( p.y < _min.y ) _min.y = p.y;
  21342. if ( p.y > _max.y ) _max.y = p.y;
  21343. if ( p.z < _min.z ) _min.z = p.z;
  21344. if ( p.z > _max.z ) _max.z = p.z;
  21345. }
  21346. shadowCamera.left = _min.x;
  21347. shadowCamera.right = _max.x;
  21348. shadowCamera.top = _max.y;
  21349. shadowCamera.bottom = _min.y;
  21350. // can't really fit near/far
  21351. //shadowCamera.near = _min.z;
  21352. //shadowCamera.far = _max.z;
  21353. shadowCamera.updateProjectionMatrix();
  21354. }
  21355. // For the moment just ignore objects that have multiple materials with different animation methods
  21356. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21357. function getObjectMaterial( object ) {
  21358. return object.material instanceof THREE.MeshFaceMaterial
  21359. ? object.material.materials[ 0 ]
  21360. : object.material;
  21361. };
  21362. };
  21363. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21364. /**
  21365. * @author mikael emtinger / http://gomo.se/
  21366. * @author alteredq / http://alteredqualia.com/
  21367. */
  21368. THREE.SpritePlugin = function () {
  21369. var _gl, _renderer, _precision, _sprite = {};
  21370. this.init = function ( renderer ) {
  21371. _gl = renderer.context;
  21372. _renderer = renderer;
  21373. _precision = renderer.getPrecision();
  21374. _sprite.vertices = new Float32Array( 8 + 8 );
  21375. _sprite.faces = new Uint16Array( 6 );
  21376. var i = 0;
  21377. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21378. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21379. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21380. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21381. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21382. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21383. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21384. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21385. i = 0;
  21386. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21387. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21388. _sprite.vertexBuffer = _gl.createBuffer();
  21389. _sprite.elementBuffer = _gl.createBuffer();
  21390. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21391. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21392. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21393. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21394. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21395. _sprite.attributes = {};
  21396. _sprite.uniforms = {};
  21397. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21398. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21399. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21400. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21401. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21402. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21403. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21404. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21405. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21406. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21407. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21408. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21409. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21410. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21411. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21412. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21413. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21414. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21415. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21416. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21417. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21418. };
  21419. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21420. var sprites = scene.__webglSprites,
  21421. nSprites = sprites.length;
  21422. if ( ! nSprites ) return;
  21423. var attributes = _sprite.attributes,
  21424. uniforms = _sprite.uniforms;
  21425. var invAspect = viewportHeight / viewportWidth;
  21426. var halfViewportWidth = viewportWidth * 0.5,
  21427. halfViewportHeight = viewportHeight * 0.5;
  21428. // setup gl
  21429. _gl.useProgram( _sprite.program );
  21430. _gl.enableVertexAttribArray( attributes.position );
  21431. _gl.enableVertexAttribArray( attributes.uv );
  21432. _gl.disable( _gl.CULL_FACE );
  21433. _gl.enable( _gl.BLEND );
  21434. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21435. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21436. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21437. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21438. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21439. _gl.activeTexture( _gl.TEXTURE0 );
  21440. _gl.uniform1i( uniforms.map, 0 );
  21441. var oldFogType = 0;
  21442. var sceneFogType = 0;
  21443. var fog = scene.fog;
  21444. if ( fog ) {
  21445. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21446. if ( fog instanceof THREE.Fog ) {
  21447. _gl.uniform1f( uniforms.fogNear, fog.near );
  21448. _gl.uniform1f( uniforms.fogFar, fog.far );
  21449. _gl.uniform1i( uniforms.fogType, 1 );
  21450. oldFogType = 1;
  21451. sceneFogType = 1;
  21452. } else if ( fog instanceof THREE.FogExp2 ) {
  21453. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21454. _gl.uniform1i( uniforms.fogType, 2 );
  21455. oldFogType = 2;
  21456. sceneFogType = 2;
  21457. }
  21458. } else {
  21459. _gl.uniform1i( uniforms.fogType, 0 );
  21460. oldFogType = 0;
  21461. sceneFogType = 0;
  21462. }
  21463. // update positions and sort
  21464. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21465. for( i = 0; i < nSprites; i ++ ) {
  21466. sprite = sprites[ i ];
  21467. material = sprite.material;
  21468. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21469. if ( ! material.useScreenCoordinates ) {
  21470. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21471. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21472. } else {
  21473. sprite.z = - sprite.position.z;
  21474. }
  21475. }
  21476. sprites.sort( painterSortStable );
  21477. // render all sprites
  21478. for( i = 0; i < nSprites; i ++ ) {
  21479. sprite = sprites[ i ];
  21480. material = sprite.material;
  21481. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21482. if ( material.map && material.map.image && material.map.image.width ) {
  21483. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21484. if ( material.useScreenCoordinates === true ) {
  21485. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21486. _gl.uniform3f(
  21487. uniforms.screenPosition,
  21488. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21489. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21490. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21491. );
  21492. scale[ 0 ] = _renderer.devicePixelRatio;
  21493. scale[ 1 ] = _renderer.devicePixelRatio;
  21494. } else {
  21495. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21496. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21497. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21498. scale[ 0 ] = 1;
  21499. scale[ 1 ] = 1;
  21500. }
  21501. if ( scene.fog && material.fog ) {
  21502. fogType = sceneFogType;
  21503. } else {
  21504. fogType = 0;
  21505. }
  21506. if ( oldFogType !== fogType ) {
  21507. _gl.uniform1i( uniforms.fogType, fogType );
  21508. oldFogType = fogType;
  21509. }
  21510. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21511. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21512. scale[ 1 ] *= size * sprite.scale.y;
  21513. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21514. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21515. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21516. _gl.uniform1f( uniforms.opacity, material.opacity );
  21517. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21518. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21519. _gl.uniform2fv( uniforms.scale, scale );
  21520. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21521. _renderer.setDepthTest( material.depthTest );
  21522. _renderer.setDepthWrite( material.depthWrite );
  21523. _renderer.setTexture( material.map, 0 );
  21524. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21525. }
  21526. }
  21527. // restore gl
  21528. _gl.enable( _gl.CULL_FACE );
  21529. };
  21530. function createProgram ( shader, precision ) {
  21531. var program = _gl.createProgram();
  21532. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21533. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21534. var prefix = "precision " + precision + " float;\n";
  21535. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21536. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21537. _gl.compileShader( fragmentShader );
  21538. _gl.compileShader( vertexShader );
  21539. _gl.attachShader( program, fragmentShader );
  21540. _gl.attachShader( program, vertexShader );
  21541. _gl.linkProgram( program );
  21542. return program;
  21543. };
  21544. function painterSortStable ( a, b ) {
  21545. if ( a.z !== b.z ) {
  21546. return b.z - a.z;
  21547. } else {
  21548. return b.id - a.id;
  21549. }
  21550. };
  21551. };
  21552. /**
  21553. * @author alteredq / http://alteredqualia.com/
  21554. */
  21555. THREE.DepthPassPlugin = function () {
  21556. this.enabled = false;
  21557. this.renderTarget = null;
  21558. var _gl,
  21559. _renderer,
  21560. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21561. _frustum = new THREE.Frustum(),
  21562. _projScreenMatrix = new THREE.Matrix4();
  21563. this.init = function ( renderer ) {
  21564. _gl = renderer.context;
  21565. _renderer = renderer;
  21566. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21567. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21568. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21569. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21570. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21571. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21572. _depthMaterial._shadowPass = true;
  21573. _depthMaterialMorph._shadowPass = true;
  21574. _depthMaterialSkin._shadowPass = true;
  21575. _depthMaterialMorphSkin._shadowPass = true;
  21576. };
  21577. this.render = function ( scene, camera ) {
  21578. if ( ! this.enabled ) return;
  21579. this.update( scene, camera );
  21580. };
  21581. this.update = function ( scene, camera ) {
  21582. var i, il, j, jl, n,
  21583. program, buffer, material,
  21584. webglObject, object, light,
  21585. renderList,
  21586. fog = null;
  21587. // set GL state for depth map
  21588. _gl.clearColor( 1, 1, 1, 1 );
  21589. _gl.disable( _gl.BLEND );
  21590. _renderer.setDepthTest( true );
  21591. // update scene
  21592. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21593. // update camera matrices and frustum
  21594. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21595. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21596. _frustum.setFromMatrix( _projScreenMatrix );
  21597. // render depth map
  21598. _renderer.setRenderTarget( this.renderTarget );
  21599. _renderer.clear();
  21600. // set object matrices & frustum culling
  21601. renderList = scene.__webglObjects;
  21602. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21603. webglObject = renderList[ j ];
  21604. object = webglObject.object;
  21605. webglObject.render = false;
  21606. if ( object.visible ) {
  21607. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21608. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21609. webglObject.render = true;
  21610. }
  21611. }
  21612. }
  21613. // render regular objects
  21614. var objectMaterial, useMorphing, useSkinning;
  21615. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21616. webglObject = renderList[ j ];
  21617. if ( webglObject.render ) {
  21618. object = webglObject.object;
  21619. buffer = webglObject.buffer;
  21620. // todo: create proper depth material for particles
  21621. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21622. objectMaterial = getObjectMaterial( object );
  21623. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21624. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21625. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21626. if ( object.customDepthMaterial ) {
  21627. material = object.customDepthMaterial;
  21628. } else if ( useSkinning ) {
  21629. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21630. } else if ( useMorphing ) {
  21631. material = _depthMaterialMorph;
  21632. } else {
  21633. material = _depthMaterial;
  21634. }
  21635. if ( buffer instanceof THREE.BufferGeometry ) {
  21636. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21637. } else {
  21638. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21639. }
  21640. }
  21641. }
  21642. // set matrices and render immediate objects
  21643. renderList = scene.__webglObjectsImmediate;
  21644. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21645. webglObject = renderList[ j ];
  21646. object = webglObject.object;
  21647. if ( object.visible ) {
  21648. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21649. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21650. }
  21651. }
  21652. // restore GL state
  21653. var clearColor = _renderer.getClearColor(),
  21654. clearAlpha = _renderer.getClearAlpha();
  21655. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21656. _gl.enable( _gl.BLEND );
  21657. };
  21658. // For the moment just ignore objects that have multiple materials with different animation methods
  21659. // Only the first material will be taken into account for deciding which depth material to use
  21660. function getObjectMaterial( object ) {
  21661. return object.material instanceof THREE.MeshFaceMaterial
  21662. ? object.material.materials[ 0 ]
  21663. : object.material;
  21664. };
  21665. };
  21666. /**
  21667. * @author mikael emtinger / http://gomo.se/
  21668. *
  21669. */
  21670. THREE.ShaderFlares = {
  21671. 'lensFlareVertexTexture': {
  21672. vertexShader: [
  21673. "uniform lowp int renderType;",
  21674. "uniform vec3 screenPosition;",
  21675. "uniform vec2 scale;",
  21676. "uniform float rotation;",
  21677. "uniform sampler2D occlusionMap;",
  21678. "attribute vec2 position;",
  21679. "attribute vec2 uv;",
  21680. "varying vec2 vUV;",
  21681. "varying float vVisibility;",
  21682. "void main() {",
  21683. "vUV = uv;",
  21684. "vec2 pos = position;",
  21685. "if( renderType == 2 ) {",
  21686. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21687. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21688. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21689. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21690. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21691. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21692. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21693. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21694. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21695. "vVisibility = ( visibility.r / 9.0 ) *",
  21696. "( 1.0 - visibility.g / 9.0 ) *",
  21697. "( visibility.b / 9.0 ) *",
  21698. "( 1.0 - visibility.a / 9.0 );",
  21699. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21700. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21701. "}",
  21702. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21703. "}"
  21704. ].join( "\n" ),
  21705. fragmentShader: [
  21706. "uniform lowp int renderType;",
  21707. "uniform sampler2D map;",
  21708. "uniform float opacity;",
  21709. "uniform vec3 color;",
  21710. "varying vec2 vUV;",
  21711. "varying float vVisibility;",
  21712. "void main() {",
  21713. // pink square
  21714. "if( renderType == 0 ) {",
  21715. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21716. // restore
  21717. "} else if( renderType == 1 ) {",
  21718. "gl_FragColor = texture2D( map, vUV );",
  21719. // flare
  21720. "} else {",
  21721. "vec4 texture = texture2D( map, vUV );",
  21722. "texture.a *= opacity * vVisibility;",
  21723. "gl_FragColor = texture;",
  21724. "gl_FragColor.rgb *= color;",
  21725. "}",
  21726. "}"
  21727. ].join( "\n" )
  21728. },
  21729. 'lensFlare': {
  21730. vertexShader: [
  21731. "uniform lowp int renderType;",
  21732. "uniform vec3 screenPosition;",
  21733. "uniform vec2 scale;",
  21734. "uniform float rotation;",
  21735. "attribute vec2 position;",
  21736. "attribute vec2 uv;",
  21737. "varying vec2 vUV;",
  21738. "void main() {",
  21739. "vUV = uv;",
  21740. "vec2 pos = position;",
  21741. "if( renderType == 2 ) {",
  21742. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21743. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21744. "}",
  21745. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21746. "}"
  21747. ].join( "\n" ),
  21748. fragmentShader: [
  21749. "precision mediump float;",
  21750. "uniform lowp int renderType;",
  21751. "uniform sampler2D map;",
  21752. "uniform sampler2D occlusionMap;",
  21753. "uniform float opacity;",
  21754. "uniform vec3 color;",
  21755. "varying vec2 vUV;",
  21756. "void main() {",
  21757. // pink square
  21758. "if( renderType == 0 ) {",
  21759. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21760. // restore
  21761. "} else if( renderType == 1 ) {",
  21762. "gl_FragColor = texture2D( map, vUV );",
  21763. // flare
  21764. "} else {",
  21765. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21766. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21767. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21768. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21769. "visibility = ( 1.0 - visibility / 4.0 );",
  21770. "vec4 texture = texture2D( map, vUV );",
  21771. "texture.a *= opacity * visibility;",
  21772. "gl_FragColor = texture;",
  21773. "gl_FragColor.rgb *= color;",
  21774. "}",
  21775. "}"
  21776. ].join( "\n" )
  21777. }
  21778. };
  21779. /**
  21780. * @author mikael emtinger / http://gomo.se/
  21781. * @author alteredq / http://alteredqualia.com/
  21782. *
  21783. */
  21784. THREE.ShaderSprite = {
  21785. 'sprite': {
  21786. vertexShader: [
  21787. "uniform int useScreenCoordinates;",
  21788. "uniform int sizeAttenuation;",
  21789. "uniform vec3 screenPosition;",
  21790. "uniform mat4 modelViewMatrix;",
  21791. "uniform mat4 projectionMatrix;",
  21792. "uniform float rotation;",
  21793. "uniform vec2 scale;",
  21794. "uniform vec2 alignment;",
  21795. "uniform vec2 uvOffset;",
  21796. "uniform vec2 uvScale;",
  21797. "attribute vec2 position;",
  21798. "attribute vec2 uv;",
  21799. "varying vec2 vUV;",
  21800. "void main() {",
  21801. "vUV = uvOffset + uv * uvScale;",
  21802. "vec2 alignedPosition = position + alignment;",
  21803. "vec2 rotatedPosition;",
  21804. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21805. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21806. "vec4 finalPosition;",
  21807. "if( useScreenCoordinates != 0 ) {",
  21808. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21809. "} else {",
  21810. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21811. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21812. "}",
  21813. "gl_Position = finalPosition;",
  21814. "}"
  21815. ].join( "\n" ),
  21816. fragmentShader: [
  21817. "uniform vec3 color;",
  21818. "uniform sampler2D map;",
  21819. "uniform float opacity;",
  21820. "uniform int fogType;",
  21821. "uniform vec3 fogColor;",
  21822. "uniform float fogDensity;",
  21823. "uniform float fogNear;",
  21824. "uniform float fogFar;",
  21825. "uniform float alphaTest;",
  21826. "varying vec2 vUV;",
  21827. "void main() {",
  21828. "vec4 texture = texture2D( map, vUV );",
  21829. "if ( texture.a < alphaTest ) discard;",
  21830. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21831. "if ( fogType > 0 ) {",
  21832. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21833. "float fogFactor = 0.0;",
  21834. "if ( fogType == 1 ) {",
  21835. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21836. "} else {",
  21837. "const float LOG2 = 1.442695;",
  21838. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21839. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21840. "}",
  21841. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21842. "}",
  21843. "}"
  21844. ].join( "\n" )
  21845. }
  21846. };