three.unit.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.THREE = global.THREE || {})));
  5. }(this, (function (exports) { 'use strict';
  6. // Polyfills
  7. if ( Number.EPSILON === undefined ) {
  8. Number.EPSILON = Math.pow( 2, - 52 );
  9. }
  10. //
  11. if ( Math.sign === undefined ) {
  12. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  13. Math.sign = function ( x ) {
  14. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  15. };
  16. }
  17. if ( Function.prototype.name === undefined ) {
  18. // Missing in IE9-11.
  19. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  20. Object.defineProperty( Function.prototype, 'name', {
  21. get: function () {
  22. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  23. }
  24. } );
  25. }
  26. if ( Object.assign === undefined ) {
  27. // Missing in IE.
  28. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  29. ( function () {
  30. Object.assign = function ( target ) {
  31. 'use strict';
  32. if ( target === undefined || target === null ) {
  33. throw new TypeError( 'Cannot convert undefined or null to object' );
  34. }
  35. var output = Object( target );
  36. for ( var index = 1; index < arguments.length; index ++ ) {
  37. var source = arguments[ index ];
  38. if ( source !== undefined && source !== null ) {
  39. for ( var nextKey in source ) {
  40. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  41. output[ nextKey ] = source[ nextKey ];
  42. }
  43. }
  44. }
  45. }
  46. return output;
  47. };
  48. } )();
  49. }
  50. var REVISION = '85dev';
  51. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  52. var CullFaceNone = 0;
  53. var CullFaceBack = 1;
  54. var CullFaceFront = 2;
  55. var CullFaceFrontBack = 3;
  56. var FrontFaceDirectionCW = 0;
  57. var FrontFaceDirectionCCW = 1;
  58. var BasicShadowMap = 0;
  59. var PCFShadowMap = 1;
  60. var PCFSoftShadowMap = 2;
  61. var FrontSide = 0;
  62. var BackSide = 1;
  63. var DoubleSide = 2;
  64. var FlatShading = 1;
  65. var SmoothShading = 2;
  66. var NoColors = 0;
  67. var FaceColors = 1;
  68. var VertexColors = 2;
  69. var NoBlending = 0;
  70. var NormalBlending = 1;
  71. var AdditiveBlending = 2;
  72. var SubtractiveBlending = 3;
  73. var MultiplyBlending = 4;
  74. var CustomBlending = 5;
  75. var AddEquation = 100;
  76. var SubtractEquation = 101;
  77. var ReverseSubtractEquation = 102;
  78. var MinEquation = 103;
  79. var MaxEquation = 104;
  80. var ZeroFactor = 200;
  81. var OneFactor = 201;
  82. var SrcColorFactor = 202;
  83. var OneMinusSrcColorFactor = 203;
  84. var SrcAlphaFactor = 204;
  85. var OneMinusSrcAlphaFactor = 205;
  86. var DstAlphaFactor = 206;
  87. var OneMinusDstAlphaFactor = 207;
  88. var DstColorFactor = 208;
  89. var OneMinusDstColorFactor = 209;
  90. var SrcAlphaSaturateFactor = 210;
  91. var NeverDepth = 0;
  92. var AlwaysDepth = 1;
  93. var LessDepth = 2;
  94. var LessEqualDepth = 3;
  95. var EqualDepth = 4;
  96. var GreaterEqualDepth = 5;
  97. var GreaterDepth = 6;
  98. var NotEqualDepth = 7;
  99. var MultiplyOperation = 0;
  100. var MixOperation = 1;
  101. var AddOperation = 2;
  102. var NoToneMapping = 0;
  103. var LinearToneMapping = 1;
  104. var ReinhardToneMapping = 2;
  105. var Uncharted2ToneMapping = 3;
  106. var CineonToneMapping = 4;
  107. var UVMapping = 300;
  108. var CubeReflectionMapping = 301;
  109. var CubeRefractionMapping = 302;
  110. var EquirectangularReflectionMapping = 303;
  111. var EquirectangularRefractionMapping = 304;
  112. var SphericalReflectionMapping = 305;
  113. var CubeUVReflectionMapping = 306;
  114. var CubeUVRefractionMapping = 307;
  115. var RepeatWrapping = 1000;
  116. var ClampToEdgeWrapping = 1001;
  117. var MirroredRepeatWrapping = 1002;
  118. var NearestFilter = 1003;
  119. var NearestMipMapNearestFilter = 1004;
  120. var NearestMipMapLinearFilter = 1005;
  121. var LinearFilter = 1006;
  122. var LinearMipMapNearestFilter = 1007;
  123. var LinearMipMapLinearFilter = 1008;
  124. var UnsignedByteType = 1009;
  125. var ByteType = 1010;
  126. var ShortType = 1011;
  127. var UnsignedShortType = 1012;
  128. var IntType = 1013;
  129. var UnsignedIntType = 1014;
  130. var FloatType = 1015;
  131. var HalfFloatType = 1016;
  132. var UnsignedShort4444Type = 1017;
  133. var UnsignedShort5551Type = 1018;
  134. var UnsignedShort565Type = 1019;
  135. var UnsignedInt248Type = 1020;
  136. var AlphaFormat = 1021;
  137. var RGBFormat = 1022;
  138. var RGBAFormat = 1023;
  139. var LuminanceFormat = 1024;
  140. var LuminanceAlphaFormat = 1025;
  141. var RGBEFormat = RGBAFormat;
  142. var DepthFormat = 1026;
  143. var DepthStencilFormat = 1027;
  144. var RGB_S3TC_DXT1_Format = 2001;
  145. var RGBA_S3TC_DXT1_Format = 2002;
  146. var RGBA_S3TC_DXT3_Format = 2003;
  147. var RGBA_S3TC_DXT5_Format = 2004;
  148. var RGB_PVRTC_4BPPV1_Format = 2100;
  149. var RGB_PVRTC_2BPPV1_Format = 2101;
  150. var RGBA_PVRTC_4BPPV1_Format = 2102;
  151. var RGBA_PVRTC_2BPPV1_Format = 2103;
  152. var RGB_ETC1_Format = 2151;
  153. var LoopOnce = 2200;
  154. var LoopRepeat = 2201;
  155. var LoopPingPong = 2202;
  156. var InterpolateDiscrete = 2300;
  157. var InterpolateLinear = 2301;
  158. var InterpolateSmooth = 2302;
  159. var ZeroCurvatureEnding = 2400;
  160. var ZeroSlopeEnding = 2401;
  161. var WrapAroundEnding = 2402;
  162. var TrianglesDrawMode = 0;
  163. var TriangleStripDrawMode = 1;
  164. var TriangleFanDrawMode = 2;
  165. var LinearEncoding = 3000;
  166. var sRGBEncoding = 3001;
  167. var GammaEncoding = 3007;
  168. var RGBEEncoding = 3002;
  169. var LogLuvEncoding = 3003;
  170. var RGBM7Encoding = 3004;
  171. var RGBM16Encoding = 3005;
  172. var RGBDEncoding = 3006;
  173. var BasicDepthPacking = 3200;
  174. var RGBADepthPacking = 3201;
  175. /**
  176. * @author alteredq / http://alteredqualia.com/
  177. * @author mrdoob / http://mrdoob.com/
  178. */
  179. var _Math = {
  180. DEG2RAD: Math.PI / 180,
  181. RAD2DEG: 180 / Math.PI,
  182. generateUUID: function () {
  183. // http://www.broofa.com/Tools/Math.uuid.htm
  184. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  185. var uuid = new Array( 36 );
  186. var rnd = 0, r;
  187. return function generateUUID() {
  188. for ( var i = 0; i < 36; i ++ ) {
  189. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  190. uuid[ i ] = '-';
  191. } else if ( i === 14 ) {
  192. uuid[ i ] = '4';
  193. } else {
  194. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  195. r = rnd & 0xf;
  196. rnd = rnd >> 4;
  197. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  198. }
  199. }
  200. return uuid.join( '' );
  201. };
  202. }(),
  203. clamp: function ( value, min, max ) {
  204. return Math.max( min, Math.min( max, value ) );
  205. },
  206. // compute euclidian modulo of m % n
  207. // https://en.wikipedia.org/wiki/Modulo_operation
  208. euclideanModulo: function ( n, m ) {
  209. return ( ( n % m ) + m ) % m;
  210. },
  211. // Linear mapping from range <a1, a2> to range <b1, b2>
  212. mapLinear: function ( x, a1, a2, b1, b2 ) {
  213. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  214. },
  215. // https://en.wikipedia.org/wiki/Linear_interpolation
  216. lerp: function ( x, y, t ) {
  217. return ( 1 - t ) * x + t * y;
  218. },
  219. // http://en.wikipedia.org/wiki/Smoothstep
  220. smoothstep: function ( x, min, max ) {
  221. if ( x <= min ) return 0;
  222. if ( x >= max ) return 1;
  223. x = ( x - min ) / ( max - min );
  224. return x * x * ( 3 - 2 * x );
  225. },
  226. smootherstep: function ( x, min, max ) {
  227. if ( x <= min ) return 0;
  228. if ( x >= max ) return 1;
  229. x = ( x - min ) / ( max - min );
  230. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  231. },
  232. // Random integer from <low, high> interval
  233. randInt: function ( low, high ) {
  234. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  235. },
  236. // Random float from <low, high> interval
  237. randFloat: function ( low, high ) {
  238. return low + Math.random() * ( high - low );
  239. },
  240. // Random float from <-range/2, range/2> interval
  241. randFloatSpread: function ( range ) {
  242. return range * ( 0.5 - Math.random() );
  243. },
  244. degToRad: function ( degrees ) {
  245. return degrees * _Math.DEG2RAD;
  246. },
  247. radToDeg: function ( radians ) {
  248. return radians * _Math.RAD2DEG;
  249. },
  250. isPowerOfTwo: function ( value ) {
  251. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  252. },
  253. nearestPowerOfTwo: function ( value ) {
  254. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  255. },
  256. nextPowerOfTwo: function ( value ) {
  257. value --;
  258. value |= value >> 1;
  259. value |= value >> 2;
  260. value |= value >> 4;
  261. value |= value >> 8;
  262. value |= value >> 16;
  263. value ++;
  264. return value;
  265. }
  266. };
  267. /**
  268. * @author mrdoob / http://mrdoob.com/
  269. * @author supereggbert / http://www.paulbrunt.co.uk/
  270. * @author philogb / http://blog.thejit.org/
  271. * @author jordi_ros / http://plattsoft.com
  272. * @author D1plo1d / http://github.com/D1plo1d
  273. * @author alteredq / http://alteredqualia.com/
  274. * @author mikael emtinger / http://gomo.se/
  275. * @author timknip / http://www.floorplanner.com/
  276. * @author bhouston / http://clara.io
  277. * @author WestLangley / http://github.com/WestLangley
  278. */
  279. function Matrix4() {
  280. this.elements = new Float32Array( [
  281. 1, 0, 0, 0,
  282. 0, 1, 0, 0,
  283. 0, 0, 1, 0,
  284. 0, 0, 0, 1
  285. ] );
  286. if ( arguments.length > 0 ) {
  287. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  288. }
  289. }
  290. Matrix4.prototype = {
  291. constructor: Matrix4,
  292. isMatrix4: true,
  293. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  294. var te = this.elements;
  295. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  296. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  297. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  298. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  299. return this;
  300. },
  301. identity: function () {
  302. this.set(
  303. 1, 0, 0, 0,
  304. 0, 1, 0, 0,
  305. 0, 0, 1, 0,
  306. 0, 0, 0, 1
  307. );
  308. return this;
  309. },
  310. clone: function () {
  311. return new Matrix4().fromArray( this.elements );
  312. },
  313. copy: function ( m ) {
  314. this.elements.set( m.elements );
  315. return this;
  316. },
  317. copyPosition: function ( m ) {
  318. var te = this.elements;
  319. var me = m.elements;
  320. te[ 12 ] = me[ 12 ];
  321. te[ 13 ] = me[ 13 ];
  322. te[ 14 ] = me[ 14 ];
  323. return this;
  324. },
  325. extractBasis: function ( xAxis, yAxis, zAxis ) {
  326. xAxis.setFromMatrixColumn( this, 0 );
  327. yAxis.setFromMatrixColumn( this, 1 );
  328. zAxis.setFromMatrixColumn( this, 2 );
  329. return this;
  330. },
  331. makeBasis: function ( xAxis, yAxis, zAxis ) {
  332. this.set(
  333. xAxis.x, yAxis.x, zAxis.x, 0,
  334. xAxis.y, yAxis.y, zAxis.y, 0,
  335. xAxis.z, yAxis.z, zAxis.z, 0,
  336. 0, 0, 0, 1
  337. );
  338. return this;
  339. },
  340. extractRotation: function () {
  341. var v1;
  342. return function extractRotation( m ) {
  343. if ( v1 === undefined ) v1 = new Vector3();
  344. var te = this.elements;
  345. var me = m.elements;
  346. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  347. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  348. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  349. te[ 0 ] = me[ 0 ] * scaleX;
  350. te[ 1 ] = me[ 1 ] * scaleX;
  351. te[ 2 ] = me[ 2 ] * scaleX;
  352. te[ 4 ] = me[ 4 ] * scaleY;
  353. te[ 5 ] = me[ 5 ] * scaleY;
  354. te[ 6 ] = me[ 6 ] * scaleY;
  355. te[ 8 ] = me[ 8 ] * scaleZ;
  356. te[ 9 ] = me[ 9 ] * scaleZ;
  357. te[ 10 ] = me[ 10 ] * scaleZ;
  358. return this;
  359. };
  360. }(),
  361. makeRotationFromEuler: function ( euler ) {
  362. if ( (euler && euler.isEuler) === false ) {
  363. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  364. }
  365. var te = this.elements;
  366. var x = euler.x, y = euler.y, z = euler.z;
  367. var a = Math.cos( x ), b = Math.sin( x );
  368. var c = Math.cos( y ), d = Math.sin( y );
  369. var e = Math.cos( z ), f = Math.sin( z );
  370. if ( euler.order === 'XYZ' ) {
  371. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  372. te[ 0 ] = c * e;
  373. te[ 4 ] = - c * f;
  374. te[ 8 ] = d;
  375. te[ 1 ] = af + be * d;
  376. te[ 5 ] = ae - bf * d;
  377. te[ 9 ] = - b * c;
  378. te[ 2 ] = bf - ae * d;
  379. te[ 6 ] = be + af * d;
  380. te[ 10 ] = a * c;
  381. } else if ( euler.order === 'YXZ' ) {
  382. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  383. te[ 0 ] = ce + df * b;
  384. te[ 4 ] = de * b - cf;
  385. te[ 8 ] = a * d;
  386. te[ 1 ] = a * f;
  387. te[ 5 ] = a * e;
  388. te[ 9 ] = - b;
  389. te[ 2 ] = cf * b - de;
  390. te[ 6 ] = df + ce * b;
  391. te[ 10 ] = a * c;
  392. } else if ( euler.order === 'ZXY' ) {
  393. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  394. te[ 0 ] = ce - df * b;
  395. te[ 4 ] = - a * f;
  396. te[ 8 ] = de + cf * b;
  397. te[ 1 ] = cf + de * b;
  398. te[ 5 ] = a * e;
  399. te[ 9 ] = df - ce * b;
  400. te[ 2 ] = - a * d;
  401. te[ 6 ] = b;
  402. te[ 10 ] = a * c;
  403. } else if ( euler.order === 'ZYX' ) {
  404. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  405. te[ 0 ] = c * e;
  406. te[ 4 ] = be * d - af;
  407. te[ 8 ] = ae * d + bf;
  408. te[ 1 ] = c * f;
  409. te[ 5 ] = bf * d + ae;
  410. te[ 9 ] = af * d - be;
  411. te[ 2 ] = - d;
  412. te[ 6 ] = b * c;
  413. te[ 10 ] = a * c;
  414. } else if ( euler.order === 'YZX' ) {
  415. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  416. te[ 0 ] = c * e;
  417. te[ 4 ] = bd - ac * f;
  418. te[ 8 ] = bc * f + ad;
  419. te[ 1 ] = f;
  420. te[ 5 ] = a * e;
  421. te[ 9 ] = - b * e;
  422. te[ 2 ] = - d * e;
  423. te[ 6 ] = ad * f + bc;
  424. te[ 10 ] = ac - bd * f;
  425. } else if ( euler.order === 'XZY' ) {
  426. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  427. te[ 0 ] = c * e;
  428. te[ 4 ] = - f;
  429. te[ 8 ] = d * e;
  430. te[ 1 ] = ac * f + bd;
  431. te[ 5 ] = a * e;
  432. te[ 9 ] = ad * f - bc;
  433. te[ 2 ] = bc * f - ad;
  434. te[ 6 ] = b * e;
  435. te[ 10 ] = bd * f + ac;
  436. }
  437. // last column
  438. te[ 3 ] = 0;
  439. te[ 7 ] = 0;
  440. te[ 11 ] = 0;
  441. // bottom row
  442. te[ 12 ] = 0;
  443. te[ 13 ] = 0;
  444. te[ 14 ] = 0;
  445. te[ 15 ] = 1;
  446. return this;
  447. },
  448. makeRotationFromQuaternion: function ( q ) {
  449. var te = this.elements;
  450. var x = q.x, y = q.y, z = q.z, w = q.w;
  451. var x2 = x + x, y2 = y + y, z2 = z + z;
  452. var xx = x * x2, xy = x * y2, xz = x * z2;
  453. var yy = y * y2, yz = y * z2, zz = z * z2;
  454. var wx = w * x2, wy = w * y2, wz = w * z2;
  455. te[ 0 ] = 1 - ( yy + zz );
  456. te[ 4 ] = xy - wz;
  457. te[ 8 ] = xz + wy;
  458. te[ 1 ] = xy + wz;
  459. te[ 5 ] = 1 - ( xx + zz );
  460. te[ 9 ] = yz - wx;
  461. te[ 2 ] = xz - wy;
  462. te[ 6 ] = yz + wx;
  463. te[ 10 ] = 1 - ( xx + yy );
  464. // last column
  465. te[ 3 ] = 0;
  466. te[ 7 ] = 0;
  467. te[ 11 ] = 0;
  468. // bottom row
  469. te[ 12 ] = 0;
  470. te[ 13 ] = 0;
  471. te[ 14 ] = 0;
  472. te[ 15 ] = 1;
  473. return this;
  474. },
  475. lookAt: function () {
  476. var x, y, z;
  477. return function lookAt( eye, target, up ) {
  478. if ( x === undefined ) {
  479. x = new Vector3();
  480. y = new Vector3();
  481. z = new Vector3();
  482. }
  483. var te = this.elements;
  484. z.subVectors( eye, target ).normalize();
  485. if ( z.lengthSq() === 0 ) {
  486. z.z = 1;
  487. }
  488. x.crossVectors( up, z ).normalize();
  489. if ( x.lengthSq() === 0 ) {
  490. z.z += 0.0001;
  491. x.crossVectors( up, z ).normalize();
  492. }
  493. y.crossVectors( z, x );
  494. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  495. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  496. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  497. return this;
  498. };
  499. }(),
  500. multiply: function ( m, n ) {
  501. if ( n !== undefined ) {
  502. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  503. return this.multiplyMatrices( m, n );
  504. }
  505. return this.multiplyMatrices( this, m );
  506. },
  507. premultiply: function ( m ) {
  508. return this.multiplyMatrices( m, this );
  509. },
  510. multiplyMatrices: function ( a, b ) {
  511. var ae = a.elements;
  512. var be = b.elements;
  513. var te = this.elements;
  514. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  515. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  516. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  517. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  518. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  519. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  520. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  521. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  522. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  523. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  524. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  525. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  526. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  527. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  528. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  529. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  530. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  531. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  532. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  533. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  534. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  535. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  536. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  537. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  538. return this;
  539. },
  540. multiplyToArray: function ( a, b, r ) {
  541. var te = this.elements;
  542. this.multiplyMatrices( a, b );
  543. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  544. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  545. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  546. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  547. return this;
  548. },
  549. multiplyScalar: function ( s ) {
  550. var te = this.elements;
  551. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  552. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  553. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  554. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  555. return this;
  556. },
  557. applyToBufferAttribute: function () {
  558. var v1;
  559. return function applyToBufferAttribute( attribute ) {
  560. if ( v1 === undefined ) v1 = new Vector3();
  561. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  562. v1.x = attribute.getX( i );
  563. v1.y = attribute.getY( i );
  564. v1.z = attribute.getZ( i );
  565. v1.applyMatrix4( this );
  566. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  567. }
  568. return attribute;
  569. };
  570. }(),
  571. determinant: function () {
  572. var te = this.elements;
  573. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  574. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  575. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  576. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  577. //TODO: make this more efficient
  578. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  579. return (
  580. n41 * (
  581. + n14 * n23 * n32
  582. - n13 * n24 * n32
  583. - n14 * n22 * n33
  584. + n12 * n24 * n33
  585. + n13 * n22 * n34
  586. - n12 * n23 * n34
  587. ) +
  588. n42 * (
  589. + n11 * n23 * n34
  590. - n11 * n24 * n33
  591. + n14 * n21 * n33
  592. - n13 * n21 * n34
  593. + n13 * n24 * n31
  594. - n14 * n23 * n31
  595. ) +
  596. n43 * (
  597. + n11 * n24 * n32
  598. - n11 * n22 * n34
  599. - n14 * n21 * n32
  600. + n12 * n21 * n34
  601. + n14 * n22 * n31
  602. - n12 * n24 * n31
  603. ) +
  604. n44 * (
  605. - n13 * n22 * n31
  606. - n11 * n23 * n32
  607. + n11 * n22 * n33
  608. + n13 * n21 * n32
  609. - n12 * n21 * n33
  610. + n12 * n23 * n31
  611. )
  612. );
  613. },
  614. transpose: function () {
  615. var te = this.elements;
  616. var tmp;
  617. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  618. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  619. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  620. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  621. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  622. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  623. return this;
  624. },
  625. setPosition: function ( v ) {
  626. var te = this.elements;
  627. te[ 12 ] = v.x;
  628. te[ 13 ] = v.y;
  629. te[ 14 ] = v.z;
  630. return this;
  631. },
  632. getInverse: function ( m, throwOnDegenerate ) {
  633. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  634. var te = this.elements,
  635. me = m.elements,
  636. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  637. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  638. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  639. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  640. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  641. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  642. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  643. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  644. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  645. if ( det === 0 ) {
  646. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  647. if ( throwOnDegenerate === true ) {
  648. throw new Error( msg );
  649. } else {
  650. console.warn( msg );
  651. }
  652. return this.identity();
  653. }
  654. var detInv = 1 / det;
  655. te[ 0 ] = t11 * detInv;
  656. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  657. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  658. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  659. te[ 4 ] = t12 * detInv;
  660. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  661. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  662. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  663. te[ 8 ] = t13 * detInv;
  664. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  665. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  666. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  667. te[ 12 ] = t14 * detInv;
  668. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  669. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  670. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  671. return this;
  672. },
  673. scale: function ( v ) {
  674. var te = this.elements;
  675. var x = v.x, y = v.y, z = v.z;
  676. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  677. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  678. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  679. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  680. return this;
  681. },
  682. getMaxScaleOnAxis: function () {
  683. var te = this.elements;
  684. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  685. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  686. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  687. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  688. },
  689. makeTranslation: function ( x, y, z ) {
  690. this.set(
  691. 1, 0, 0, x,
  692. 0, 1, 0, y,
  693. 0, 0, 1, z,
  694. 0, 0, 0, 1
  695. );
  696. return this;
  697. },
  698. makeRotationX: function ( theta ) {
  699. var c = Math.cos( theta ), s = Math.sin( theta );
  700. this.set(
  701. 1, 0, 0, 0,
  702. 0, c, - s, 0,
  703. 0, s, c, 0,
  704. 0, 0, 0, 1
  705. );
  706. return this;
  707. },
  708. makeRotationY: function ( theta ) {
  709. var c = Math.cos( theta ), s = Math.sin( theta );
  710. this.set(
  711. c, 0, s, 0,
  712. 0, 1, 0, 0,
  713. - s, 0, c, 0,
  714. 0, 0, 0, 1
  715. );
  716. return this;
  717. },
  718. makeRotationZ: function ( theta ) {
  719. var c = Math.cos( theta ), s = Math.sin( theta );
  720. this.set(
  721. c, - s, 0, 0,
  722. s, c, 0, 0,
  723. 0, 0, 1, 0,
  724. 0, 0, 0, 1
  725. );
  726. return this;
  727. },
  728. makeRotationAxis: function ( axis, angle ) {
  729. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  730. var c = Math.cos( angle );
  731. var s = Math.sin( angle );
  732. var t = 1 - c;
  733. var x = axis.x, y = axis.y, z = axis.z;
  734. var tx = t * x, ty = t * y;
  735. this.set(
  736. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  737. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  738. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  739. 0, 0, 0, 1
  740. );
  741. return this;
  742. },
  743. makeScale: function ( x, y, z ) {
  744. this.set(
  745. x, 0, 0, 0,
  746. 0, y, 0, 0,
  747. 0, 0, z, 0,
  748. 0, 0, 0, 1
  749. );
  750. return this;
  751. },
  752. makeShear: function ( x, y, z ) {
  753. this.set(
  754. 1, y, z, 0,
  755. x, 1, z, 0,
  756. x, y, 1, 0,
  757. 0, 0, 0, 1
  758. );
  759. return this;
  760. },
  761. compose: function ( position, quaternion, scale ) {
  762. this.makeRotationFromQuaternion( quaternion );
  763. this.scale( scale );
  764. this.setPosition( position );
  765. return this;
  766. },
  767. decompose: function () {
  768. var vector, matrix;
  769. return function decompose( position, quaternion, scale ) {
  770. if ( vector === undefined ) {
  771. vector = new Vector3();
  772. matrix = new Matrix4();
  773. }
  774. var te = this.elements;
  775. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  776. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  777. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  778. // if determine is negative, we need to invert one scale
  779. var det = this.determinant();
  780. if ( det < 0 ) {
  781. sx = - sx;
  782. }
  783. position.x = te[ 12 ];
  784. position.y = te[ 13 ];
  785. position.z = te[ 14 ];
  786. // scale the rotation part
  787. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  788. var invSX = 1 / sx;
  789. var invSY = 1 / sy;
  790. var invSZ = 1 / sz;
  791. matrix.elements[ 0 ] *= invSX;
  792. matrix.elements[ 1 ] *= invSX;
  793. matrix.elements[ 2 ] *= invSX;
  794. matrix.elements[ 4 ] *= invSY;
  795. matrix.elements[ 5 ] *= invSY;
  796. matrix.elements[ 6 ] *= invSY;
  797. matrix.elements[ 8 ] *= invSZ;
  798. matrix.elements[ 9 ] *= invSZ;
  799. matrix.elements[ 10 ] *= invSZ;
  800. quaternion.setFromRotationMatrix( matrix );
  801. scale.x = sx;
  802. scale.y = sy;
  803. scale.z = sz;
  804. return this;
  805. };
  806. }(),
  807. makePerspective: function ( left, right, top, bottom, near, far ) {
  808. if ( far === undefined ) {
  809. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  810. }
  811. var te = this.elements;
  812. var x = 2 * near / ( right - left );
  813. var y = 2 * near / ( top - bottom );
  814. var a = ( right + left ) / ( right - left );
  815. var b = ( top + bottom ) / ( top - bottom );
  816. var c = - ( far + near ) / ( far - near );
  817. var d = - 2 * far * near / ( far - near );
  818. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  819. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  820. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  821. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  822. return this;
  823. },
  824. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  825. var te = this.elements;
  826. var w = 1.0 / ( right - left );
  827. var h = 1.0 / ( top - bottom );
  828. var p = 1.0 / ( far - near );
  829. var x = ( right + left ) * w;
  830. var y = ( top + bottom ) * h;
  831. var z = ( far + near ) * p;
  832. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  833. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  834. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  835. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  836. return this;
  837. },
  838. equals: function ( matrix ) {
  839. var te = this.elements;
  840. var me = matrix.elements;
  841. for ( var i = 0; i < 16; i ++ ) {
  842. if ( te[ i ] !== me[ i ] ) return false;
  843. }
  844. return true;
  845. },
  846. fromArray: function ( array, offset ) {
  847. if ( offset === undefined ) offset = 0;
  848. for( var i = 0; i < 16; i ++ ) {
  849. this.elements[ i ] = array[ i + offset ];
  850. }
  851. return this;
  852. },
  853. toArray: function ( array, offset ) {
  854. if ( array === undefined ) array = [];
  855. if ( offset === undefined ) offset = 0;
  856. var te = this.elements;
  857. array[ offset ] = te[ 0 ];
  858. array[ offset + 1 ] = te[ 1 ];
  859. array[ offset + 2 ] = te[ 2 ];
  860. array[ offset + 3 ] = te[ 3 ];
  861. array[ offset + 4 ] = te[ 4 ];
  862. array[ offset + 5 ] = te[ 5 ];
  863. array[ offset + 6 ] = te[ 6 ];
  864. array[ offset + 7 ] = te[ 7 ];
  865. array[ offset + 8 ] = te[ 8 ];
  866. array[ offset + 9 ] = te[ 9 ];
  867. array[ offset + 10 ] = te[ 10 ];
  868. array[ offset + 11 ] = te[ 11 ];
  869. array[ offset + 12 ] = te[ 12 ];
  870. array[ offset + 13 ] = te[ 13 ];
  871. array[ offset + 14 ] = te[ 14 ];
  872. array[ offset + 15 ] = te[ 15 ];
  873. return array;
  874. }
  875. };
  876. /**
  877. * @author mrdoob / http://mrdoob.com/
  878. * @author *kile / http://kile.stravaganza.org/
  879. * @author philogb / http://blog.thejit.org/
  880. * @author mikael emtinger / http://gomo.se/
  881. * @author egraether / http://egraether.com/
  882. * @author WestLangley / http://github.com/WestLangley
  883. */
  884. function Vector3( x, y, z ) {
  885. this.x = x || 0;
  886. this.y = y || 0;
  887. this.z = z || 0;
  888. }
  889. Vector3.prototype = {
  890. constructor: Vector3,
  891. isVector3: true,
  892. set: function ( x, y, z ) {
  893. this.x = x;
  894. this.y = y;
  895. this.z = z;
  896. return this;
  897. },
  898. setScalar: function ( scalar ) {
  899. this.x = scalar;
  900. this.y = scalar;
  901. this.z = scalar;
  902. return this;
  903. },
  904. setX: function ( x ) {
  905. this.x = x;
  906. return this;
  907. },
  908. setY: function ( y ) {
  909. this.y = y;
  910. return this;
  911. },
  912. setZ: function ( z ) {
  913. this.z = z;
  914. return this;
  915. },
  916. setComponent: function ( index, value ) {
  917. switch ( index ) {
  918. case 0: this.x = value; break;
  919. case 1: this.y = value; break;
  920. case 2: this.z = value; break;
  921. default: throw new Error( 'index is out of range: ' + index );
  922. }
  923. return this;
  924. },
  925. getComponent: function ( index ) {
  926. switch ( index ) {
  927. case 0: return this.x;
  928. case 1: return this.y;
  929. case 2: return this.z;
  930. default: throw new Error( 'index is out of range: ' + index );
  931. }
  932. },
  933. clone: function () {
  934. return new this.constructor( this.x, this.y, this.z );
  935. },
  936. copy: function ( v ) {
  937. this.x = v.x;
  938. this.y = v.y;
  939. this.z = v.z;
  940. return this;
  941. },
  942. add: function ( v, w ) {
  943. if ( w !== undefined ) {
  944. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  945. return this.addVectors( v, w );
  946. }
  947. this.x += v.x;
  948. this.y += v.y;
  949. this.z += v.z;
  950. return this;
  951. },
  952. addScalar: function ( s ) {
  953. this.x += s;
  954. this.y += s;
  955. this.z += s;
  956. return this;
  957. },
  958. addVectors: function ( a, b ) {
  959. this.x = a.x + b.x;
  960. this.y = a.y + b.y;
  961. this.z = a.z + b.z;
  962. return this;
  963. },
  964. addScaledVector: function ( v, s ) {
  965. this.x += v.x * s;
  966. this.y += v.y * s;
  967. this.z += v.z * s;
  968. return this;
  969. },
  970. sub: function ( v, w ) {
  971. if ( w !== undefined ) {
  972. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  973. return this.subVectors( v, w );
  974. }
  975. this.x -= v.x;
  976. this.y -= v.y;
  977. this.z -= v.z;
  978. return this;
  979. },
  980. subScalar: function ( s ) {
  981. this.x -= s;
  982. this.y -= s;
  983. this.z -= s;
  984. return this;
  985. },
  986. subVectors: function ( a, b ) {
  987. this.x = a.x - b.x;
  988. this.y = a.y - b.y;
  989. this.z = a.z - b.z;
  990. return this;
  991. },
  992. multiply: function ( v, w ) {
  993. if ( w !== undefined ) {
  994. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  995. return this.multiplyVectors( v, w );
  996. }
  997. this.x *= v.x;
  998. this.y *= v.y;
  999. this.z *= v.z;
  1000. return this;
  1001. },
  1002. multiplyScalar: function ( scalar ) {
  1003. if ( isFinite( scalar ) ) {
  1004. this.x *= scalar;
  1005. this.y *= scalar;
  1006. this.z *= scalar;
  1007. } else {
  1008. this.x = 0;
  1009. this.y = 0;
  1010. this.z = 0;
  1011. }
  1012. return this;
  1013. },
  1014. multiplyVectors: function ( a, b ) {
  1015. this.x = a.x * b.x;
  1016. this.y = a.y * b.y;
  1017. this.z = a.z * b.z;
  1018. return this;
  1019. },
  1020. applyEuler: function () {
  1021. var quaternion;
  1022. return function applyEuler( euler ) {
  1023. if ( (euler && euler.isEuler) === false ) {
  1024. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1025. }
  1026. if ( quaternion === undefined ) quaternion = new Quaternion();
  1027. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1028. };
  1029. }(),
  1030. applyAxisAngle: function () {
  1031. var quaternion;
  1032. return function applyAxisAngle( axis, angle ) {
  1033. if ( quaternion === undefined ) quaternion = new Quaternion();
  1034. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1035. };
  1036. }(),
  1037. applyMatrix3: function ( m ) {
  1038. var x = this.x, y = this.y, z = this.z;
  1039. var e = m.elements;
  1040. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1041. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1042. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1043. return this;
  1044. },
  1045. applyMatrix4: function ( m ) {
  1046. var x = this.x, y = this.y, z = this.z;
  1047. var e = m.elements;
  1048. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1049. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1050. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1051. var w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ];
  1052. return this.divideScalar( w );
  1053. },
  1054. applyQuaternion: function ( q ) {
  1055. var x = this.x, y = this.y, z = this.z;
  1056. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1057. // calculate quat * vector
  1058. var ix = qw * x + qy * z - qz * y;
  1059. var iy = qw * y + qz * x - qx * z;
  1060. var iz = qw * z + qx * y - qy * x;
  1061. var iw = - qx * x - qy * y - qz * z;
  1062. // calculate result * inverse quat
  1063. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1064. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1065. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1066. return this;
  1067. },
  1068. project: function () {
  1069. var matrix;
  1070. return function project( camera ) {
  1071. if ( matrix === undefined ) matrix = new Matrix4();
  1072. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1073. return this.applyMatrix4( matrix );
  1074. };
  1075. }(),
  1076. unproject: function () {
  1077. var matrix;
  1078. return function unproject( camera ) {
  1079. if ( matrix === undefined ) matrix = new Matrix4();
  1080. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1081. return this.applyMatrix4( matrix );
  1082. };
  1083. }(),
  1084. transformDirection: function ( m ) {
  1085. // input: THREE.Matrix4 affine matrix
  1086. // vector interpreted as a direction
  1087. var x = this.x, y = this.y, z = this.z;
  1088. var e = m.elements;
  1089. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1090. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1091. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1092. return this.normalize();
  1093. },
  1094. divide: function ( v ) {
  1095. this.x /= v.x;
  1096. this.y /= v.y;
  1097. this.z /= v.z;
  1098. return this;
  1099. },
  1100. divideScalar: function ( scalar ) {
  1101. return this.multiplyScalar( 1 / scalar );
  1102. },
  1103. min: function ( v ) {
  1104. this.x = Math.min( this.x, v.x );
  1105. this.y = Math.min( this.y, v.y );
  1106. this.z = Math.min( this.z, v.z );
  1107. return this;
  1108. },
  1109. max: function ( v ) {
  1110. this.x = Math.max( this.x, v.x );
  1111. this.y = Math.max( this.y, v.y );
  1112. this.z = Math.max( this.z, v.z );
  1113. return this;
  1114. },
  1115. clamp: function ( min, max ) {
  1116. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1117. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1118. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1119. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1120. return this;
  1121. },
  1122. clampScalar: function () {
  1123. var min, max;
  1124. return function clampScalar( minVal, maxVal ) {
  1125. if ( min === undefined ) {
  1126. min = new Vector3();
  1127. max = new Vector3();
  1128. }
  1129. min.set( minVal, minVal, minVal );
  1130. max.set( maxVal, maxVal, maxVal );
  1131. return this.clamp( min, max );
  1132. };
  1133. }(),
  1134. clampLength: function ( min, max ) {
  1135. var length = this.length();
  1136. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1137. },
  1138. floor: function () {
  1139. this.x = Math.floor( this.x );
  1140. this.y = Math.floor( this.y );
  1141. this.z = Math.floor( this.z );
  1142. return this;
  1143. },
  1144. ceil: function () {
  1145. this.x = Math.ceil( this.x );
  1146. this.y = Math.ceil( this.y );
  1147. this.z = Math.ceil( this.z );
  1148. return this;
  1149. },
  1150. round: function () {
  1151. this.x = Math.round( this.x );
  1152. this.y = Math.round( this.y );
  1153. this.z = Math.round( this.z );
  1154. return this;
  1155. },
  1156. roundToZero: function () {
  1157. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1158. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1159. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1160. return this;
  1161. },
  1162. negate: function () {
  1163. this.x = - this.x;
  1164. this.y = - this.y;
  1165. this.z = - this.z;
  1166. return this;
  1167. },
  1168. dot: function ( v ) {
  1169. return this.x * v.x + this.y * v.y + this.z * v.z;
  1170. },
  1171. lengthSq: function () {
  1172. return this.x * this.x + this.y * this.y + this.z * this.z;
  1173. },
  1174. length: function () {
  1175. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1176. },
  1177. lengthManhattan: function () {
  1178. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1179. },
  1180. normalize: function () {
  1181. return this.divideScalar( this.length() );
  1182. },
  1183. setLength: function ( length ) {
  1184. return this.multiplyScalar( length / this.length() );
  1185. },
  1186. lerp: function ( v, alpha ) {
  1187. this.x += ( v.x - this.x ) * alpha;
  1188. this.y += ( v.y - this.y ) * alpha;
  1189. this.z += ( v.z - this.z ) * alpha;
  1190. return this;
  1191. },
  1192. lerpVectors: function ( v1, v2, alpha ) {
  1193. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1194. },
  1195. cross: function ( v, w ) {
  1196. if ( w !== undefined ) {
  1197. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1198. return this.crossVectors( v, w );
  1199. }
  1200. var x = this.x, y = this.y, z = this.z;
  1201. this.x = y * v.z - z * v.y;
  1202. this.y = z * v.x - x * v.z;
  1203. this.z = x * v.y - y * v.x;
  1204. return this;
  1205. },
  1206. crossVectors: function ( a, b ) {
  1207. var ax = a.x, ay = a.y, az = a.z;
  1208. var bx = b.x, by = b.y, bz = b.z;
  1209. this.x = ay * bz - az * by;
  1210. this.y = az * bx - ax * bz;
  1211. this.z = ax * by - ay * bx;
  1212. return this;
  1213. },
  1214. projectOnVector: function ( vector ) {
  1215. var scalar = vector.dot( this ) / vector.lengthSq();
  1216. return this.copy( vector ).multiplyScalar( scalar );
  1217. },
  1218. projectOnPlane: function () {
  1219. var v1;
  1220. return function projectOnPlane( planeNormal ) {
  1221. if ( v1 === undefined ) v1 = new Vector3();
  1222. v1.copy( this ).projectOnVector( planeNormal );
  1223. return this.sub( v1 );
  1224. };
  1225. }(),
  1226. reflect: function () {
  1227. // reflect incident vector off plane orthogonal to normal
  1228. // normal is assumed to have unit length
  1229. var v1;
  1230. return function reflect( normal ) {
  1231. if ( v1 === undefined ) v1 = new Vector3();
  1232. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1233. };
  1234. }(),
  1235. angleTo: function ( v ) {
  1236. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1237. // clamp, to handle numerical problems
  1238. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  1239. },
  1240. distanceTo: function ( v ) {
  1241. return Math.sqrt( this.distanceToSquared( v ) );
  1242. },
  1243. distanceToSquared: function ( v ) {
  1244. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1245. return dx * dx + dy * dy + dz * dz;
  1246. },
  1247. distanceToManhattan: function ( v ) {
  1248. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1249. },
  1250. setFromSpherical: function( s ) {
  1251. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1252. this.x = sinPhiRadius * Math.sin( s.theta );
  1253. this.y = Math.cos( s.phi ) * s.radius;
  1254. this.z = sinPhiRadius * Math.cos( s.theta );
  1255. return this;
  1256. },
  1257. setFromCylindrical: function( c ) {
  1258. this.x = c.radius * Math.sin( c.theta );
  1259. this.y = c.y;
  1260. this.z = c.radius * Math.cos( c.theta );
  1261. return this;
  1262. },
  1263. setFromMatrixPosition: function ( m ) {
  1264. return this.setFromMatrixColumn( m, 3 );
  1265. },
  1266. setFromMatrixScale: function ( m ) {
  1267. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1268. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1269. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1270. this.x = sx;
  1271. this.y = sy;
  1272. this.z = sz;
  1273. return this;
  1274. },
  1275. setFromMatrixColumn: function ( m, index ) {
  1276. if ( typeof m === 'number' ) {
  1277. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  1278. var temp = m;
  1279. m = index;
  1280. index = temp;
  1281. }
  1282. return this.fromArray( m.elements, index * 4 );
  1283. },
  1284. equals: function ( v ) {
  1285. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1286. },
  1287. fromArray: function ( array, offset ) {
  1288. if ( offset === undefined ) offset = 0;
  1289. this.x = array[ offset ];
  1290. this.y = array[ offset + 1 ];
  1291. this.z = array[ offset + 2 ];
  1292. return this;
  1293. },
  1294. toArray: function ( array, offset ) {
  1295. if ( array === undefined ) array = [];
  1296. if ( offset === undefined ) offset = 0;
  1297. array[ offset ] = this.x;
  1298. array[ offset + 1 ] = this.y;
  1299. array[ offset + 2 ] = this.z;
  1300. return array;
  1301. },
  1302. fromBufferAttribute: function ( attribute, index, offset ) {
  1303. if ( offset !== undefined ) {
  1304. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  1305. }
  1306. this.x = attribute.getX( index );
  1307. this.y = attribute.getY( index );
  1308. this.z = attribute.getZ( index );
  1309. return this;
  1310. }
  1311. };
  1312. /**
  1313. * @author mikael emtinger / http://gomo.se/
  1314. * @author alteredq / http://alteredqualia.com/
  1315. * @author WestLangley / http://github.com/WestLangley
  1316. * @author bhouston / http://clara.io
  1317. */
  1318. function Quaternion( x, y, z, w ) {
  1319. this._x = x || 0;
  1320. this._y = y || 0;
  1321. this._z = z || 0;
  1322. this._w = ( w !== undefined ) ? w : 1;
  1323. }
  1324. Quaternion.prototype = {
  1325. constructor: Quaternion,
  1326. get x () {
  1327. return this._x;
  1328. },
  1329. set x ( value ) {
  1330. this._x = value;
  1331. this.onChangeCallback();
  1332. },
  1333. get y () {
  1334. return this._y;
  1335. },
  1336. set y ( value ) {
  1337. this._y = value;
  1338. this.onChangeCallback();
  1339. },
  1340. get z () {
  1341. return this._z;
  1342. },
  1343. set z ( value ) {
  1344. this._z = value;
  1345. this.onChangeCallback();
  1346. },
  1347. get w () {
  1348. return this._w;
  1349. },
  1350. set w ( value ) {
  1351. this._w = value;
  1352. this.onChangeCallback();
  1353. },
  1354. set: function ( x, y, z, w ) {
  1355. this._x = x;
  1356. this._y = y;
  1357. this._z = z;
  1358. this._w = w;
  1359. this.onChangeCallback();
  1360. return this;
  1361. },
  1362. clone: function () {
  1363. return new this.constructor( this._x, this._y, this._z, this._w );
  1364. },
  1365. copy: function ( quaternion ) {
  1366. this._x = quaternion.x;
  1367. this._y = quaternion.y;
  1368. this._z = quaternion.z;
  1369. this._w = quaternion.w;
  1370. this.onChangeCallback();
  1371. return this;
  1372. },
  1373. setFromEuler: function ( euler, update ) {
  1374. if ( (euler && euler.isEuler) === false ) {
  1375. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1376. }
  1377. // http://www.mathworks.com/matlabcentral/fileexchange/
  1378. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1379. // content/SpinCalc.m
  1380. var c1 = Math.cos( euler._x / 2 );
  1381. var c2 = Math.cos( euler._y / 2 );
  1382. var c3 = Math.cos( euler._z / 2 );
  1383. var s1 = Math.sin( euler._x / 2 );
  1384. var s2 = Math.sin( euler._y / 2 );
  1385. var s3 = Math.sin( euler._z / 2 );
  1386. var order = euler.order;
  1387. if ( order === 'XYZ' ) {
  1388. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1389. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1390. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1391. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1392. } else if ( order === 'YXZ' ) {
  1393. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1394. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1395. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1396. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1397. } else if ( order === 'ZXY' ) {
  1398. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1399. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1400. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1401. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1402. } else if ( order === 'ZYX' ) {
  1403. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1404. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1405. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1406. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1407. } else if ( order === 'YZX' ) {
  1408. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1409. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1410. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1411. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1412. } else if ( order === 'XZY' ) {
  1413. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1414. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1415. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1416. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1417. }
  1418. if ( update !== false ) this.onChangeCallback();
  1419. return this;
  1420. },
  1421. setFromAxisAngle: function ( axis, angle ) {
  1422. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1423. // assumes axis is normalized
  1424. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1425. this._x = axis.x * s;
  1426. this._y = axis.y * s;
  1427. this._z = axis.z * s;
  1428. this._w = Math.cos( halfAngle );
  1429. this.onChangeCallback();
  1430. return this;
  1431. },
  1432. setFromRotationMatrix: function ( m ) {
  1433. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1434. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1435. var te = m.elements,
  1436. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1437. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1438. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1439. trace = m11 + m22 + m33,
  1440. s;
  1441. if ( trace > 0 ) {
  1442. s = 0.5 / Math.sqrt( trace + 1.0 );
  1443. this._w = 0.25 / s;
  1444. this._x = ( m32 - m23 ) * s;
  1445. this._y = ( m13 - m31 ) * s;
  1446. this._z = ( m21 - m12 ) * s;
  1447. } else if ( m11 > m22 && m11 > m33 ) {
  1448. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1449. this._w = ( m32 - m23 ) / s;
  1450. this._x = 0.25 * s;
  1451. this._y = ( m12 + m21 ) / s;
  1452. this._z = ( m13 + m31 ) / s;
  1453. } else if ( m22 > m33 ) {
  1454. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1455. this._w = ( m13 - m31 ) / s;
  1456. this._x = ( m12 + m21 ) / s;
  1457. this._y = 0.25 * s;
  1458. this._z = ( m23 + m32 ) / s;
  1459. } else {
  1460. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1461. this._w = ( m21 - m12 ) / s;
  1462. this._x = ( m13 + m31 ) / s;
  1463. this._y = ( m23 + m32 ) / s;
  1464. this._z = 0.25 * s;
  1465. }
  1466. this.onChangeCallback();
  1467. return this;
  1468. },
  1469. setFromUnitVectors: function () {
  1470. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  1471. // assumes direction vectors vFrom and vTo are normalized
  1472. var v1, r;
  1473. var EPS = 0.000001;
  1474. return function setFromUnitVectors( vFrom, vTo ) {
  1475. if ( v1 === undefined ) v1 = new Vector3();
  1476. r = vFrom.dot( vTo ) + 1;
  1477. if ( r < EPS ) {
  1478. r = 0;
  1479. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1480. v1.set( - vFrom.y, vFrom.x, 0 );
  1481. } else {
  1482. v1.set( 0, - vFrom.z, vFrom.y );
  1483. }
  1484. } else {
  1485. v1.crossVectors( vFrom, vTo );
  1486. }
  1487. this._x = v1.x;
  1488. this._y = v1.y;
  1489. this._z = v1.z;
  1490. this._w = r;
  1491. return this.normalize();
  1492. };
  1493. }(),
  1494. inverse: function () {
  1495. return this.conjugate().normalize();
  1496. },
  1497. conjugate: function () {
  1498. this._x *= - 1;
  1499. this._y *= - 1;
  1500. this._z *= - 1;
  1501. this.onChangeCallback();
  1502. return this;
  1503. },
  1504. dot: function ( v ) {
  1505. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1506. },
  1507. lengthSq: function () {
  1508. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1509. },
  1510. length: function () {
  1511. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1512. },
  1513. normalize: function () {
  1514. var l = this.length();
  1515. if ( l === 0 ) {
  1516. this._x = 0;
  1517. this._y = 0;
  1518. this._z = 0;
  1519. this._w = 1;
  1520. } else {
  1521. l = 1 / l;
  1522. this._x = this._x * l;
  1523. this._y = this._y * l;
  1524. this._z = this._z * l;
  1525. this._w = this._w * l;
  1526. }
  1527. this.onChangeCallback();
  1528. return this;
  1529. },
  1530. multiply: function ( q, p ) {
  1531. if ( p !== undefined ) {
  1532. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1533. return this.multiplyQuaternions( q, p );
  1534. }
  1535. return this.multiplyQuaternions( this, q );
  1536. },
  1537. premultiply: function ( q ) {
  1538. return this.multiplyQuaternions( q, this );
  1539. },
  1540. multiplyQuaternions: function ( a, b ) {
  1541. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1542. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1543. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1544. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1545. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1546. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1547. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1548. this.onChangeCallback();
  1549. return this;
  1550. },
  1551. slerp: function ( qb, t ) {
  1552. if ( t === 0 ) return this;
  1553. if ( t === 1 ) return this.copy( qb );
  1554. var x = this._x, y = this._y, z = this._z, w = this._w;
  1555. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1556. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1557. if ( cosHalfTheta < 0 ) {
  1558. this._w = - qb._w;
  1559. this._x = - qb._x;
  1560. this._y = - qb._y;
  1561. this._z = - qb._z;
  1562. cosHalfTheta = - cosHalfTheta;
  1563. } else {
  1564. this.copy( qb );
  1565. }
  1566. if ( cosHalfTheta >= 1.0 ) {
  1567. this._w = w;
  1568. this._x = x;
  1569. this._y = y;
  1570. this._z = z;
  1571. return this;
  1572. }
  1573. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1574. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1575. this._w = 0.5 * ( w + this._w );
  1576. this._x = 0.5 * ( x + this._x );
  1577. this._y = 0.5 * ( y + this._y );
  1578. this._z = 0.5 * ( z + this._z );
  1579. return this;
  1580. }
  1581. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1582. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1583. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1584. this._w = ( w * ratioA + this._w * ratioB );
  1585. this._x = ( x * ratioA + this._x * ratioB );
  1586. this._y = ( y * ratioA + this._y * ratioB );
  1587. this._z = ( z * ratioA + this._z * ratioB );
  1588. this.onChangeCallback();
  1589. return this;
  1590. },
  1591. equals: function ( quaternion ) {
  1592. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1593. },
  1594. fromArray: function ( array, offset ) {
  1595. if ( offset === undefined ) offset = 0;
  1596. this._x = array[ offset ];
  1597. this._y = array[ offset + 1 ];
  1598. this._z = array[ offset + 2 ];
  1599. this._w = array[ offset + 3 ];
  1600. this.onChangeCallback();
  1601. return this;
  1602. },
  1603. toArray: function ( array, offset ) {
  1604. if ( array === undefined ) array = [];
  1605. if ( offset === undefined ) offset = 0;
  1606. array[ offset ] = this._x;
  1607. array[ offset + 1 ] = this._y;
  1608. array[ offset + 2 ] = this._z;
  1609. array[ offset + 3 ] = this._w;
  1610. return array;
  1611. },
  1612. onChange: function ( callback ) {
  1613. this.onChangeCallback = callback;
  1614. return this;
  1615. },
  1616. onChangeCallback: function () {}
  1617. };
  1618. Object.assign( Quaternion, {
  1619. slerp: function( qa, qb, qm, t ) {
  1620. return qm.copy( qa ).slerp( qb, t );
  1621. },
  1622. slerpFlat: function(
  1623. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1624. // fuzz-free, array-based Quaternion SLERP operation
  1625. var x0 = src0[ srcOffset0 + 0 ],
  1626. y0 = src0[ srcOffset0 + 1 ],
  1627. z0 = src0[ srcOffset0 + 2 ],
  1628. w0 = src0[ srcOffset0 + 3 ],
  1629. x1 = src1[ srcOffset1 + 0 ],
  1630. y1 = src1[ srcOffset1 + 1 ],
  1631. z1 = src1[ srcOffset1 + 2 ],
  1632. w1 = src1[ srcOffset1 + 3 ];
  1633. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1634. var s = 1 - t,
  1635. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1636. dir = ( cos >= 0 ? 1 : - 1 ),
  1637. sqrSin = 1 - cos * cos;
  1638. // Skip the Slerp for tiny steps to avoid numeric problems:
  1639. if ( sqrSin > Number.EPSILON ) {
  1640. var sin = Math.sqrt( sqrSin ),
  1641. len = Math.atan2( sin, cos * dir );
  1642. s = Math.sin( s * len ) / sin;
  1643. t = Math.sin( t * len ) / sin;
  1644. }
  1645. var tDir = t * dir;
  1646. x0 = x0 * s + x1 * tDir;
  1647. y0 = y0 * s + y1 * tDir;
  1648. z0 = z0 * s + z1 * tDir;
  1649. w0 = w0 * s + w1 * tDir;
  1650. // Normalize in case we just did a lerp:
  1651. if ( s === 1 - t ) {
  1652. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1653. x0 *= f;
  1654. y0 *= f;
  1655. z0 *= f;
  1656. w0 *= f;
  1657. }
  1658. }
  1659. dst[ dstOffset ] = x0;
  1660. dst[ dstOffset + 1 ] = y0;
  1661. dst[ dstOffset + 2 ] = z0;
  1662. dst[ dstOffset + 3 ] = w0;
  1663. }
  1664. } );
  1665. /**
  1666. * https://github.com/mrdoob/eventdispatcher.js/
  1667. */
  1668. function EventDispatcher() {}
  1669. EventDispatcher.prototype = {
  1670. addEventListener: function ( type, listener ) {
  1671. if ( this._listeners === undefined ) this._listeners = {};
  1672. var listeners = this._listeners;
  1673. if ( listeners[ type ] === undefined ) {
  1674. listeners[ type ] = [];
  1675. }
  1676. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1677. listeners[ type ].push( listener );
  1678. }
  1679. },
  1680. hasEventListener: function ( type, listener ) {
  1681. if ( this._listeners === undefined ) return false;
  1682. var listeners = this._listeners;
  1683. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  1684. },
  1685. removeEventListener: function ( type, listener ) {
  1686. if ( this._listeners === undefined ) return;
  1687. var listeners = this._listeners;
  1688. var listenerArray = listeners[ type ];
  1689. if ( listenerArray !== undefined ) {
  1690. var index = listenerArray.indexOf( listener );
  1691. if ( index !== - 1 ) {
  1692. listenerArray.splice( index, 1 );
  1693. }
  1694. }
  1695. },
  1696. dispatchEvent: function ( event ) {
  1697. if ( this._listeners === undefined ) return;
  1698. var listeners = this._listeners;
  1699. var listenerArray = listeners[ event.type ];
  1700. if ( listenerArray !== undefined ) {
  1701. event.target = this;
  1702. var array = [], i = 0;
  1703. var length = listenerArray.length;
  1704. for ( i = 0; i < length; i ++ ) {
  1705. array[ i ] = listenerArray[ i ];
  1706. }
  1707. for ( i = 0; i < length; i ++ ) {
  1708. array[ i ].call( this, event );
  1709. }
  1710. }
  1711. }
  1712. };
  1713. /**
  1714. * @author mrdoob / http://mrdoob.com/
  1715. * @author WestLangley / http://github.com/WestLangley
  1716. * @author bhouston / http://clara.io
  1717. */
  1718. function Euler( x, y, z, order ) {
  1719. this._x = x || 0;
  1720. this._y = y || 0;
  1721. this._z = z || 0;
  1722. this._order = order || Euler.DefaultOrder;
  1723. }
  1724. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1725. Euler.DefaultOrder = 'XYZ';
  1726. Euler.prototype = {
  1727. constructor: Euler,
  1728. isEuler: true,
  1729. get x () {
  1730. return this._x;
  1731. },
  1732. set x ( value ) {
  1733. this._x = value;
  1734. this.onChangeCallback();
  1735. },
  1736. get y () {
  1737. return this._y;
  1738. },
  1739. set y ( value ) {
  1740. this._y = value;
  1741. this.onChangeCallback();
  1742. },
  1743. get z () {
  1744. return this._z;
  1745. },
  1746. set z ( value ) {
  1747. this._z = value;
  1748. this.onChangeCallback();
  1749. },
  1750. get order () {
  1751. return this._order;
  1752. },
  1753. set order ( value ) {
  1754. this._order = value;
  1755. this.onChangeCallback();
  1756. },
  1757. set: function ( x, y, z, order ) {
  1758. this._x = x;
  1759. this._y = y;
  1760. this._z = z;
  1761. this._order = order || this._order;
  1762. this.onChangeCallback();
  1763. return this;
  1764. },
  1765. clone: function () {
  1766. return new this.constructor( this._x, this._y, this._z, this._order );
  1767. },
  1768. copy: function ( euler ) {
  1769. this._x = euler._x;
  1770. this._y = euler._y;
  1771. this._z = euler._z;
  1772. this._order = euler._order;
  1773. this.onChangeCallback();
  1774. return this;
  1775. },
  1776. setFromRotationMatrix: function ( m, order, update ) {
  1777. var clamp = _Math.clamp;
  1778. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1779. var te = m.elements;
  1780. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  1781. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  1782. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1783. order = order || this._order;
  1784. if ( order === 'XYZ' ) {
  1785. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  1786. if ( Math.abs( m13 ) < 0.99999 ) {
  1787. this._x = Math.atan2( - m23, m33 );
  1788. this._z = Math.atan2( - m12, m11 );
  1789. } else {
  1790. this._x = Math.atan2( m32, m22 );
  1791. this._z = 0;
  1792. }
  1793. } else if ( order === 'YXZ' ) {
  1794. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  1795. if ( Math.abs( m23 ) < 0.99999 ) {
  1796. this._y = Math.atan2( m13, m33 );
  1797. this._z = Math.atan2( m21, m22 );
  1798. } else {
  1799. this._y = Math.atan2( - m31, m11 );
  1800. this._z = 0;
  1801. }
  1802. } else if ( order === 'ZXY' ) {
  1803. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  1804. if ( Math.abs( m32 ) < 0.99999 ) {
  1805. this._y = Math.atan2( - m31, m33 );
  1806. this._z = Math.atan2( - m12, m22 );
  1807. } else {
  1808. this._y = 0;
  1809. this._z = Math.atan2( m21, m11 );
  1810. }
  1811. } else if ( order === 'ZYX' ) {
  1812. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  1813. if ( Math.abs( m31 ) < 0.99999 ) {
  1814. this._x = Math.atan2( m32, m33 );
  1815. this._z = Math.atan2( m21, m11 );
  1816. } else {
  1817. this._x = 0;
  1818. this._z = Math.atan2( - m12, m22 );
  1819. }
  1820. } else if ( order === 'YZX' ) {
  1821. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  1822. if ( Math.abs( m21 ) < 0.99999 ) {
  1823. this._x = Math.atan2( - m23, m22 );
  1824. this._y = Math.atan2( - m31, m11 );
  1825. } else {
  1826. this._x = 0;
  1827. this._y = Math.atan2( m13, m33 );
  1828. }
  1829. } else if ( order === 'XZY' ) {
  1830. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  1831. if ( Math.abs( m12 ) < 0.99999 ) {
  1832. this._x = Math.atan2( m32, m22 );
  1833. this._y = Math.atan2( m13, m11 );
  1834. } else {
  1835. this._x = Math.atan2( - m23, m33 );
  1836. this._y = 0;
  1837. }
  1838. } else {
  1839. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  1840. }
  1841. this._order = order;
  1842. if ( update !== false ) this.onChangeCallback();
  1843. return this;
  1844. },
  1845. setFromQuaternion: function () {
  1846. var matrix;
  1847. return function setFromQuaternion( q, order, update ) {
  1848. if ( matrix === undefined ) matrix = new Matrix4();
  1849. matrix.makeRotationFromQuaternion( q );
  1850. return this.setFromRotationMatrix( matrix, order, update );
  1851. };
  1852. }(),
  1853. setFromVector3: function ( v, order ) {
  1854. return this.set( v.x, v.y, v.z, order || this._order );
  1855. },
  1856. reorder: function () {
  1857. // WARNING: this discards revolution information -bhouston
  1858. var q = new Quaternion();
  1859. return function reorder( newOrder ) {
  1860. q.setFromEuler( this );
  1861. return this.setFromQuaternion( q, newOrder );
  1862. };
  1863. }(),
  1864. equals: function ( euler ) {
  1865. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1866. },
  1867. fromArray: function ( array ) {
  1868. this._x = array[ 0 ];
  1869. this._y = array[ 1 ];
  1870. this._z = array[ 2 ];
  1871. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1872. this.onChangeCallback();
  1873. return this;
  1874. },
  1875. toArray: function ( array, offset ) {
  1876. if ( array === undefined ) array = [];
  1877. if ( offset === undefined ) offset = 0;
  1878. array[ offset ] = this._x;
  1879. array[ offset + 1 ] = this._y;
  1880. array[ offset + 2 ] = this._z;
  1881. array[ offset + 3 ] = this._order;
  1882. return array;
  1883. },
  1884. toVector3: function ( optionalResult ) {
  1885. if ( optionalResult ) {
  1886. return optionalResult.set( this._x, this._y, this._z );
  1887. } else {
  1888. return new Vector3( this._x, this._y, this._z );
  1889. }
  1890. },
  1891. onChange: function ( callback ) {
  1892. this.onChangeCallback = callback;
  1893. return this;
  1894. },
  1895. onChangeCallback: function () {}
  1896. };
  1897. /**
  1898. * @author mrdoob / http://mrdoob.com/
  1899. */
  1900. function Layers() {
  1901. this.mask = 1;
  1902. }
  1903. Layers.prototype = {
  1904. constructor: Layers,
  1905. set: function ( channel ) {
  1906. this.mask = 1 << channel;
  1907. },
  1908. enable: function ( channel ) {
  1909. this.mask |= 1 << channel;
  1910. },
  1911. toggle: function ( channel ) {
  1912. this.mask ^= 1 << channel;
  1913. },
  1914. disable: function ( channel ) {
  1915. this.mask &= ~ ( 1 << channel );
  1916. },
  1917. test: function ( layers ) {
  1918. return ( this.mask & layers.mask ) !== 0;
  1919. }
  1920. };
  1921. /**
  1922. * @author alteredq / http://alteredqualia.com/
  1923. * @author WestLangley / http://github.com/WestLangley
  1924. * @author bhouston / http://clara.io
  1925. * @author tschw
  1926. */
  1927. function Matrix3() {
  1928. this.elements = new Float32Array( [
  1929. 1, 0, 0,
  1930. 0, 1, 0,
  1931. 0, 0, 1
  1932. ] );
  1933. if ( arguments.length > 0 ) {
  1934. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  1935. }
  1936. }
  1937. Matrix3.prototype = {
  1938. constructor: Matrix3,
  1939. isMatrix3: true,
  1940. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1941. var te = this.elements;
  1942. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  1943. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  1944. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  1945. return this;
  1946. },
  1947. identity: function () {
  1948. this.set(
  1949. 1, 0, 0,
  1950. 0, 1, 0,
  1951. 0, 0, 1
  1952. );
  1953. return this;
  1954. },
  1955. clone: function () {
  1956. return new this.constructor().fromArray( this.elements );
  1957. },
  1958. copy: function ( m ) {
  1959. var me = m.elements;
  1960. this.set(
  1961. me[ 0 ], me[ 3 ], me[ 6 ],
  1962. me[ 1 ], me[ 4 ], me[ 7 ],
  1963. me[ 2 ], me[ 5 ], me[ 8 ]
  1964. );
  1965. return this;
  1966. },
  1967. setFromMatrix4: function( m ) {
  1968. var me = m.elements;
  1969. this.set(
  1970. me[ 0 ], me[ 4 ], me[ 8 ],
  1971. me[ 1 ], me[ 5 ], me[ 9 ],
  1972. me[ 2 ], me[ 6 ], me[ 10 ]
  1973. );
  1974. return this;
  1975. },
  1976. applyToBufferAttribute: function () {
  1977. var v1;
  1978. return function applyToBufferAttribute( attribute ) {
  1979. if ( v1 === undefined ) v1 = new Vector3();
  1980. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  1981. v1.x = attribute.getX( i );
  1982. v1.y = attribute.getY( i );
  1983. v1.z = attribute.getZ( i );
  1984. v1.applyMatrix3( this );
  1985. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  1986. }
  1987. return attribute;
  1988. };
  1989. }(),
  1990. multiplyScalar: function ( s ) {
  1991. var te = this.elements;
  1992. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  1993. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  1994. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  1995. return this;
  1996. },
  1997. determinant: function () {
  1998. var te = this.elements;
  1999. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2000. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2001. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2002. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2003. },
  2004. getInverse: function ( matrix, throwOnDegenerate ) {
  2005. if ( matrix && matrix.isMatrix4 ) {
  2006. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  2007. }
  2008. var me = matrix.elements,
  2009. te = this.elements,
  2010. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  2011. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  2012. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  2013. t11 = n33 * n22 - n32 * n23,
  2014. t12 = n32 * n13 - n33 * n12,
  2015. t13 = n23 * n12 - n22 * n13,
  2016. det = n11 * t11 + n21 * t12 + n31 * t13;
  2017. if ( det === 0 ) {
  2018. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2019. if ( throwOnDegenerate === true ) {
  2020. throw new Error( msg );
  2021. } else {
  2022. console.warn( msg );
  2023. }
  2024. return this.identity();
  2025. }
  2026. var detInv = 1 / det;
  2027. te[ 0 ] = t11 * detInv;
  2028. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  2029. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  2030. te[ 3 ] = t12 * detInv;
  2031. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  2032. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  2033. te[ 6 ] = t13 * detInv;
  2034. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  2035. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  2036. return this;
  2037. },
  2038. transpose: function () {
  2039. var tmp, m = this.elements;
  2040. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2041. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2042. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2043. return this;
  2044. },
  2045. getNormalMatrix: function ( matrix4 ) {
  2046. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  2047. },
  2048. transposeIntoArray: function ( r ) {
  2049. var m = this.elements;
  2050. r[ 0 ] = m[ 0 ];
  2051. r[ 1 ] = m[ 3 ];
  2052. r[ 2 ] = m[ 6 ];
  2053. r[ 3 ] = m[ 1 ];
  2054. r[ 4 ] = m[ 4 ];
  2055. r[ 5 ] = m[ 7 ];
  2056. r[ 6 ] = m[ 2 ];
  2057. r[ 7 ] = m[ 5 ];
  2058. r[ 8 ] = m[ 8 ];
  2059. return this;
  2060. },
  2061. fromArray: function ( array, offset ) {
  2062. if ( offset === undefined ) offset = 0;
  2063. for( var i = 0; i < 9; i ++ ) {
  2064. this.elements[ i ] = array[ i + offset ];
  2065. }
  2066. return this;
  2067. },
  2068. toArray: function ( array, offset ) {
  2069. if ( array === undefined ) array = [];
  2070. if ( offset === undefined ) offset = 0;
  2071. var te = this.elements;
  2072. array[ offset ] = te[ 0 ];
  2073. array[ offset + 1 ] = te[ 1 ];
  2074. array[ offset + 2 ] = te[ 2 ];
  2075. array[ offset + 3 ] = te[ 3 ];
  2076. array[ offset + 4 ] = te[ 4 ];
  2077. array[ offset + 5 ] = te[ 5 ];
  2078. array[ offset + 6 ] = te[ 6 ];
  2079. array[ offset + 7 ] = te[ 7 ];
  2080. array[ offset + 8 ] = te[ 8 ];
  2081. return array;
  2082. }
  2083. };
  2084. /**
  2085. * @author mrdoob / http://mrdoob.com/
  2086. * @author mikael emtinger / http://gomo.se/
  2087. * @author alteredq / http://alteredqualia.com/
  2088. * @author WestLangley / http://github.com/WestLangley
  2089. * @author elephantatwork / www.elephantatwork.ch
  2090. */
  2091. var object3DId = 0;
  2092. function Object3D() {
  2093. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  2094. this.uuid = _Math.generateUUID();
  2095. this.name = '';
  2096. this.type = 'Object3D';
  2097. this.parent = null;
  2098. this.children = [];
  2099. this.up = Object3D.DefaultUp.clone();
  2100. var position = new Vector3();
  2101. var rotation = new Euler();
  2102. var quaternion = new Quaternion();
  2103. var scale = new Vector3( 1, 1, 1 );
  2104. function onRotationChange() {
  2105. quaternion.setFromEuler( rotation, false );
  2106. }
  2107. function onQuaternionChange() {
  2108. rotation.setFromQuaternion( quaternion, undefined, false );
  2109. }
  2110. rotation.onChange( onRotationChange );
  2111. quaternion.onChange( onQuaternionChange );
  2112. Object.defineProperties( this, {
  2113. position: {
  2114. enumerable: true,
  2115. value: position
  2116. },
  2117. rotation: {
  2118. enumerable: true,
  2119. value: rotation
  2120. },
  2121. quaternion: {
  2122. enumerable: true,
  2123. value: quaternion
  2124. },
  2125. scale: {
  2126. enumerable: true,
  2127. value: scale
  2128. },
  2129. modelViewMatrix: {
  2130. value: new Matrix4()
  2131. },
  2132. normalMatrix: {
  2133. value: new Matrix3()
  2134. }
  2135. } );
  2136. this.matrix = new Matrix4();
  2137. this.matrixWorld = new Matrix4();
  2138. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  2139. this.matrixWorldNeedsUpdate = false;
  2140. this.layers = new Layers();
  2141. this.visible = true;
  2142. this.castShadow = false;
  2143. this.receiveShadow = false;
  2144. this.frustumCulled = true;
  2145. this.renderOrder = 0;
  2146. this.userData = {};
  2147. this.onBeforeRender = function () {};
  2148. this.onAfterRender = function () {};
  2149. }
  2150. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  2151. Object3D.DefaultMatrixAutoUpdate = true;
  2152. Object3D.prototype = {
  2153. constructor: Object3D,
  2154. isObject3D: true,
  2155. applyMatrix: function ( matrix ) {
  2156. this.matrix.multiplyMatrices( matrix, this.matrix );
  2157. this.matrix.decompose( this.position, this.quaternion, this.scale );
  2158. },
  2159. setRotationFromAxisAngle: function ( axis, angle ) {
  2160. // assumes axis is normalized
  2161. this.quaternion.setFromAxisAngle( axis, angle );
  2162. },
  2163. setRotationFromEuler: function ( euler ) {
  2164. this.quaternion.setFromEuler( euler, true );
  2165. },
  2166. setRotationFromMatrix: function ( m ) {
  2167. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2168. this.quaternion.setFromRotationMatrix( m );
  2169. },
  2170. setRotationFromQuaternion: function ( q ) {
  2171. // assumes q is normalized
  2172. this.quaternion.copy( q );
  2173. },
  2174. rotateOnAxis: function () {
  2175. // rotate object on axis in object space
  2176. // axis is assumed to be normalized
  2177. var q1 = new Quaternion();
  2178. return function rotateOnAxis( axis, angle ) {
  2179. q1.setFromAxisAngle( axis, angle );
  2180. this.quaternion.multiply( q1 );
  2181. return this;
  2182. };
  2183. }(),
  2184. rotateX: function () {
  2185. var v1 = new Vector3( 1, 0, 0 );
  2186. return function rotateX( angle ) {
  2187. return this.rotateOnAxis( v1, angle );
  2188. };
  2189. }(),
  2190. rotateY: function () {
  2191. var v1 = new Vector3( 0, 1, 0 );
  2192. return function rotateY( angle ) {
  2193. return this.rotateOnAxis( v1, angle );
  2194. };
  2195. }(),
  2196. rotateZ: function () {
  2197. var v1 = new Vector3( 0, 0, 1 );
  2198. return function rotateZ( angle ) {
  2199. return this.rotateOnAxis( v1, angle );
  2200. };
  2201. }(),
  2202. translateOnAxis: function () {
  2203. // translate object by distance along axis in object space
  2204. // axis is assumed to be normalized
  2205. var v1 = new Vector3();
  2206. return function translateOnAxis( axis, distance ) {
  2207. v1.copy( axis ).applyQuaternion( this.quaternion );
  2208. this.position.add( v1.multiplyScalar( distance ) );
  2209. return this;
  2210. };
  2211. }(),
  2212. translateX: function () {
  2213. var v1 = new Vector3( 1, 0, 0 );
  2214. return function translateX( distance ) {
  2215. return this.translateOnAxis( v1, distance );
  2216. };
  2217. }(),
  2218. translateY: function () {
  2219. var v1 = new Vector3( 0, 1, 0 );
  2220. return function translateY( distance ) {
  2221. return this.translateOnAxis( v1, distance );
  2222. };
  2223. }(),
  2224. translateZ: function () {
  2225. var v1 = new Vector3( 0, 0, 1 );
  2226. return function translateZ( distance ) {
  2227. return this.translateOnAxis( v1, distance );
  2228. };
  2229. }(),
  2230. localToWorld: function ( vector ) {
  2231. return vector.applyMatrix4( this.matrixWorld );
  2232. },
  2233. worldToLocal: function () {
  2234. var m1 = new Matrix4();
  2235. return function worldToLocal( vector ) {
  2236. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  2237. };
  2238. }(),
  2239. lookAt: function () {
  2240. // This routine does not support objects with rotated and/or translated parent(s)
  2241. var m1 = new Matrix4();
  2242. return function lookAt( vector ) {
  2243. m1.lookAt( vector, this.position, this.up );
  2244. this.quaternion.setFromRotationMatrix( m1 );
  2245. };
  2246. }(),
  2247. add: function ( object ) {
  2248. if ( arguments.length > 1 ) {
  2249. for ( var i = 0; i < arguments.length; i ++ ) {
  2250. this.add( arguments[ i ] );
  2251. }
  2252. return this;
  2253. }
  2254. if ( object === this ) {
  2255. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  2256. return this;
  2257. }
  2258. if ( ( object && object.isObject3D ) ) {
  2259. if ( object.parent !== null ) {
  2260. object.parent.remove( object );
  2261. }
  2262. object.parent = this;
  2263. object.dispatchEvent( { type: 'added' } );
  2264. this.children.push( object );
  2265. } else {
  2266. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  2267. }
  2268. return this;
  2269. },
  2270. remove: function ( object ) {
  2271. if ( arguments.length > 1 ) {
  2272. for ( var i = 0; i < arguments.length; i ++ ) {
  2273. this.remove( arguments[ i ] );
  2274. }
  2275. }
  2276. var index = this.children.indexOf( object );
  2277. if ( index !== - 1 ) {
  2278. object.parent = null;
  2279. object.dispatchEvent( { type: 'removed' } );
  2280. this.children.splice( index, 1 );
  2281. }
  2282. },
  2283. getObjectById: function ( id ) {
  2284. return this.getObjectByProperty( 'id', id );
  2285. },
  2286. getObjectByName: function ( name ) {
  2287. return this.getObjectByProperty( 'name', name );
  2288. },
  2289. getObjectByProperty: function ( name, value ) {
  2290. if ( this[ name ] === value ) return this;
  2291. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2292. var child = this.children[ i ];
  2293. var object = child.getObjectByProperty( name, value );
  2294. if ( object !== undefined ) {
  2295. return object;
  2296. }
  2297. }
  2298. return undefined;
  2299. },
  2300. getWorldPosition: function ( optionalTarget ) {
  2301. var result = optionalTarget || new Vector3();
  2302. this.updateMatrixWorld( true );
  2303. return result.setFromMatrixPosition( this.matrixWorld );
  2304. },
  2305. getWorldQuaternion: function () {
  2306. var position = new Vector3();
  2307. var scale = new Vector3();
  2308. return function getWorldQuaternion( optionalTarget ) {
  2309. var result = optionalTarget || new Quaternion();
  2310. this.updateMatrixWorld( true );
  2311. this.matrixWorld.decompose( position, result, scale );
  2312. return result;
  2313. };
  2314. }(),
  2315. getWorldRotation: function () {
  2316. var quaternion = new Quaternion();
  2317. return function getWorldRotation( optionalTarget ) {
  2318. var result = optionalTarget || new Euler();
  2319. this.getWorldQuaternion( quaternion );
  2320. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  2321. };
  2322. }(),
  2323. getWorldScale: function () {
  2324. var position = new Vector3();
  2325. var quaternion = new Quaternion();
  2326. return function getWorldScale( optionalTarget ) {
  2327. var result = optionalTarget || new Vector3();
  2328. this.updateMatrixWorld( true );
  2329. this.matrixWorld.decompose( position, quaternion, result );
  2330. return result;
  2331. };
  2332. }(),
  2333. getWorldDirection: function () {
  2334. var quaternion = new Quaternion();
  2335. return function getWorldDirection( optionalTarget ) {
  2336. var result = optionalTarget || new Vector3();
  2337. this.getWorldQuaternion( quaternion );
  2338. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  2339. };
  2340. }(),
  2341. raycast: function () {},
  2342. traverse: function ( callback ) {
  2343. callback( this );
  2344. var children = this.children;
  2345. for ( var i = 0, l = children.length; i < l; i ++ ) {
  2346. children[ i ].traverse( callback );
  2347. }
  2348. },
  2349. traverseVisible: function ( callback ) {
  2350. if ( this.visible === false ) return;
  2351. callback( this );
  2352. var children = this.children;
  2353. for ( var i = 0, l = children.length; i < l; i ++ ) {
  2354. children[ i ].traverseVisible( callback );
  2355. }
  2356. },
  2357. traverseAncestors: function ( callback ) {
  2358. var parent = this.parent;
  2359. if ( parent !== null ) {
  2360. callback( parent );
  2361. parent.traverseAncestors( callback );
  2362. }
  2363. },
  2364. updateMatrix: function () {
  2365. this.matrix.compose( this.position, this.quaternion, this.scale );
  2366. this.matrixWorldNeedsUpdate = true;
  2367. },
  2368. updateMatrixWorld: function ( force ) {
  2369. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2370. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2371. if ( this.parent === null ) {
  2372. this.matrixWorld.copy( this.matrix );
  2373. } else {
  2374. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  2375. }
  2376. this.matrixWorldNeedsUpdate = false;
  2377. force = true;
  2378. }
  2379. // update children
  2380. var children = this.children;
  2381. for ( var i = 0, l = children.length; i < l; i ++ ) {
  2382. children[ i ].updateMatrixWorld( force );
  2383. }
  2384. },
  2385. toJSON: function ( meta ) {
  2386. // meta is '' when called from JSON.stringify
  2387. var isRootObject = ( meta === undefined || meta === '' );
  2388. var output = {};
  2389. // meta is a hash used to collect geometries, materials.
  2390. // not providing it implies that this is the root object
  2391. // being serialized.
  2392. if ( isRootObject ) {
  2393. // initialize meta obj
  2394. meta = {
  2395. geometries: {},
  2396. materials: {},
  2397. textures: {},
  2398. images: {}
  2399. };
  2400. output.metadata = {
  2401. version: 4.4,
  2402. type: 'Object',
  2403. generator: 'Object3D.toJSON'
  2404. };
  2405. }
  2406. // standard Object3D serialization
  2407. var object = {};
  2408. object.uuid = this.uuid;
  2409. object.type = this.type;
  2410. if ( this.name !== '' ) object.name = this.name;
  2411. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  2412. if ( this.castShadow === true ) object.castShadow = true;
  2413. if ( this.receiveShadow === true ) object.receiveShadow = true;
  2414. if ( this.visible === false ) object.visible = false;
  2415. object.matrix = this.matrix.toArray();
  2416. //
  2417. if ( this.geometry !== undefined ) {
  2418. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  2419. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  2420. }
  2421. object.geometry = this.geometry.uuid;
  2422. }
  2423. if ( this.material !== undefined ) {
  2424. if ( meta.materials[ this.material.uuid ] === undefined ) {
  2425. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  2426. }
  2427. object.material = this.material.uuid;
  2428. }
  2429. //
  2430. if ( this.children.length > 0 ) {
  2431. object.children = [];
  2432. for ( var i = 0; i < this.children.length; i ++ ) {
  2433. object.children.push( this.children[ i ].toJSON( meta ).object );
  2434. }
  2435. }
  2436. if ( isRootObject ) {
  2437. var geometries = extractFromCache( meta.geometries );
  2438. var materials = extractFromCache( meta.materials );
  2439. var textures = extractFromCache( meta.textures );
  2440. var images = extractFromCache( meta.images );
  2441. if ( geometries.length > 0 ) output.geometries = geometries;
  2442. if ( materials.length > 0 ) output.materials = materials;
  2443. if ( textures.length > 0 ) output.textures = textures;
  2444. if ( images.length > 0 ) output.images = images;
  2445. }
  2446. output.object = object;
  2447. return output;
  2448. // extract data from the cache hash
  2449. // remove metadata on each item
  2450. // and return as array
  2451. function extractFromCache( cache ) {
  2452. var values = [];
  2453. for ( var key in cache ) {
  2454. var data = cache[ key ];
  2455. delete data.metadata;
  2456. values.push( data );
  2457. }
  2458. return values;
  2459. }
  2460. },
  2461. clone: function ( recursive ) {
  2462. return new this.constructor().copy( this, recursive );
  2463. },
  2464. copy: function ( source, recursive ) {
  2465. if ( recursive === undefined ) recursive = true;
  2466. this.name = source.name;
  2467. this.up.copy( source.up );
  2468. this.position.copy( source.position );
  2469. this.quaternion.copy( source.quaternion );
  2470. this.scale.copy( source.scale );
  2471. this.matrix.copy( source.matrix );
  2472. this.matrixWorld.copy( source.matrixWorld );
  2473. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2474. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  2475. this.layers.mask = source.layers.mask;
  2476. this.visible = source.visible;
  2477. this.castShadow = source.castShadow;
  2478. this.receiveShadow = source.receiveShadow;
  2479. this.frustumCulled = source.frustumCulled;
  2480. this.renderOrder = source.renderOrder;
  2481. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  2482. if ( recursive === true ) {
  2483. for ( var i = 0; i < source.children.length; i ++ ) {
  2484. var child = source.children[ i ];
  2485. this.add( child.clone() );
  2486. }
  2487. }
  2488. return this;
  2489. }
  2490. };
  2491. Object.assign( Object3D.prototype, EventDispatcher.prototype );
  2492. /**
  2493. * @author mrdoob / http://mrdoob.com/
  2494. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  2495. */
  2496. function Audio( listener ) {
  2497. Object3D.call( this );
  2498. this.type = 'Audio';
  2499. this.context = listener.context;
  2500. this.gain = this.context.createGain();
  2501. this.gain.connect( listener.getInput() );
  2502. this.autoplay = false;
  2503. this.buffer = null;
  2504. this.loop = false;
  2505. this.startTime = 0;
  2506. this.playbackRate = 1;
  2507. this.isPlaying = false;
  2508. this.hasPlaybackControl = true;
  2509. this.sourceType = 'empty';
  2510. this.filters = [];
  2511. }
  2512. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  2513. constructor: Audio,
  2514. getOutput: function () {
  2515. return this.gain;
  2516. },
  2517. setNodeSource: function ( audioNode ) {
  2518. this.hasPlaybackControl = false;
  2519. this.sourceType = 'audioNode';
  2520. this.source = audioNode;
  2521. this.connect();
  2522. return this;
  2523. },
  2524. setBuffer: function ( audioBuffer ) {
  2525. this.buffer = audioBuffer;
  2526. this.sourceType = 'buffer';
  2527. if ( this.autoplay ) this.play();
  2528. return this;
  2529. },
  2530. play: function () {
  2531. if ( this.isPlaying === true ) {
  2532. console.warn( 'THREE.Audio: Audio is already playing.' );
  2533. return;
  2534. }
  2535. if ( this.hasPlaybackControl === false ) {
  2536. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  2537. return;
  2538. }
  2539. var source = this.context.createBufferSource();
  2540. source.buffer = this.buffer;
  2541. source.loop = this.loop;
  2542. source.onended = this.onEnded.bind( this );
  2543. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  2544. source.start( 0, this.startTime );
  2545. this.isPlaying = true;
  2546. this.source = source;
  2547. return this.connect();
  2548. },
  2549. pause: function () {
  2550. if ( this.hasPlaybackControl === false ) {
  2551. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  2552. return;
  2553. }
  2554. this.source.stop();
  2555. this.startTime = this.context.currentTime;
  2556. this.isPlaying = false;
  2557. return this;
  2558. },
  2559. stop: function () {
  2560. if ( this.hasPlaybackControl === false ) {
  2561. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  2562. return;
  2563. }
  2564. this.source.stop();
  2565. this.startTime = 0;
  2566. this.isPlaying = false;
  2567. return this;
  2568. },
  2569. connect: function () {
  2570. if ( this.filters.length > 0 ) {
  2571. this.source.connect( this.filters[ 0 ] );
  2572. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  2573. this.filters[ i - 1 ].connect( this.filters[ i ] );
  2574. }
  2575. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  2576. } else {
  2577. this.source.connect( this.getOutput() );
  2578. }
  2579. return this;
  2580. },
  2581. disconnect: function () {
  2582. if ( this.filters.length > 0 ) {
  2583. this.source.disconnect( this.filters[ 0 ] );
  2584. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  2585. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  2586. }
  2587. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  2588. } else {
  2589. this.source.disconnect( this.getOutput() );
  2590. }
  2591. return this;
  2592. },
  2593. getFilters: function () {
  2594. return this.filters;
  2595. },
  2596. setFilters: function ( value ) {
  2597. if ( ! value ) value = [];
  2598. if ( this.isPlaying === true ) {
  2599. this.disconnect();
  2600. this.filters = value;
  2601. this.connect();
  2602. } else {
  2603. this.filters = value;
  2604. }
  2605. return this;
  2606. },
  2607. getFilter: function () {
  2608. return this.getFilters()[ 0 ];
  2609. },
  2610. setFilter: function ( filter ) {
  2611. return this.setFilters( filter ? [ filter ] : [] );
  2612. },
  2613. setPlaybackRate: function ( value ) {
  2614. if ( this.hasPlaybackControl === false ) {
  2615. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  2616. return;
  2617. }
  2618. this.playbackRate = value;
  2619. if ( this.isPlaying === true ) {
  2620. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  2621. }
  2622. return this;
  2623. },
  2624. getPlaybackRate: function () {
  2625. return this.playbackRate;
  2626. },
  2627. onEnded: function () {
  2628. this.isPlaying = false;
  2629. },
  2630. getLoop: function () {
  2631. if ( this.hasPlaybackControl === false ) {
  2632. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  2633. return false;
  2634. }
  2635. return this.loop;
  2636. },
  2637. setLoop: function ( value ) {
  2638. if ( this.hasPlaybackControl === false ) {
  2639. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  2640. return;
  2641. }
  2642. this.loop = value;
  2643. if ( this.isPlaying === true ) {
  2644. this.source.loop = this.loop;
  2645. }
  2646. return this;
  2647. },
  2648. getVolume: function () {
  2649. return this.gain.gain.value;
  2650. },
  2651. setVolume: function ( value ) {
  2652. this.gain.gain.value = value;
  2653. return this;
  2654. }
  2655. } );
  2656. /**
  2657. * @author mrdoob / http://mrdoob.com/
  2658. */
  2659. function AudioAnalyser( audio, fftSize ) {
  2660. this.analyser = audio.context.createAnalyser();
  2661. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  2662. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  2663. audio.getOutput().connect( this.analyser );
  2664. }
  2665. Object.assign( AudioAnalyser.prototype, {
  2666. getFrequencyData: function () {
  2667. this.analyser.getByteFrequencyData( this.data );
  2668. return this.data;
  2669. },
  2670. getAverageFrequency: function () {
  2671. var value = 0, data = this.getFrequencyData();
  2672. for ( var i = 0; i < data.length; i ++ ) {
  2673. value += data[ i ];
  2674. }
  2675. return value / data.length;
  2676. }
  2677. } );
  2678. /**
  2679. * @author mrdoob / http://mrdoob.com/
  2680. * @author mikael emtinger / http://gomo.se/
  2681. * @author WestLangley / http://github.com/WestLangley
  2682. */
  2683. function Camera() {
  2684. Object3D.call( this );
  2685. this.type = 'Camera';
  2686. this.matrixWorldInverse = new Matrix4();
  2687. this.projectionMatrix = new Matrix4();
  2688. }
  2689. Camera.prototype = Object.create( Object3D.prototype );
  2690. Camera.prototype.constructor = Camera;
  2691. Camera.prototype.isCamera = true;
  2692. Camera.prototype.getWorldDirection = function () {
  2693. var quaternion = new Quaternion();
  2694. return function getWorldDirection( optionalTarget ) {
  2695. var result = optionalTarget || new Vector3();
  2696. this.getWorldQuaternion( quaternion );
  2697. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  2698. };
  2699. }();
  2700. Camera.prototype.lookAt = function () {
  2701. // This routine does not support cameras with rotated and/or translated parent(s)
  2702. var m1 = new Matrix4();
  2703. return function lookAt( vector ) {
  2704. m1.lookAt( this.position, vector, this.up );
  2705. this.quaternion.setFromRotationMatrix( m1 );
  2706. };
  2707. }();
  2708. Camera.prototype.clone = function () {
  2709. return new this.constructor().copy( this );
  2710. };
  2711. Camera.prototype.copy = function ( source ) {
  2712. Object3D.prototype.copy.call( this, source );
  2713. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  2714. this.projectionMatrix.copy( source.projectionMatrix );
  2715. return this;
  2716. };
  2717. /**
  2718. * @author mrdoob / http://mrdoob.com/
  2719. * @author greggman / http://games.greggman.com/
  2720. * @author zz85 / http://www.lab4games.net/zz85/blog
  2721. * @author tschw
  2722. */
  2723. function PerspectiveCamera( fov, aspect, near, far ) {
  2724. Camera.call( this );
  2725. this.type = 'PerspectiveCamera';
  2726. this.fov = fov !== undefined ? fov : 50;
  2727. this.zoom = 1;
  2728. this.near = near !== undefined ? near : 0.1;
  2729. this.far = far !== undefined ? far : 2000;
  2730. this.focus = 10;
  2731. this.aspect = aspect !== undefined ? aspect : 1;
  2732. this.view = null;
  2733. this.filmGauge = 35; // width of the film (default in millimeters)
  2734. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  2735. this.updateProjectionMatrix();
  2736. }
  2737. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  2738. constructor: PerspectiveCamera,
  2739. isPerspectiveCamera: true,
  2740. copy: function ( source ) {
  2741. Camera.prototype.copy.call( this, source );
  2742. this.fov = source.fov;
  2743. this.zoom = source.zoom;
  2744. this.near = source.near;
  2745. this.far = source.far;
  2746. this.focus = source.focus;
  2747. this.aspect = source.aspect;
  2748. this.view = source.view === null ? null : Object.assign( {}, source.view );
  2749. this.filmGauge = source.filmGauge;
  2750. this.filmOffset = source.filmOffset;
  2751. return this;
  2752. },
  2753. /**
  2754. * Sets the FOV by focal length in respect to the current .filmGauge.
  2755. *
  2756. * The default film gauge is 35, so that the focal length can be specified for
  2757. * a 35mm (full frame) camera.
  2758. *
  2759. * Values for focal length and film gauge must have the same unit.
  2760. */
  2761. setFocalLength: function ( focalLength ) {
  2762. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  2763. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  2764. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  2765. this.updateProjectionMatrix();
  2766. },
  2767. /**
  2768. * Calculates the focal length from the current .fov and .filmGauge.
  2769. */
  2770. getFocalLength: function () {
  2771. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  2772. return 0.5 * this.getFilmHeight() / vExtentSlope;
  2773. },
  2774. getEffectiveFOV: function () {
  2775. return _Math.RAD2DEG * 2 * Math.atan(
  2776. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  2777. },
  2778. getFilmWidth: function () {
  2779. // film not completely covered in portrait format (aspect < 1)
  2780. return this.filmGauge * Math.min( this.aspect, 1 );
  2781. },
  2782. getFilmHeight: function () {
  2783. // film not completely covered in landscape format (aspect > 1)
  2784. return this.filmGauge / Math.max( this.aspect, 1 );
  2785. },
  2786. /**
  2787. * Sets an offset in a larger frustum. This is useful for multi-window or
  2788. * multi-monitor/multi-machine setups.
  2789. *
  2790. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  2791. * the monitors are in grid like this
  2792. *
  2793. * +---+---+---+
  2794. * | A | B | C |
  2795. * +---+---+---+
  2796. * | D | E | F |
  2797. * +---+---+---+
  2798. *
  2799. * then for each monitor you would call it like this
  2800. *
  2801. * var w = 1920;
  2802. * var h = 1080;
  2803. * var fullWidth = w * 3;
  2804. * var fullHeight = h * 2;
  2805. *
  2806. * --A--
  2807. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  2808. * --B--
  2809. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  2810. * --C--
  2811. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  2812. * --D--
  2813. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  2814. * --E--
  2815. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  2816. * --F--
  2817. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  2818. *
  2819. * Note there is no reason monitors have to be the same size or in a grid.
  2820. */
  2821. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  2822. this.aspect = fullWidth / fullHeight;
  2823. this.view = {
  2824. fullWidth: fullWidth,
  2825. fullHeight: fullHeight,
  2826. offsetX: x,
  2827. offsetY: y,
  2828. width: width,
  2829. height: height
  2830. };
  2831. this.updateProjectionMatrix();
  2832. },
  2833. clearViewOffset: function() {
  2834. this.view = null;
  2835. this.updateProjectionMatrix();
  2836. },
  2837. updateProjectionMatrix: function () {
  2838. var near = this.near,
  2839. top = near * Math.tan(
  2840. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  2841. height = 2 * top,
  2842. width = this.aspect * height,
  2843. left = - 0.5 * width,
  2844. view = this.view;
  2845. if ( view !== null ) {
  2846. var fullWidth = view.fullWidth,
  2847. fullHeight = view.fullHeight;
  2848. left += view.offsetX * width / fullWidth;
  2849. top -= view.offsetY * height / fullHeight;
  2850. width *= view.width / fullWidth;
  2851. height *= view.height / fullHeight;
  2852. }
  2853. var skew = this.filmOffset;
  2854. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  2855. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  2856. },
  2857. toJSON: function ( meta ) {
  2858. var data = Object3D.prototype.toJSON.call( this, meta );
  2859. data.object.fov = this.fov;
  2860. data.object.zoom = this.zoom;
  2861. data.object.near = this.near;
  2862. data.object.far = this.far;
  2863. data.object.focus = this.focus;
  2864. data.object.aspect = this.aspect;
  2865. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  2866. data.object.filmGauge = this.filmGauge;
  2867. data.object.filmOffset = this.filmOffset;
  2868. return data;
  2869. }
  2870. } );
  2871. /**
  2872. * @author supereggbert / http://www.paulbrunt.co.uk/
  2873. * @author philogb / http://blog.thejit.org/
  2874. * @author mikael emtinger / http://gomo.se/
  2875. * @author egraether / http://egraether.com/
  2876. * @author WestLangley / http://github.com/WestLangley
  2877. */
  2878. function Vector4( x, y, z, w ) {
  2879. this.x = x || 0;
  2880. this.y = y || 0;
  2881. this.z = z || 0;
  2882. this.w = ( w !== undefined ) ? w : 1;
  2883. }
  2884. Vector4.prototype = {
  2885. constructor: Vector4,
  2886. isVector4: true,
  2887. set: function ( x, y, z, w ) {
  2888. this.x = x;
  2889. this.y = y;
  2890. this.z = z;
  2891. this.w = w;
  2892. return this;
  2893. },
  2894. setScalar: function ( scalar ) {
  2895. this.x = scalar;
  2896. this.y = scalar;
  2897. this.z = scalar;
  2898. this.w = scalar;
  2899. return this;
  2900. },
  2901. setX: function ( x ) {
  2902. this.x = x;
  2903. return this;
  2904. },
  2905. setY: function ( y ) {
  2906. this.y = y;
  2907. return this;
  2908. },
  2909. setZ: function ( z ) {
  2910. this.z = z;
  2911. return this;
  2912. },
  2913. setW: function ( w ) {
  2914. this.w = w;
  2915. return this;
  2916. },
  2917. setComponent: function ( index, value ) {
  2918. switch ( index ) {
  2919. case 0: this.x = value; break;
  2920. case 1: this.y = value; break;
  2921. case 2: this.z = value; break;
  2922. case 3: this.w = value; break;
  2923. default: throw new Error( 'index is out of range: ' + index );
  2924. }
  2925. return this;
  2926. },
  2927. getComponent: function ( index ) {
  2928. switch ( index ) {
  2929. case 0: return this.x;
  2930. case 1: return this.y;
  2931. case 2: return this.z;
  2932. case 3: return this.w;
  2933. default: throw new Error( 'index is out of range: ' + index );
  2934. }
  2935. },
  2936. clone: function () {
  2937. return new this.constructor( this.x, this.y, this.z, this.w );
  2938. },
  2939. copy: function ( v ) {
  2940. this.x = v.x;
  2941. this.y = v.y;
  2942. this.z = v.z;
  2943. this.w = ( v.w !== undefined ) ? v.w : 1;
  2944. return this;
  2945. },
  2946. add: function ( v, w ) {
  2947. if ( w !== undefined ) {
  2948. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2949. return this.addVectors( v, w );
  2950. }
  2951. this.x += v.x;
  2952. this.y += v.y;
  2953. this.z += v.z;
  2954. this.w += v.w;
  2955. return this;
  2956. },
  2957. addScalar: function ( s ) {
  2958. this.x += s;
  2959. this.y += s;
  2960. this.z += s;
  2961. this.w += s;
  2962. return this;
  2963. },
  2964. addVectors: function ( a, b ) {
  2965. this.x = a.x + b.x;
  2966. this.y = a.y + b.y;
  2967. this.z = a.z + b.z;
  2968. this.w = a.w + b.w;
  2969. return this;
  2970. },
  2971. addScaledVector: function ( v, s ) {
  2972. this.x += v.x * s;
  2973. this.y += v.y * s;
  2974. this.z += v.z * s;
  2975. this.w += v.w * s;
  2976. return this;
  2977. },
  2978. sub: function ( v, w ) {
  2979. if ( w !== undefined ) {
  2980. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2981. return this.subVectors( v, w );
  2982. }
  2983. this.x -= v.x;
  2984. this.y -= v.y;
  2985. this.z -= v.z;
  2986. this.w -= v.w;
  2987. return this;
  2988. },
  2989. subScalar: function ( s ) {
  2990. this.x -= s;
  2991. this.y -= s;
  2992. this.z -= s;
  2993. this.w -= s;
  2994. return this;
  2995. },
  2996. subVectors: function ( a, b ) {
  2997. this.x = a.x - b.x;
  2998. this.y = a.y - b.y;
  2999. this.z = a.z - b.z;
  3000. this.w = a.w - b.w;
  3001. return this;
  3002. },
  3003. multiplyScalar: function ( scalar ) {
  3004. if ( isFinite( scalar ) ) {
  3005. this.x *= scalar;
  3006. this.y *= scalar;
  3007. this.z *= scalar;
  3008. this.w *= scalar;
  3009. } else {
  3010. this.x = 0;
  3011. this.y = 0;
  3012. this.z = 0;
  3013. this.w = 0;
  3014. }
  3015. return this;
  3016. },
  3017. applyMatrix4: function ( m ) {
  3018. var x = this.x, y = this.y, z = this.z, w = this.w;
  3019. var e = m.elements;
  3020. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  3021. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  3022. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  3023. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  3024. return this;
  3025. },
  3026. divideScalar: function ( scalar ) {
  3027. return this.multiplyScalar( 1 / scalar );
  3028. },
  3029. setAxisAngleFromQuaternion: function ( q ) {
  3030. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3031. // q is assumed to be normalized
  3032. this.w = 2 * Math.acos( q.w );
  3033. var s = Math.sqrt( 1 - q.w * q.w );
  3034. if ( s < 0.0001 ) {
  3035. this.x = 1;
  3036. this.y = 0;
  3037. this.z = 0;
  3038. } else {
  3039. this.x = q.x / s;
  3040. this.y = q.y / s;
  3041. this.z = q.z / s;
  3042. }
  3043. return this;
  3044. },
  3045. setAxisAngleFromRotationMatrix: function ( m ) {
  3046. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3047. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3048. var angle, x, y, z, // variables for result
  3049. epsilon = 0.01, // margin to allow for rounding errors
  3050. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  3051. te = m.elements,
  3052. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3053. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3054. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3055. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  3056. ( Math.abs( m13 - m31 ) < epsilon ) &&
  3057. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  3058. // singularity found
  3059. // first check for identity matrix which must have +1 for all terms
  3060. // in leading diagonal and zero in other terms
  3061. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  3062. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  3063. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  3064. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  3065. // this singularity is identity matrix so angle = 0
  3066. this.set( 1, 0, 0, 0 );
  3067. return this; // zero angle, arbitrary axis
  3068. }
  3069. // otherwise this singularity is angle = 180
  3070. angle = Math.PI;
  3071. var xx = ( m11 + 1 ) / 2;
  3072. var yy = ( m22 + 1 ) / 2;
  3073. var zz = ( m33 + 1 ) / 2;
  3074. var xy = ( m12 + m21 ) / 4;
  3075. var xz = ( m13 + m31 ) / 4;
  3076. var yz = ( m23 + m32 ) / 4;
  3077. if ( ( xx > yy ) && ( xx > zz ) ) {
  3078. // m11 is the largest diagonal term
  3079. if ( xx < epsilon ) {
  3080. x = 0;
  3081. y = 0.707106781;
  3082. z = 0.707106781;
  3083. } else {
  3084. x = Math.sqrt( xx );
  3085. y = xy / x;
  3086. z = xz / x;
  3087. }
  3088. } else if ( yy > zz ) {
  3089. // m22 is the largest diagonal term
  3090. if ( yy < epsilon ) {
  3091. x = 0.707106781;
  3092. y = 0;
  3093. z = 0.707106781;
  3094. } else {
  3095. y = Math.sqrt( yy );
  3096. x = xy / y;
  3097. z = yz / y;
  3098. }
  3099. } else {
  3100. // m33 is the largest diagonal term so base result on this
  3101. if ( zz < epsilon ) {
  3102. x = 0.707106781;
  3103. y = 0.707106781;
  3104. z = 0;
  3105. } else {
  3106. z = Math.sqrt( zz );
  3107. x = xz / z;
  3108. y = yz / z;
  3109. }
  3110. }
  3111. this.set( x, y, z, angle );
  3112. return this; // return 180 deg rotation
  3113. }
  3114. // as we have reached here there are no singularities so we can handle normally
  3115. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  3116. ( m13 - m31 ) * ( m13 - m31 ) +
  3117. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  3118. if ( Math.abs( s ) < 0.001 ) s = 1;
  3119. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3120. // caught by singularity test above, but I've left it in just in case
  3121. this.x = ( m32 - m23 ) / s;
  3122. this.y = ( m13 - m31 ) / s;
  3123. this.z = ( m21 - m12 ) / s;
  3124. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  3125. return this;
  3126. },
  3127. min: function ( v ) {
  3128. this.x = Math.min( this.x, v.x );
  3129. this.y = Math.min( this.y, v.y );
  3130. this.z = Math.min( this.z, v.z );
  3131. this.w = Math.min( this.w, v.w );
  3132. return this;
  3133. },
  3134. max: function ( v ) {
  3135. this.x = Math.max( this.x, v.x );
  3136. this.y = Math.max( this.y, v.y );
  3137. this.z = Math.max( this.z, v.z );
  3138. this.w = Math.max( this.w, v.w );
  3139. return this;
  3140. },
  3141. clamp: function ( min, max ) {
  3142. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  3143. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  3144. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  3145. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  3146. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  3147. return this;
  3148. },
  3149. clampScalar: function () {
  3150. var min, max;
  3151. return function clampScalar( minVal, maxVal ) {
  3152. if ( min === undefined ) {
  3153. min = new Vector4();
  3154. max = new Vector4();
  3155. }
  3156. min.set( minVal, minVal, minVal, minVal );
  3157. max.set( maxVal, maxVal, maxVal, maxVal );
  3158. return this.clamp( min, max );
  3159. };
  3160. }(),
  3161. floor: function () {
  3162. this.x = Math.floor( this.x );
  3163. this.y = Math.floor( this.y );
  3164. this.z = Math.floor( this.z );
  3165. this.w = Math.floor( this.w );
  3166. return this;
  3167. },
  3168. ceil: function () {
  3169. this.x = Math.ceil( this.x );
  3170. this.y = Math.ceil( this.y );
  3171. this.z = Math.ceil( this.z );
  3172. this.w = Math.ceil( this.w );
  3173. return this;
  3174. },
  3175. round: function () {
  3176. this.x = Math.round( this.x );
  3177. this.y = Math.round( this.y );
  3178. this.z = Math.round( this.z );
  3179. this.w = Math.round( this.w );
  3180. return this;
  3181. },
  3182. roundToZero: function () {
  3183. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  3184. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  3185. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  3186. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  3187. return this;
  3188. },
  3189. negate: function () {
  3190. this.x = - this.x;
  3191. this.y = - this.y;
  3192. this.z = - this.z;
  3193. this.w = - this.w;
  3194. return this;
  3195. },
  3196. dot: function ( v ) {
  3197. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3198. },
  3199. lengthSq: function () {
  3200. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3201. },
  3202. length: function () {
  3203. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  3204. },
  3205. lengthManhattan: function () {
  3206. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  3207. },
  3208. normalize: function () {
  3209. return this.divideScalar( this.length() );
  3210. },
  3211. setLength: function ( length ) {
  3212. return this.multiplyScalar( length / this.length() );
  3213. },
  3214. lerp: function ( v, alpha ) {
  3215. this.x += ( v.x - this.x ) * alpha;
  3216. this.y += ( v.y - this.y ) * alpha;
  3217. this.z += ( v.z - this.z ) * alpha;
  3218. this.w += ( v.w - this.w ) * alpha;
  3219. return this;
  3220. },
  3221. lerpVectors: function ( v1, v2, alpha ) {
  3222. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  3223. },
  3224. equals: function ( v ) {
  3225. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  3226. },
  3227. fromArray: function ( array, offset ) {
  3228. if ( offset === undefined ) offset = 0;
  3229. this.x = array[ offset ];
  3230. this.y = array[ offset + 1 ];
  3231. this.z = array[ offset + 2 ];
  3232. this.w = array[ offset + 3 ];
  3233. return this;
  3234. },
  3235. toArray: function ( array, offset ) {
  3236. if ( array === undefined ) array = [];
  3237. if ( offset === undefined ) offset = 0;
  3238. array[ offset ] = this.x;
  3239. array[ offset + 1 ] = this.y;
  3240. array[ offset + 2 ] = this.z;
  3241. array[ offset + 3 ] = this.w;
  3242. return array;
  3243. },
  3244. fromBufferAttribute: function ( attribute, index, offset ) {
  3245. if ( offset !== undefined ) {
  3246. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  3247. }
  3248. this.x = attribute.getX( index );
  3249. this.y = attribute.getY( index );
  3250. this.z = attribute.getZ( index );
  3251. this.w = attribute.getW( index );
  3252. return this;
  3253. }
  3254. };
  3255. /**
  3256. * @author mrdoob / http://mrdoob.com/
  3257. * @author philogb / http://blog.thejit.org/
  3258. * @author egraether / http://egraether.com/
  3259. * @author zz85 / http://www.lab4games.net/zz85/blog
  3260. */
  3261. function Vector2( x, y ) {
  3262. this.x = x || 0;
  3263. this.y = y || 0;
  3264. }
  3265. Vector2.prototype = {
  3266. constructor: Vector2,
  3267. isVector2: true,
  3268. get width() {
  3269. return this.x;
  3270. },
  3271. set width( value ) {
  3272. this.x = value;
  3273. },
  3274. get height() {
  3275. return this.y;
  3276. },
  3277. set height( value ) {
  3278. this.y = value;
  3279. },
  3280. //
  3281. set: function ( x, y ) {
  3282. this.x = x;
  3283. this.y = y;
  3284. return this;
  3285. },
  3286. setScalar: function ( scalar ) {
  3287. this.x = scalar;
  3288. this.y = scalar;
  3289. return this;
  3290. },
  3291. setX: function ( x ) {
  3292. this.x = x;
  3293. return this;
  3294. },
  3295. setY: function ( y ) {
  3296. this.y = y;
  3297. return this;
  3298. },
  3299. setComponent: function ( index, value ) {
  3300. switch ( index ) {
  3301. case 0: this.x = value; break;
  3302. case 1: this.y = value; break;
  3303. default: throw new Error( 'index is out of range: ' + index );
  3304. }
  3305. return this;
  3306. },
  3307. getComponent: function ( index ) {
  3308. switch ( index ) {
  3309. case 0: return this.x;
  3310. case 1: return this.y;
  3311. default: throw new Error( 'index is out of range: ' + index );
  3312. }
  3313. },
  3314. clone: function () {
  3315. return new this.constructor( this.x, this.y );
  3316. },
  3317. copy: function ( v ) {
  3318. this.x = v.x;
  3319. this.y = v.y;
  3320. return this;
  3321. },
  3322. add: function ( v, w ) {
  3323. if ( w !== undefined ) {
  3324. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  3325. return this.addVectors( v, w );
  3326. }
  3327. this.x += v.x;
  3328. this.y += v.y;
  3329. return this;
  3330. },
  3331. addScalar: function ( s ) {
  3332. this.x += s;
  3333. this.y += s;
  3334. return this;
  3335. },
  3336. addVectors: function ( a, b ) {
  3337. this.x = a.x + b.x;
  3338. this.y = a.y + b.y;
  3339. return this;
  3340. },
  3341. addScaledVector: function ( v, s ) {
  3342. this.x += v.x * s;
  3343. this.y += v.y * s;
  3344. return this;
  3345. },
  3346. sub: function ( v, w ) {
  3347. if ( w !== undefined ) {
  3348. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  3349. return this.subVectors( v, w );
  3350. }
  3351. this.x -= v.x;
  3352. this.y -= v.y;
  3353. return this;
  3354. },
  3355. subScalar: function ( s ) {
  3356. this.x -= s;
  3357. this.y -= s;
  3358. return this;
  3359. },
  3360. subVectors: function ( a, b ) {
  3361. this.x = a.x - b.x;
  3362. this.y = a.y - b.y;
  3363. return this;
  3364. },
  3365. multiply: function ( v ) {
  3366. this.x *= v.x;
  3367. this.y *= v.y;
  3368. return this;
  3369. },
  3370. multiplyScalar: function ( scalar ) {
  3371. if ( isFinite( scalar ) ) {
  3372. this.x *= scalar;
  3373. this.y *= scalar;
  3374. } else {
  3375. this.x = 0;
  3376. this.y = 0;
  3377. }
  3378. return this;
  3379. },
  3380. divide: function ( v ) {
  3381. this.x /= v.x;
  3382. this.y /= v.y;
  3383. return this;
  3384. },
  3385. divideScalar: function ( scalar ) {
  3386. return this.multiplyScalar( 1 / scalar );
  3387. },
  3388. min: function ( v ) {
  3389. this.x = Math.min( this.x, v.x );
  3390. this.y = Math.min( this.y, v.y );
  3391. return this;
  3392. },
  3393. max: function ( v ) {
  3394. this.x = Math.max( this.x, v.x );
  3395. this.y = Math.max( this.y, v.y );
  3396. return this;
  3397. },
  3398. clamp: function ( min, max ) {
  3399. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  3400. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  3401. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  3402. return this;
  3403. },
  3404. clampScalar: function () {
  3405. var min, max;
  3406. return function clampScalar( minVal, maxVal ) {
  3407. if ( min === undefined ) {
  3408. min = new Vector2();
  3409. max = new Vector2();
  3410. }
  3411. min.set( minVal, minVal );
  3412. max.set( maxVal, maxVal );
  3413. return this.clamp( min, max );
  3414. };
  3415. }(),
  3416. clampLength: function ( min, max ) {
  3417. var length = this.length();
  3418. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  3419. },
  3420. floor: function () {
  3421. this.x = Math.floor( this.x );
  3422. this.y = Math.floor( this.y );
  3423. return this;
  3424. },
  3425. ceil: function () {
  3426. this.x = Math.ceil( this.x );
  3427. this.y = Math.ceil( this.y );
  3428. return this;
  3429. },
  3430. round: function () {
  3431. this.x = Math.round( this.x );
  3432. this.y = Math.round( this.y );
  3433. return this;
  3434. },
  3435. roundToZero: function () {
  3436. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  3437. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  3438. return this;
  3439. },
  3440. negate: function () {
  3441. this.x = - this.x;
  3442. this.y = - this.y;
  3443. return this;
  3444. },
  3445. dot: function ( v ) {
  3446. return this.x * v.x + this.y * v.y;
  3447. },
  3448. lengthSq: function () {
  3449. return this.x * this.x + this.y * this.y;
  3450. },
  3451. length: function () {
  3452. return Math.sqrt( this.x * this.x + this.y * this.y );
  3453. },
  3454. lengthManhattan: function() {
  3455. return Math.abs( this.x ) + Math.abs( this.y );
  3456. },
  3457. normalize: function () {
  3458. return this.divideScalar( this.length() );
  3459. },
  3460. angle: function () {
  3461. // computes the angle in radians with respect to the positive x-axis
  3462. var angle = Math.atan2( this.y, this.x );
  3463. if ( angle < 0 ) angle += 2 * Math.PI;
  3464. return angle;
  3465. },
  3466. distanceTo: function ( v ) {
  3467. return Math.sqrt( this.distanceToSquared( v ) );
  3468. },
  3469. distanceToSquared: function ( v ) {
  3470. var dx = this.x - v.x, dy = this.y - v.y;
  3471. return dx * dx + dy * dy;
  3472. },
  3473. distanceToManhattan: function ( v ) {
  3474. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  3475. },
  3476. setLength: function ( length ) {
  3477. return this.multiplyScalar( length / this.length() );
  3478. },
  3479. lerp: function ( v, alpha ) {
  3480. this.x += ( v.x - this.x ) * alpha;
  3481. this.y += ( v.y - this.y ) * alpha;
  3482. return this;
  3483. },
  3484. lerpVectors: function ( v1, v2, alpha ) {
  3485. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  3486. },
  3487. equals: function ( v ) {
  3488. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  3489. },
  3490. fromArray: function ( array, offset ) {
  3491. if ( offset === undefined ) offset = 0;
  3492. this.x = array[ offset ];
  3493. this.y = array[ offset + 1 ];
  3494. return this;
  3495. },
  3496. toArray: function ( array, offset ) {
  3497. if ( array === undefined ) array = [];
  3498. if ( offset === undefined ) offset = 0;
  3499. array[ offset ] = this.x;
  3500. array[ offset + 1 ] = this.y;
  3501. return array;
  3502. },
  3503. fromBufferAttribute: function ( attribute, index, offset ) {
  3504. if ( offset !== undefined ) {
  3505. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  3506. }
  3507. this.x = attribute.getX( index );
  3508. this.y = attribute.getY( index );
  3509. return this;
  3510. },
  3511. rotateAround: function ( center, angle ) {
  3512. var c = Math.cos( angle ), s = Math.sin( angle );
  3513. var x = this.x - center.x;
  3514. var y = this.y - center.y;
  3515. this.x = x * c - y * s + center.x;
  3516. this.y = x * s + y * c + center.y;
  3517. return this;
  3518. }
  3519. };
  3520. /**
  3521. * @author mrdoob / http://mrdoob.com/
  3522. */
  3523. function Color( r, g, b ) {
  3524. if ( g === undefined && b === undefined ) {
  3525. // r is THREE.Color, hex or string
  3526. return this.set( r );
  3527. }
  3528. return this.setRGB( r, g, b );
  3529. }
  3530. Color.prototype = {
  3531. constructor: Color,
  3532. isColor: true,
  3533. r: 1, g: 1, b: 1,
  3534. set: function ( value ) {
  3535. if ( value && value.isColor ) {
  3536. this.copy( value );
  3537. } else if ( typeof value === 'number' ) {
  3538. this.setHex( value );
  3539. } else if ( typeof value === 'string' ) {
  3540. this.setStyle( value );
  3541. }
  3542. return this;
  3543. },
  3544. setScalar: function ( scalar ) {
  3545. this.r = scalar;
  3546. this.g = scalar;
  3547. this.b = scalar;
  3548. return this;
  3549. },
  3550. setHex: function ( hex ) {
  3551. hex = Math.floor( hex );
  3552. this.r = ( hex >> 16 & 255 ) / 255;
  3553. this.g = ( hex >> 8 & 255 ) / 255;
  3554. this.b = ( hex & 255 ) / 255;
  3555. return this;
  3556. },
  3557. setRGB: function ( r, g, b ) {
  3558. this.r = r;
  3559. this.g = g;
  3560. this.b = b;
  3561. return this;
  3562. },
  3563. setHSL: function () {
  3564. function hue2rgb( p, q, t ) {
  3565. if ( t < 0 ) t += 1;
  3566. if ( t > 1 ) t -= 1;
  3567. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  3568. if ( t < 1 / 2 ) return q;
  3569. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  3570. return p;
  3571. }
  3572. return function setHSL( h, s, l ) {
  3573. // h,s,l ranges are in 0.0 - 1.0
  3574. h = _Math.euclideanModulo( h, 1 );
  3575. s = _Math.clamp( s, 0, 1 );
  3576. l = _Math.clamp( l, 0, 1 );
  3577. if ( s === 0 ) {
  3578. this.r = this.g = this.b = l;
  3579. } else {
  3580. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  3581. var q = ( 2 * l ) - p;
  3582. this.r = hue2rgb( q, p, h + 1 / 3 );
  3583. this.g = hue2rgb( q, p, h );
  3584. this.b = hue2rgb( q, p, h - 1 / 3 );
  3585. }
  3586. return this;
  3587. };
  3588. }(),
  3589. setStyle: function ( style ) {
  3590. function handleAlpha( string ) {
  3591. if ( string === undefined ) return;
  3592. if ( parseFloat( string ) < 1 ) {
  3593. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  3594. }
  3595. }
  3596. var m;
  3597. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  3598. // rgb / hsl
  3599. var color;
  3600. var name = m[ 1 ];
  3601. var components = m[ 2 ];
  3602. switch ( name ) {
  3603. case 'rgb':
  3604. case 'rgba':
  3605. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3606. // rgb(255,0,0) rgba(255,0,0,0.5)
  3607. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  3608. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  3609. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  3610. handleAlpha( color[ 5 ] );
  3611. return this;
  3612. }
  3613. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3614. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  3615. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  3616. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  3617. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  3618. handleAlpha( color[ 5 ] );
  3619. return this;
  3620. }
  3621. break;
  3622. case 'hsl':
  3623. case 'hsla':
  3624. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  3625. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  3626. var h = parseFloat( color[ 1 ] ) / 360;
  3627. var s = parseInt( color[ 2 ], 10 ) / 100;
  3628. var l = parseInt( color[ 3 ], 10 ) / 100;
  3629. handleAlpha( color[ 5 ] );
  3630. return this.setHSL( h, s, l );
  3631. }
  3632. break;
  3633. }
  3634. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  3635. // hex color
  3636. var hex = m[ 1 ];
  3637. var size = hex.length;
  3638. if ( size === 3 ) {
  3639. // #ff0
  3640. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  3641. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  3642. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  3643. return this;
  3644. } else if ( size === 6 ) {
  3645. // #ff0000
  3646. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  3647. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  3648. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  3649. return this;
  3650. }
  3651. }
  3652. if ( style && style.length > 0 ) {
  3653. // color keywords
  3654. var hex = ColorKeywords[ style ];
  3655. if ( hex !== undefined ) {
  3656. // red
  3657. this.setHex( hex );
  3658. } else {
  3659. // unknown color
  3660. console.warn( 'THREE.Color: Unknown color ' + style );
  3661. }
  3662. }
  3663. return this;
  3664. },
  3665. clone: function () {
  3666. return new this.constructor( this.r, this.g, this.b );
  3667. },
  3668. copy: function ( color ) {
  3669. this.r = color.r;
  3670. this.g = color.g;
  3671. this.b = color.b;
  3672. return this;
  3673. },
  3674. copyGammaToLinear: function ( color, gammaFactor ) {
  3675. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3676. this.r = Math.pow( color.r, gammaFactor );
  3677. this.g = Math.pow( color.g, gammaFactor );
  3678. this.b = Math.pow( color.b, gammaFactor );
  3679. return this;
  3680. },
  3681. copyLinearToGamma: function ( color, gammaFactor ) {
  3682. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  3683. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  3684. this.r = Math.pow( color.r, safeInverse );
  3685. this.g = Math.pow( color.g, safeInverse );
  3686. this.b = Math.pow( color.b, safeInverse );
  3687. return this;
  3688. },
  3689. convertGammaToLinear: function () {
  3690. var r = this.r, g = this.g, b = this.b;
  3691. this.r = r * r;
  3692. this.g = g * g;
  3693. this.b = b * b;
  3694. return this;
  3695. },
  3696. convertLinearToGamma: function () {
  3697. this.r = Math.sqrt( this.r );
  3698. this.g = Math.sqrt( this.g );
  3699. this.b = Math.sqrt( this.b );
  3700. return this;
  3701. },
  3702. getHex: function () {
  3703. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  3704. },
  3705. getHexString: function () {
  3706. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  3707. },
  3708. getHSL: function ( optionalTarget ) {
  3709. // h,s,l ranges are in 0.0 - 1.0
  3710. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  3711. var r = this.r, g = this.g, b = this.b;
  3712. var max = Math.max( r, g, b );
  3713. var min = Math.min( r, g, b );
  3714. var hue, saturation;
  3715. var lightness = ( min + max ) / 2.0;
  3716. if ( min === max ) {
  3717. hue = 0;
  3718. saturation = 0;
  3719. } else {
  3720. var delta = max - min;
  3721. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  3722. switch ( max ) {
  3723. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  3724. case g: hue = ( b - r ) / delta + 2; break;
  3725. case b: hue = ( r - g ) / delta + 4; break;
  3726. }
  3727. hue /= 6;
  3728. }
  3729. hsl.h = hue;
  3730. hsl.s = saturation;
  3731. hsl.l = lightness;
  3732. return hsl;
  3733. },
  3734. getStyle: function () {
  3735. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  3736. },
  3737. offsetHSL: function ( h, s, l ) {
  3738. var hsl = this.getHSL();
  3739. hsl.h += h; hsl.s += s; hsl.l += l;
  3740. this.setHSL( hsl.h, hsl.s, hsl.l );
  3741. return this;
  3742. },
  3743. add: function ( color ) {
  3744. this.r += color.r;
  3745. this.g += color.g;
  3746. this.b += color.b;
  3747. return this;
  3748. },
  3749. addColors: function ( color1, color2 ) {
  3750. this.r = color1.r + color2.r;
  3751. this.g = color1.g + color2.g;
  3752. this.b = color1.b + color2.b;
  3753. return this;
  3754. },
  3755. addScalar: function ( s ) {
  3756. this.r += s;
  3757. this.g += s;
  3758. this.b += s;
  3759. return this;
  3760. },
  3761. sub: function( color ) {
  3762. this.r = Math.max( 0, this.r - color.r );
  3763. this.g = Math.max( 0, this.g - color.g );
  3764. this.b = Math.max( 0, this.b - color.b );
  3765. return this;
  3766. },
  3767. multiply: function ( color ) {
  3768. this.r *= color.r;
  3769. this.g *= color.g;
  3770. this.b *= color.b;
  3771. return this;
  3772. },
  3773. multiplyScalar: function ( s ) {
  3774. this.r *= s;
  3775. this.g *= s;
  3776. this.b *= s;
  3777. return this;
  3778. },
  3779. lerp: function ( color, alpha ) {
  3780. this.r += ( color.r - this.r ) * alpha;
  3781. this.g += ( color.g - this.g ) * alpha;
  3782. this.b += ( color.b - this.b ) * alpha;
  3783. return this;
  3784. },
  3785. equals: function ( c ) {
  3786. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  3787. },
  3788. fromArray: function ( array, offset ) {
  3789. if ( offset === undefined ) offset = 0;
  3790. this.r = array[ offset ];
  3791. this.g = array[ offset + 1 ];
  3792. this.b = array[ offset + 2 ];
  3793. return this;
  3794. },
  3795. toArray: function ( array, offset ) {
  3796. if ( array === undefined ) array = [];
  3797. if ( offset === undefined ) offset = 0;
  3798. array[ offset ] = this.r;
  3799. array[ offset + 1 ] = this.g;
  3800. array[ offset + 2 ] = this.b;
  3801. return array;
  3802. },
  3803. toJSON: function () {
  3804. return this.getHex();
  3805. }
  3806. };
  3807. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  3808. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  3809. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  3810. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  3811. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  3812. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  3813. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  3814. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  3815. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  3816. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  3817. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  3818. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  3819. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  3820. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  3821. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  3822. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  3823. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  3824. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  3825. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  3826. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  3827. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  3828. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  3829. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  3830. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  3831. /**
  3832. * @author mrdoob / http://mrdoob.com/
  3833. */
  3834. function BufferAttribute( array, itemSize, normalized ) {
  3835. if ( Array.isArray( array ) ) {
  3836. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  3837. }
  3838. this.uuid = _Math.generateUUID();
  3839. this.array = array;
  3840. this.itemSize = itemSize;
  3841. this.count = array !== undefined ? array.length / itemSize : 0;
  3842. this.normalized = normalized === true;
  3843. this.dynamic = false;
  3844. this.updateRange = { offset: 0, count: - 1 };
  3845. this.onUploadCallback = function () {};
  3846. this.version = 0;
  3847. }
  3848. BufferAttribute.prototype = {
  3849. constructor: BufferAttribute,
  3850. isBufferAttribute: true,
  3851. set needsUpdate( value ) {
  3852. if ( value === true ) this.version ++;
  3853. },
  3854. setArray: function ( array ) {
  3855. if ( Array.isArray( array ) ) {
  3856. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  3857. }
  3858. this.count = array !== undefined ? array.length / this.itemSize : 0;
  3859. this.array = array;
  3860. },
  3861. setDynamic: function ( value ) {
  3862. this.dynamic = value;
  3863. return this;
  3864. },
  3865. copy: function ( source ) {
  3866. this.array = new source.array.constructor( source.array );
  3867. this.itemSize = source.itemSize;
  3868. this.count = source.count;
  3869. this.normalized = source.normalized;
  3870. this.dynamic = source.dynamic;
  3871. return this;
  3872. },
  3873. copyAt: function ( index1, attribute, index2 ) {
  3874. index1 *= this.itemSize;
  3875. index2 *= attribute.itemSize;
  3876. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  3877. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  3878. }
  3879. return this;
  3880. },
  3881. copyArray: function ( array ) {
  3882. this.array.set( array );
  3883. return this;
  3884. },
  3885. copyColorsArray: function ( colors ) {
  3886. var array = this.array, offset = 0;
  3887. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  3888. var color = colors[ i ];
  3889. if ( color === undefined ) {
  3890. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  3891. color = new Color();
  3892. }
  3893. array[ offset ++ ] = color.r;
  3894. array[ offset ++ ] = color.g;
  3895. array[ offset ++ ] = color.b;
  3896. }
  3897. return this;
  3898. },
  3899. copyIndicesArray: function ( indices ) {
  3900. var array = this.array, offset = 0;
  3901. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  3902. var index = indices[ i ];
  3903. array[ offset ++ ] = index.a;
  3904. array[ offset ++ ] = index.b;
  3905. array[ offset ++ ] = index.c;
  3906. }
  3907. return this;
  3908. },
  3909. copyVector2sArray: function ( vectors ) {
  3910. var array = this.array, offset = 0;
  3911. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  3912. var vector = vectors[ i ];
  3913. if ( vector === undefined ) {
  3914. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  3915. vector = new Vector2();
  3916. }
  3917. array[ offset ++ ] = vector.x;
  3918. array[ offset ++ ] = vector.y;
  3919. }
  3920. return this;
  3921. },
  3922. copyVector3sArray: function ( vectors ) {
  3923. var array = this.array, offset = 0;
  3924. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  3925. var vector = vectors[ i ];
  3926. if ( vector === undefined ) {
  3927. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  3928. vector = new Vector3();
  3929. }
  3930. array[ offset ++ ] = vector.x;
  3931. array[ offset ++ ] = vector.y;
  3932. array[ offset ++ ] = vector.z;
  3933. }
  3934. return this;
  3935. },
  3936. copyVector4sArray: function ( vectors ) {
  3937. var array = this.array, offset = 0;
  3938. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  3939. var vector = vectors[ i ];
  3940. if ( vector === undefined ) {
  3941. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  3942. vector = new Vector4();
  3943. }
  3944. array[ offset ++ ] = vector.x;
  3945. array[ offset ++ ] = vector.y;
  3946. array[ offset ++ ] = vector.z;
  3947. array[ offset ++ ] = vector.w;
  3948. }
  3949. return this;
  3950. },
  3951. set: function ( value, offset ) {
  3952. if ( offset === undefined ) offset = 0;
  3953. this.array.set( value, offset );
  3954. return this;
  3955. },
  3956. getX: function ( index ) {
  3957. return this.array[ index * this.itemSize ];
  3958. },
  3959. setX: function ( index, x ) {
  3960. this.array[ index * this.itemSize ] = x;
  3961. return this;
  3962. },
  3963. getY: function ( index ) {
  3964. return this.array[ index * this.itemSize + 1 ];
  3965. },
  3966. setY: function ( index, y ) {
  3967. this.array[ index * this.itemSize + 1 ] = y;
  3968. return this;
  3969. },
  3970. getZ: function ( index ) {
  3971. return this.array[ index * this.itemSize + 2 ];
  3972. },
  3973. setZ: function ( index, z ) {
  3974. this.array[ index * this.itemSize + 2 ] = z;
  3975. return this;
  3976. },
  3977. getW: function ( index ) {
  3978. return this.array[ index * this.itemSize + 3 ];
  3979. },
  3980. setW: function ( index, w ) {
  3981. this.array[ index * this.itemSize + 3 ] = w;
  3982. return this;
  3983. },
  3984. setXY: function ( index, x, y ) {
  3985. index *= this.itemSize;
  3986. this.array[ index + 0 ] = x;
  3987. this.array[ index + 1 ] = y;
  3988. return this;
  3989. },
  3990. setXYZ: function ( index, x, y, z ) {
  3991. index *= this.itemSize;
  3992. this.array[ index + 0 ] = x;
  3993. this.array[ index + 1 ] = y;
  3994. this.array[ index + 2 ] = z;
  3995. return this;
  3996. },
  3997. setXYZW: function ( index, x, y, z, w ) {
  3998. index *= this.itemSize;
  3999. this.array[ index + 0 ] = x;
  4000. this.array[ index + 1 ] = y;
  4001. this.array[ index + 2 ] = z;
  4002. this.array[ index + 3 ] = w;
  4003. return this;
  4004. },
  4005. onUpload: function ( callback ) {
  4006. this.onUploadCallback = callback;
  4007. return this;
  4008. },
  4009. clone: function () {
  4010. return new this.constructor( this.array, this.itemSize ).copy( this );
  4011. }
  4012. };
  4013. //
  4014. function Int8BufferAttribute( array, itemSize ) {
  4015. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  4016. }
  4017. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  4018. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  4019. function Uint8BufferAttribute( array, itemSize ) {
  4020. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  4021. }
  4022. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  4023. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  4024. function Uint8ClampedBufferAttribute( array, itemSize ) {
  4025. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  4026. }
  4027. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  4028. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  4029. function Int16BufferAttribute( array, itemSize ) {
  4030. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  4031. }
  4032. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  4033. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  4034. function Uint16BufferAttribute( array, itemSize ) {
  4035. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  4036. }
  4037. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  4038. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  4039. function Int32BufferAttribute( array, itemSize ) {
  4040. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  4041. }
  4042. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  4043. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  4044. function Uint32BufferAttribute( array, itemSize ) {
  4045. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  4046. }
  4047. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  4048. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  4049. function Float32BufferAttribute( array, itemSize ) {
  4050. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  4051. }
  4052. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  4053. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  4054. function Float64BufferAttribute( array, itemSize ) {
  4055. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  4056. }
  4057. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  4058. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  4059. /**
  4060. * @author bhouston / http://clara.io
  4061. * @author mrdoob / http://mrdoob.com/
  4062. */
  4063. function Sphere( center, radius ) {
  4064. this.center = ( center !== undefined ) ? center : new Vector3();
  4065. this.radius = ( radius !== undefined ) ? radius : 0;
  4066. }
  4067. Sphere.prototype = {
  4068. constructor: Sphere,
  4069. set: function ( center, radius ) {
  4070. this.center.copy( center );
  4071. this.radius = radius;
  4072. return this;
  4073. },
  4074. setFromPoints: function () {
  4075. var box;
  4076. return function setFromPoints( points, optionalCenter ) {
  4077. if ( box === undefined ) box = new Box3(); // see #10547
  4078. var center = this.center;
  4079. if ( optionalCenter !== undefined ) {
  4080. center.copy( optionalCenter );
  4081. } else {
  4082. box.setFromPoints( points ).getCenter( center );
  4083. }
  4084. var maxRadiusSq = 0;
  4085. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4086. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  4087. }
  4088. this.radius = Math.sqrt( maxRadiusSq );
  4089. return this;
  4090. };
  4091. }(),
  4092. clone: function () {
  4093. return new this.constructor().copy( this );
  4094. },
  4095. copy: function ( sphere ) {
  4096. this.center.copy( sphere.center );
  4097. this.radius = sphere.radius;
  4098. return this;
  4099. },
  4100. empty: function () {
  4101. return ( this.radius <= 0 );
  4102. },
  4103. containsPoint: function ( point ) {
  4104. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  4105. },
  4106. distanceToPoint: function ( point ) {
  4107. return ( point.distanceTo( this.center ) - this.radius );
  4108. },
  4109. intersectsSphere: function ( sphere ) {
  4110. var radiusSum = this.radius + sphere.radius;
  4111. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  4112. },
  4113. intersectsBox: function ( box ) {
  4114. return box.intersectsSphere( this );
  4115. },
  4116. intersectsPlane: function ( plane ) {
  4117. // We use the following equation to compute the signed distance from
  4118. // the center of the sphere to the plane.
  4119. //
  4120. // distance = q * n - d
  4121. //
  4122. // If this distance is greater than the radius of the sphere,
  4123. // then there is no intersection.
  4124. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  4125. },
  4126. clampPoint: function ( point, optionalTarget ) {
  4127. var deltaLengthSq = this.center.distanceToSquared( point );
  4128. var result = optionalTarget || new Vector3();
  4129. result.copy( point );
  4130. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  4131. result.sub( this.center ).normalize();
  4132. result.multiplyScalar( this.radius ).add( this.center );
  4133. }
  4134. return result;
  4135. },
  4136. getBoundingBox: function ( optionalTarget ) {
  4137. var box = optionalTarget || new Box3();
  4138. box.set( this.center, this.center );
  4139. box.expandByScalar( this.radius );
  4140. return box;
  4141. },
  4142. applyMatrix4: function ( matrix ) {
  4143. this.center.applyMatrix4( matrix );
  4144. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  4145. return this;
  4146. },
  4147. translate: function ( offset ) {
  4148. this.center.add( offset );
  4149. return this;
  4150. },
  4151. equals: function ( sphere ) {
  4152. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  4153. }
  4154. };
  4155. /**
  4156. * @author bhouston / http://clara.io
  4157. * @author WestLangley / http://github.com/WestLangley
  4158. */
  4159. function Box3( min, max ) {
  4160. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  4161. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  4162. }
  4163. Box3.prototype = {
  4164. constructor: Box3,
  4165. isBox3: true,
  4166. set: function ( min, max ) {
  4167. this.min.copy( min );
  4168. this.max.copy( max );
  4169. return this;
  4170. },
  4171. setFromArray: function ( array ) {
  4172. var minX = + Infinity;
  4173. var minY = + Infinity;
  4174. var minZ = + Infinity;
  4175. var maxX = - Infinity;
  4176. var maxY = - Infinity;
  4177. var maxZ = - Infinity;
  4178. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  4179. var x = array[ i ];
  4180. var y = array[ i + 1 ];
  4181. var z = array[ i + 2 ];
  4182. if ( x < minX ) minX = x;
  4183. if ( y < minY ) minY = y;
  4184. if ( z < minZ ) minZ = z;
  4185. if ( x > maxX ) maxX = x;
  4186. if ( y > maxY ) maxY = y;
  4187. if ( z > maxZ ) maxZ = z;
  4188. }
  4189. this.min.set( minX, minY, minZ );
  4190. this.max.set( maxX, maxY, maxZ );
  4191. return this;
  4192. },
  4193. setFromBufferAttribute: function ( attribute ) {
  4194. var minX = + Infinity;
  4195. var minY = + Infinity;
  4196. var minZ = + Infinity;
  4197. var maxX = - Infinity;
  4198. var maxY = - Infinity;
  4199. var maxZ = - Infinity;
  4200. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  4201. var x = attribute.getX( i );
  4202. var y = attribute.getY( i );
  4203. var z = attribute.getZ( i );
  4204. if ( x < minX ) minX = x;
  4205. if ( y < minY ) minY = y;
  4206. if ( z < minZ ) minZ = z;
  4207. if ( x > maxX ) maxX = x;
  4208. if ( y > maxY ) maxY = y;
  4209. if ( z > maxZ ) maxZ = z;
  4210. }
  4211. this.min.set( minX, minY, minZ );
  4212. this.max.set( maxX, maxY, maxZ );
  4213. return this;
  4214. },
  4215. setFromPoints: function ( points ) {
  4216. this.makeEmpty();
  4217. for ( var i = 0, il = points.length; i < il; i ++ ) {
  4218. this.expandByPoint( points[ i ] );
  4219. }
  4220. return this;
  4221. },
  4222. setFromCenterAndSize: function () {
  4223. var v1 = new Vector3();
  4224. return function setFromCenterAndSize( center, size ) {
  4225. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  4226. this.min.copy( center ).sub( halfSize );
  4227. this.max.copy( center ).add( halfSize );
  4228. return this;
  4229. };
  4230. }(),
  4231. setFromObject: function ( object ) {
  4232. this.makeEmpty();
  4233. return this.expandByObject( object );
  4234. },
  4235. clone: function () {
  4236. return new this.constructor().copy( this );
  4237. },
  4238. copy: function ( box ) {
  4239. this.min.copy( box.min );
  4240. this.max.copy( box.max );
  4241. return this;
  4242. },
  4243. makeEmpty: function () {
  4244. this.min.x = this.min.y = this.min.z = + Infinity;
  4245. this.max.x = this.max.y = this.max.z = - Infinity;
  4246. return this;
  4247. },
  4248. isEmpty: function () {
  4249. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4250. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  4251. },
  4252. getCenter: function ( optionalTarget ) {
  4253. var result = optionalTarget || new Vector3();
  4254. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  4255. },
  4256. getSize: function ( optionalTarget ) {
  4257. var result = optionalTarget || new Vector3();
  4258. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  4259. },
  4260. expandByPoint: function ( point ) {
  4261. this.min.min( point );
  4262. this.max.max( point );
  4263. return this;
  4264. },
  4265. expandByVector: function ( vector ) {
  4266. this.min.sub( vector );
  4267. this.max.add( vector );
  4268. return this;
  4269. },
  4270. expandByScalar: function ( scalar ) {
  4271. this.min.addScalar( - scalar );
  4272. this.max.addScalar( scalar );
  4273. return this;
  4274. },
  4275. expandByObject: function () {
  4276. // Computes the world-axis-aligned bounding box of an object (including its children),
  4277. // accounting for both the object's, and children's, world transforms
  4278. var v1 = new Vector3();
  4279. return function expandByObject( object ) {
  4280. var scope = this;
  4281. object.updateMatrixWorld( true );
  4282. object.traverse( function ( node ) {
  4283. var i, l;
  4284. var geometry = node.geometry;
  4285. if ( geometry !== undefined ) {
  4286. if ( geometry.isGeometry ) {
  4287. var vertices = geometry.vertices;
  4288. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  4289. v1.copy( vertices[ i ] );
  4290. v1.applyMatrix4( node.matrixWorld );
  4291. scope.expandByPoint( v1 );
  4292. }
  4293. } else if ( geometry.isBufferGeometry ) {
  4294. var attribute = geometry.attributes.position;
  4295. if ( attribute !== undefined ) {
  4296. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  4297. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  4298. scope.expandByPoint( v1 );
  4299. }
  4300. }
  4301. }
  4302. }
  4303. } );
  4304. return this;
  4305. };
  4306. }(),
  4307. containsPoint: function ( point ) {
  4308. return point.x < this.min.x || point.x > this.max.x ||
  4309. point.y < this.min.y || point.y > this.max.y ||
  4310. point.z < this.min.z || point.z > this.max.z ? false : true;
  4311. },
  4312. containsBox: function ( box ) {
  4313. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  4314. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  4315. this.min.z <= box.min.z && box.max.z <= this.max.z;
  4316. },
  4317. getParameter: function ( point, optionalTarget ) {
  4318. // This can potentially have a divide by zero if the box
  4319. // has a size dimension of 0.
  4320. var result = optionalTarget || new Vector3();
  4321. return result.set(
  4322. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  4323. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  4324. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  4325. );
  4326. },
  4327. intersectsBox: function ( box ) {
  4328. // using 6 splitting planes to rule out intersections.
  4329. return box.max.x < this.min.x || box.min.x > this.max.x ||
  4330. box.max.y < this.min.y || box.min.y > this.max.y ||
  4331. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  4332. },
  4333. intersectsSphere: ( function () {
  4334. var closestPoint;
  4335. return function intersectsSphere( sphere ) {
  4336. if ( closestPoint === undefined ) closestPoint = new Vector3();
  4337. // Find the point on the AABB closest to the sphere center.
  4338. this.clampPoint( sphere.center, closestPoint );
  4339. // If that point is inside the sphere, the AABB and sphere intersect.
  4340. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  4341. };
  4342. } )(),
  4343. intersectsPlane: function ( plane ) {
  4344. // We compute the minimum and maximum dot product values. If those values
  4345. // are on the same side (back or front) of the plane, then there is no intersection.
  4346. var min, max;
  4347. if ( plane.normal.x > 0 ) {
  4348. min = plane.normal.x * this.min.x;
  4349. max = plane.normal.x * this.max.x;
  4350. } else {
  4351. min = plane.normal.x * this.max.x;
  4352. max = plane.normal.x * this.min.x;
  4353. }
  4354. if ( plane.normal.y > 0 ) {
  4355. min += plane.normal.y * this.min.y;
  4356. max += plane.normal.y * this.max.y;
  4357. } else {
  4358. min += plane.normal.y * this.max.y;
  4359. max += plane.normal.y * this.min.y;
  4360. }
  4361. if ( plane.normal.z > 0 ) {
  4362. min += plane.normal.z * this.min.z;
  4363. max += plane.normal.z * this.max.z;
  4364. } else {
  4365. min += plane.normal.z * this.max.z;
  4366. max += plane.normal.z * this.min.z;
  4367. }
  4368. return ( min <= plane.constant && max >= plane.constant );
  4369. },
  4370. clampPoint: function ( point, optionalTarget ) {
  4371. var result = optionalTarget || new Vector3();
  4372. return result.copy( point ).clamp( this.min, this.max );
  4373. },
  4374. distanceToPoint: function () {
  4375. var v1 = new Vector3();
  4376. return function distanceToPoint( point ) {
  4377. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  4378. return clampedPoint.sub( point ).length();
  4379. };
  4380. }(),
  4381. getBoundingSphere: function () {
  4382. var v1 = new Vector3();
  4383. return function getBoundingSphere( optionalTarget ) {
  4384. var result = optionalTarget || new Sphere();
  4385. this.getCenter( result.center );
  4386. result.radius = this.getSize( v1 ).length() * 0.5;
  4387. return result;
  4388. };
  4389. }(),
  4390. intersect: function ( box ) {
  4391. this.min.max( box.min );
  4392. this.max.min( box.max );
  4393. // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  4394. if( this.isEmpty() ) this.makeEmpty();
  4395. return this;
  4396. },
  4397. union: function ( box ) {
  4398. this.min.min( box.min );
  4399. this.max.max( box.max );
  4400. return this;
  4401. },
  4402. applyMatrix4: function () {
  4403. var points = [
  4404. new Vector3(),
  4405. new Vector3(),
  4406. new Vector3(),
  4407. new Vector3(),
  4408. new Vector3(),
  4409. new Vector3(),
  4410. new Vector3(),
  4411. new Vector3()
  4412. ];
  4413. return function applyMatrix4( matrix ) {
  4414. // transform of empty box is an empty box.
  4415. if( this.isEmpty() ) return this;
  4416. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  4417. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  4418. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  4419. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  4420. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  4421. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  4422. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  4423. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  4424. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  4425. this.setFromPoints( points );
  4426. return this;
  4427. };
  4428. }(),
  4429. translate: function ( offset ) {
  4430. this.min.add( offset );
  4431. this.max.add( offset );
  4432. return this;
  4433. },
  4434. equals: function ( box ) {
  4435. return box.min.equals( this.min ) && box.max.equals( this.max );
  4436. }
  4437. };
  4438. /**
  4439. * @author mrdoob / http://mrdoob.com/
  4440. */
  4441. function DirectGeometry() {
  4442. this.indices = [];
  4443. this.vertices = [];
  4444. this.normals = [];
  4445. this.colors = [];
  4446. this.uvs = [];
  4447. this.uvs2 = [];
  4448. this.groups = [];
  4449. this.morphTargets = {};
  4450. this.skinWeights = [];
  4451. this.skinIndices = [];
  4452. // this.lineDistances = [];
  4453. this.boundingBox = null;
  4454. this.boundingSphere = null;
  4455. // update flags
  4456. this.verticesNeedUpdate = false;
  4457. this.normalsNeedUpdate = false;
  4458. this.colorsNeedUpdate = false;
  4459. this.uvsNeedUpdate = false;
  4460. this.groupsNeedUpdate = false;
  4461. }
  4462. Object.assign( DirectGeometry.prototype, {
  4463. computeGroups: function ( geometry ) {
  4464. var group;
  4465. var groups = [];
  4466. var materialIndex = undefined;
  4467. var faces = geometry.faces;
  4468. for ( var i = 0; i < faces.length; i ++ ) {
  4469. var face = faces[ i ];
  4470. // materials
  4471. if ( face.materialIndex !== materialIndex ) {
  4472. materialIndex = face.materialIndex;
  4473. if ( group !== undefined ) {
  4474. group.count = ( i * 3 ) - group.start;
  4475. groups.push( group );
  4476. }
  4477. group = {
  4478. start: i * 3,
  4479. materialIndex: materialIndex
  4480. };
  4481. }
  4482. }
  4483. if ( group !== undefined ) {
  4484. group.count = ( i * 3 ) - group.start;
  4485. groups.push( group );
  4486. }
  4487. this.groups = groups;
  4488. },
  4489. fromGeometry: function ( geometry ) {
  4490. var faces = geometry.faces;
  4491. var vertices = geometry.vertices;
  4492. var faceVertexUvs = geometry.faceVertexUvs;
  4493. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  4494. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  4495. // morphs
  4496. var morphTargets = geometry.morphTargets;
  4497. var morphTargetsLength = morphTargets.length;
  4498. var morphTargetsPosition;
  4499. if ( morphTargetsLength > 0 ) {
  4500. morphTargetsPosition = [];
  4501. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  4502. morphTargetsPosition[ i ] = [];
  4503. }
  4504. this.morphTargets.position = morphTargetsPosition;
  4505. }
  4506. var morphNormals = geometry.morphNormals;
  4507. var morphNormalsLength = morphNormals.length;
  4508. var morphTargetsNormal;
  4509. if ( morphNormalsLength > 0 ) {
  4510. morphTargetsNormal = [];
  4511. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  4512. morphTargetsNormal[ i ] = [];
  4513. }
  4514. this.morphTargets.normal = morphTargetsNormal;
  4515. }
  4516. // skins
  4517. var skinIndices = geometry.skinIndices;
  4518. var skinWeights = geometry.skinWeights;
  4519. var hasSkinIndices = skinIndices.length === vertices.length;
  4520. var hasSkinWeights = skinWeights.length === vertices.length;
  4521. //
  4522. for ( var i = 0; i < faces.length; i ++ ) {
  4523. var face = faces[ i ];
  4524. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  4525. var vertexNormals = face.vertexNormals;
  4526. if ( vertexNormals.length === 3 ) {
  4527. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  4528. } else {
  4529. var normal = face.normal;
  4530. this.normals.push( normal, normal, normal );
  4531. }
  4532. var vertexColors = face.vertexColors;
  4533. if ( vertexColors.length === 3 ) {
  4534. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  4535. } else {
  4536. var color = face.color;
  4537. this.colors.push( color, color, color );
  4538. }
  4539. if ( hasFaceVertexUv === true ) {
  4540. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  4541. if ( vertexUvs !== undefined ) {
  4542. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  4543. } else {
  4544. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  4545. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  4546. }
  4547. }
  4548. if ( hasFaceVertexUv2 === true ) {
  4549. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  4550. if ( vertexUvs !== undefined ) {
  4551. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  4552. } else {
  4553. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  4554. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  4555. }
  4556. }
  4557. // morphs
  4558. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  4559. var morphTarget = morphTargets[ j ].vertices;
  4560. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  4561. }
  4562. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  4563. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  4564. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  4565. }
  4566. // skins
  4567. if ( hasSkinIndices ) {
  4568. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  4569. }
  4570. if ( hasSkinWeights ) {
  4571. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  4572. }
  4573. }
  4574. this.computeGroups( geometry );
  4575. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  4576. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  4577. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  4578. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  4579. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  4580. return this;
  4581. }
  4582. } );
  4583. // http://stackoverflow.com/questions/1669190/javascript-min-max-array-values/13440842#13440842
  4584. function arrayMax( array ) {
  4585. var length = array.length, max = - Infinity;
  4586. while ( length -- ) {
  4587. if ( array[ length ] > max ) {
  4588. max = array[ length ];
  4589. }
  4590. }
  4591. return max;
  4592. }
  4593. /**
  4594. * @author mrdoob / http://mrdoob.com/
  4595. * @author alteredq / http://alteredqualia.com/
  4596. */
  4597. function Face3( a, b, c, normal, color, materialIndex ) {
  4598. this.a = a;
  4599. this.b = b;
  4600. this.c = c;
  4601. this.normal = (normal && normal.isVector3) ? normal : new Vector3();
  4602. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  4603. this.color = (color && color.isColor) ? color : new Color();
  4604. this.vertexColors = Array.isArray( color ) ? color : [];
  4605. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4606. }
  4607. Face3.prototype = {
  4608. constructor: Face3,
  4609. clone: function () {
  4610. return new this.constructor().copy( this );
  4611. },
  4612. copy: function ( source ) {
  4613. this.a = source.a;
  4614. this.b = source.b;
  4615. this.c = source.c;
  4616. this.normal.copy( source.normal );
  4617. this.color.copy( source.color );
  4618. this.materialIndex = source.materialIndex;
  4619. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  4620. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  4621. }
  4622. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  4623. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  4624. }
  4625. return this;
  4626. }
  4627. };
  4628. /**
  4629. * @author mrdoob / http://mrdoob.com/
  4630. * @author kile / http://kile.stravaganza.org/
  4631. * @author alteredq / http://alteredqualia.com/
  4632. * @author mikael emtinger / http://gomo.se/
  4633. * @author zz85 / http://www.lab4games.net/zz85/blog
  4634. * @author bhouston / http://clara.io
  4635. */
  4636. var count = 0;
  4637. function GeometryIdCount() { return count++; }
  4638. function Geometry() {
  4639. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  4640. this.uuid = _Math.generateUUID();
  4641. this.name = '';
  4642. this.type = 'Geometry';
  4643. this.vertices = [];
  4644. this.colors = [];
  4645. this.faces = [];
  4646. this.faceVertexUvs = [[]];
  4647. this.morphTargets = [];
  4648. this.morphNormals = [];
  4649. this.skinWeights = [];
  4650. this.skinIndices = [];
  4651. this.lineDistances = [];
  4652. this.boundingBox = null;
  4653. this.boundingSphere = null;
  4654. // update flags
  4655. this.elementsNeedUpdate = false;
  4656. this.verticesNeedUpdate = false;
  4657. this.uvsNeedUpdate = false;
  4658. this.normalsNeedUpdate = false;
  4659. this.colorsNeedUpdate = false;
  4660. this.lineDistancesNeedUpdate = false;
  4661. this.groupsNeedUpdate = false;
  4662. }
  4663. Geometry.prototype = {
  4664. constructor: Geometry,
  4665. isGeometry: true,
  4666. applyMatrix: function ( matrix ) {
  4667. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  4668. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4669. var vertex = this.vertices[ i ];
  4670. vertex.applyMatrix4( matrix );
  4671. }
  4672. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4673. var face = this.faces[ i ];
  4674. face.normal.applyMatrix3( normalMatrix ).normalize();
  4675. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4676. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4677. }
  4678. }
  4679. if ( this.boundingBox !== null ) {
  4680. this.computeBoundingBox();
  4681. }
  4682. if ( this.boundingSphere !== null ) {
  4683. this.computeBoundingSphere();
  4684. }
  4685. this.verticesNeedUpdate = true;
  4686. this.normalsNeedUpdate = true;
  4687. return this;
  4688. },
  4689. rotateX: function () {
  4690. // rotate geometry around world x-axis
  4691. var m1;
  4692. return function rotateX( angle ) {
  4693. if ( m1 === undefined ) m1 = new Matrix4();
  4694. m1.makeRotationX( angle );
  4695. this.applyMatrix( m1 );
  4696. return this;
  4697. };
  4698. }(),
  4699. rotateY: function () {
  4700. // rotate geometry around world y-axis
  4701. var m1;
  4702. return function rotateY( angle ) {
  4703. if ( m1 === undefined ) m1 = new Matrix4();
  4704. m1.makeRotationY( angle );
  4705. this.applyMatrix( m1 );
  4706. return this;
  4707. };
  4708. }(),
  4709. rotateZ: function () {
  4710. // rotate geometry around world z-axis
  4711. var m1;
  4712. return function rotateZ( angle ) {
  4713. if ( m1 === undefined ) m1 = new Matrix4();
  4714. m1.makeRotationZ( angle );
  4715. this.applyMatrix( m1 );
  4716. return this;
  4717. };
  4718. }(),
  4719. translate: function () {
  4720. // translate geometry
  4721. var m1;
  4722. return function translate( x, y, z ) {
  4723. if ( m1 === undefined ) m1 = new Matrix4();
  4724. m1.makeTranslation( x, y, z );
  4725. this.applyMatrix( m1 );
  4726. return this;
  4727. };
  4728. }(),
  4729. scale: function () {
  4730. // scale geometry
  4731. var m1;
  4732. return function scale( x, y, z ) {
  4733. if ( m1 === undefined ) m1 = new Matrix4();
  4734. m1.makeScale( x, y, z );
  4735. this.applyMatrix( m1 );
  4736. return this;
  4737. };
  4738. }(),
  4739. lookAt: function () {
  4740. var obj;
  4741. return function lookAt( vector ) {
  4742. if ( obj === undefined ) obj = new Object3D();
  4743. obj.lookAt( vector );
  4744. obj.updateMatrix();
  4745. this.applyMatrix( obj.matrix );
  4746. };
  4747. }(),
  4748. fromBufferGeometry: function ( geometry ) {
  4749. var scope = this;
  4750. var indices = geometry.index !== null ? geometry.index.array : undefined;
  4751. var attributes = geometry.attributes;
  4752. var positions = attributes.position.array;
  4753. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  4754. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  4755. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  4756. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  4757. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  4758. var tempNormals = [];
  4759. var tempUVs = [];
  4760. var tempUVs2 = [];
  4761. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  4762. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  4763. if ( normals !== undefined ) {
  4764. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  4765. }
  4766. if ( colors !== undefined ) {
  4767. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  4768. }
  4769. if ( uvs !== undefined ) {
  4770. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  4771. }
  4772. if ( uvs2 !== undefined ) {
  4773. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  4774. }
  4775. }
  4776. function addFace( a, b, c, materialIndex ) {
  4777. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  4778. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  4779. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  4780. scope.faces.push( face );
  4781. if ( uvs !== undefined ) {
  4782. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  4783. }
  4784. if ( uvs2 !== undefined ) {
  4785. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  4786. }
  4787. }
  4788. if ( indices !== undefined ) {
  4789. var groups = geometry.groups;
  4790. if ( groups.length > 0 ) {
  4791. for ( var i = 0; i < groups.length; i ++ ) {
  4792. var group = groups[ i ];
  4793. var start = group.start;
  4794. var count = group.count;
  4795. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  4796. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  4797. }
  4798. }
  4799. } else {
  4800. for ( var i = 0; i < indices.length; i += 3 ) {
  4801. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4802. }
  4803. }
  4804. } else {
  4805. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  4806. addFace( i, i + 1, i + 2 );
  4807. }
  4808. }
  4809. this.computeFaceNormals();
  4810. if ( geometry.boundingBox !== null ) {
  4811. this.boundingBox = geometry.boundingBox.clone();
  4812. }
  4813. if ( geometry.boundingSphere !== null ) {
  4814. this.boundingSphere = geometry.boundingSphere.clone();
  4815. }
  4816. return this;
  4817. },
  4818. center: function () {
  4819. this.computeBoundingBox();
  4820. var offset = this.boundingBox.getCenter().negate();
  4821. this.translate( offset.x, offset.y, offset.z );
  4822. return offset;
  4823. },
  4824. normalize: function () {
  4825. this.computeBoundingSphere();
  4826. var center = this.boundingSphere.center;
  4827. var radius = this.boundingSphere.radius;
  4828. var s = radius === 0 ? 1 : 1.0 / radius;
  4829. var matrix = new Matrix4();
  4830. matrix.set(
  4831. s, 0, 0, - s * center.x,
  4832. 0, s, 0, - s * center.y,
  4833. 0, 0, s, - s * center.z,
  4834. 0, 0, 0, 1
  4835. );
  4836. this.applyMatrix( matrix );
  4837. return this;
  4838. },
  4839. computeFaceNormals: function () {
  4840. var cb = new Vector3(), ab = new Vector3();
  4841. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4842. var face = this.faces[ f ];
  4843. var vA = this.vertices[ face.a ];
  4844. var vB = this.vertices[ face.b ];
  4845. var vC = this.vertices[ face.c ];
  4846. cb.subVectors( vC, vB );
  4847. ab.subVectors( vA, vB );
  4848. cb.cross( ab );
  4849. cb.normalize();
  4850. face.normal.copy( cb );
  4851. }
  4852. },
  4853. computeVertexNormals: function ( areaWeighted ) {
  4854. if ( areaWeighted === undefined ) areaWeighted = true;
  4855. var v, vl, f, fl, face, vertices;
  4856. vertices = new Array( this.vertices.length );
  4857. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4858. vertices[ v ] = new Vector3();
  4859. }
  4860. if ( areaWeighted ) {
  4861. // vertex normals weighted by triangle areas
  4862. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4863. var vA, vB, vC;
  4864. var cb = new Vector3(), ab = new Vector3();
  4865. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4866. face = this.faces[ f ];
  4867. vA = this.vertices[ face.a ];
  4868. vB = this.vertices[ face.b ];
  4869. vC = this.vertices[ face.c ];
  4870. cb.subVectors( vC, vB );
  4871. ab.subVectors( vA, vB );
  4872. cb.cross( ab );
  4873. vertices[ face.a ].add( cb );
  4874. vertices[ face.b ].add( cb );
  4875. vertices[ face.c ].add( cb );
  4876. }
  4877. } else {
  4878. this.computeFaceNormals();
  4879. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4880. face = this.faces[ f ];
  4881. vertices[ face.a ].add( face.normal );
  4882. vertices[ face.b ].add( face.normal );
  4883. vertices[ face.c ].add( face.normal );
  4884. }
  4885. }
  4886. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4887. vertices[ v ].normalize();
  4888. }
  4889. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4890. face = this.faces[ f ];
  4891. var vertexNormals = face.vertexNormals;
  4892. if ( vertexNormals.length === 3 ) {
  4893. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4894. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4895. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4896. } else {
  4897. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  4898. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  4899. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  4900. }
  4901. }
  4902. if ( this.faces.length > 0 ) {
  4903. this.normalsNeedUpdate = true;
  4904. }
  4905. },
  4906. computeFlatVertexNormals: function () {
  4907. var f, fl, face;
  4908. this.computeFaceNormals();
  4909. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4910. face = this.faces[ f ];
  4911. var vertexNormals = face.vertexNormals;
  4912. if ( vertexNormals.length === 3 ) {
  4913. vertexNormals[ 0 ].copy( face.normal );
  4914. vertexNormals[ 1 ].copy( face.normal );
  4915. vertexNormals[ 2 ].copy( face.normal );
  4916. } else {
  4917. vertexNormals[ 0 ] = face.normal.clone();
  4918. vertexNormals[ 1 ] = face.normal.clone();
  4919. vertexNormals[ 2 ] = face.normal.clone();
  4920. }
  4921. }
  4922. if ( this.faces.length > 0 ) {
  4923. this.normalsNeedUpdate = true;
  4924. }
  4925. },
  4926. computeMorphNormals: function () {
  4927. var i, il, f, fl, face;
  4928. // save original normals
  4929. // - create temp variables on first access
  4930. // otherwise just copy (for faster repeated calls)
  4931. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4932. face = this.faces[ f ];
  4933. if ( ! face.__originalFaceNormal ) {
  4934. face.__originalFaceNormal = face.normal.clone();
  4935. } else {
  4936. face.__originalFaceNormal.copy( face.normal );
  4937. }
  4938. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4939. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4940. if ( ! face.__originalVertexNormals[ i ] ) {
  4941. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4942. } else {
  4943. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4944. }
  4945. }
  4946. }
  4947. // use temp geometry to compute face and vertex normals for each morph
  4948. var tmpGeo = new Geometry();
  4949. tmpGeo.faces = this.faces;
  4950. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4951. // create on first access
  4952. if ( ! this.morphNormals[ i ] ) {
  4953. this.morphNormals[ i ] = {};
  4954. this.morphNormals[ i ].faceNormals = [];
  4955. this.morphNormals[ i ].vertexNormals = [];
  4956. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4957. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4958. var faceNormal, vertexNormals;
  4959. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4960. faceNormal = new Vector3();
  4961. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  4962. dstNormalsFace.push( faceNormal );
  4963. dstNormalsVertex.push( vertexNormals );
  4964. }
  4965. }
  4966. var morphNormals = this.morphNormals[ i ];
  4967. // set vertices to morph target
  4968. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4969. // compute morph normals
  4970. tmpGeo.computeFaceNormals();
  4971. tmpGeo.computeVertexNormals();
  4972. // store morph normals
  4973. var faceNormal, vertexNormals;
  4974. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4975. face = this.faces[ f ];
  4976. faceNormal = morphNormals.faceNormals[ f ];
  4977. vertexNormals = morphNormals.vertexNormals[ f ];
  4978. faceNormal.copy( face.normal );
  4979. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4980. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4981. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4982. }
  4983. }
  4984. // restore original normals
  4985. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4986. face = this.faces[ f ];
  4987. face.normal = face.__originalFaceNormal;
  4988. face.vertexNormals = face.__originalVertexNormals;
  4989. }
  4990. },
  4991. computeLineDistances: function () {
  4992. var d = 0;
  4993. var vertices = this.vertices;
  4994. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4995. if ( i > 0 ) {
  4996. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4997. }
  4998. this.lineDistances[ i ] = d;
  4999. }
  5000. },
  5001. computeBoundingBox: function () {
  5002. if ( this.boundingBox === null ) {
  5003. this.boundingBox = new Box3();
  5004. }
  5005. this.boundingBox.setFromPoints( this.vertices );
  5006. },
  5007. computeBoundingSphere: function () {
  5008. if ( this.boundingSphere === null ) {
  5009. this.boundingSphere = new Sphere();
  5010. }
  5011. this.boundingSphere.setFromPoints( this.vertices );
  5012. },
  5013. merge: function ( geometry, matrix, materialIndexOffset ) {
  5014. if ( ( geometry && geometry.isGeometry ) === false ) {
  5015. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  5016. return;
  5017. }
  5018. var normalMatrix,
  5019. vertexOffset = this.vertices.length,
  5020. vertices1 = this.vertices,
  5021. vertices2 = geometry.vertices,
  5022. faces1 = this.faces,
  5023. faces2 = geometry.faces,
  5024. uvs1 = this.faceVertexUvs[ 0 ],
  5025. uvs2 = geometry.faceVertexUvs[ 0 ],
  5026. colors1 = this.colors,
  5027. colors2 = geometry.colors;
  5028. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  5029. if ( matrix !== undefined ) {
  5030. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5031. }
  5032. // vertices
  5033. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  5034. var vertex = vertices2[ i ];
  5035. var vertexCopy = vertex.clone();
  5036. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  5037. vertices1.push( vertexCopy );
  5038. }
  5039. // colors
  5040. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  5041. colors1.push( colors2[ i ].clone() );
  5042. }
  5043. // faces
  5044. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  5045. var face = faces2[ i ], faceCopy, normal, color,
  5046. faceVertexNormals = face.vertexNormals,
  5047. faceVertexColors = face.vertexColors;
  5048. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  5049. faceCopy.normal.copy( face.normal );
  5050. if ( normalMatrix !== undefined ) {
  5051. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  5052. }
  5053. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  5054. normal = faceVertexNormals[ j ].clone();
  5055. if ( normalMatrix !== undefined ) {
  5056. normal.applyMatrix3( normalMatrix ).normalize();
  5057. }
  5058. faceCopy.vertexNormals.push( normal );
  5059. }
  5060. faceCopy.color.copy( face.color );
  5061. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  5062. color = faceVertexColors[ j ];
  5063. faceCopy.vertexColors.push( color.clone() );
  5064. }
  5065. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  5066. faces1.push( faceCopy );
  5067. }
  5068. // uvs
  5069. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  5070. var uv = uvs2[ i ], uvCopy = [];
  5071. if ( uv === undefined ) {
  5072. continue;
  5073. }
  5074. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5075. uvCopy.push( uv[ j ].clone() );
  5076. }
  5077. uvs1.push( uvCopy );
  5078. }
  5079. },
  5080. mergeMesh: function ( mesh ) {
  5081. if ( ( mesh && mesh.isMesh ) === false ) {
  5082. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  5083. return;
  5084. }
  5085. mesh.matrixAutoUpdate && mesh.updateMatrix();
  5086. this.merge( mesh.geometry, mesh.matrix );
  5087. },
  5088. /*
  5089. * Checks for duplicate vertices with hashmap.
  5090. * Duplicated vertices are removed
  5091. * and faces' vertices are updated.
  5092. */
  5093. mergeVertices: function () {
  5094. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  5095. var unique = [], changes = [];
  5096. var v, key;
  5097. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  5098. var precision = Math.pow( 10, precisionPoints );
  5099. var i, il, face;
  5100. var indices, j, jl;
  5101. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5102. v = this.vertices[ i ];
  5103. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5104. if ( verticesMap[ key ] === undefined ) {
  5105. verticesMap[ key ] = i;
  5106. unique.push( this.vertices[ i ] );
  5107. changes[ i ] = unique.length - 1;
  5108. } else {
  5109. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5110. changes[ i ] = changes[ verticesMap[ key ] ];
  5111. }
  5112. }
  5113. // if faces are completely degenerate after merging vertices, we
  5114. // have to remove them from the geometry.
  5115. var faceIndicesToRemove = [];
  5116. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  5117. face = this.faces[ i ];
  5118. face.a = changes[ face.a ];
  5119. face.b = changes[ face.b ];
  5120. face.c = changes[ face.c ];
  5121. indices = [ face.a, face.b, face.c ];
  5122. // if any duplicate vertices are found in a Face3
  5123. // we have to remove the face as nothing can be saved
  5124. for ( var n = 0; n < 3; n ++ ) {
  5125. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  5126. faceIndicesToRemove.push( i );
  5127. break;
  5128. }
  5129. }
  5130. }
  5131. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5132. var idx = faceIndicesToRemove[ i ];
  5133. this.faces.splice( idx, 1 );
  5134. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5135. this.faceVertexUvs[ j ].splice( idx, 1 );
  5136. }
  5137. }
  5138. // Use unique set of vertices
  5139. var diff = this.vertices.length - unique.length;
  5140. this.vertices = unique;
  5141. return diff;
  5142. },
  5143. sortFacesByMaterialIndex: function () {
  5144. var faces = this.faces;
  5145. var length = faces.length;
  5146. // tag faces
  5147. for ( var i = 0; i < length; i ++ ) {
  5148. faces[ i ]._id = i;
  5149. }
  5150. // sort faces
  5151. function materialIndexSort( a, b ) {
  5152. return a.materialIndex - b.materialIndex;
  5153. }
  5154. faces.sort( materialIndexSort );
  5155. // sort uvs
  5156. var uvs1 = this.faceVertexUvs[ 0 ];
  5157. var uvs2 = this.faceVertexUvs[ 1 ];
  5158. var newUvs1, newUvs2;
  5159. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  5160. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  5161. for ( var i = 0; i < length; i ++ ) {
  5162. var id = faces[ i ]._id;
  5163. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  5164. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  5165. }
  5166. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  5167. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  5168. },
  5169. toJSON: function () {
  5170. var data = {
  5171. metadata: {
  5172. version: 4.4,
  5173. type: 'Geometry',
  5174. generator: 'Geometry.toJSON'
  5175. }
  5176. };
  5177. // standard Geometry serialization
  5178. data.uuid = this.uuid;
  5179. data.type = this.type;
  5180. if ( this.name !== '' ) data.name = this.name;
  5181. if ( this.parameters !== undefined ) {
  5182. var parameters = this.parameters;
  5183. for ( var key in parameters ) {
  5184. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  5185. }
  5186. return data;
  5187. }
  5188. var vertices = [];
  5189. for ( var i = 0; i < this.vertices.length; i ++ ) {
  5190. var vertex = this.vertices[ i ];
  5191. vertices.push( vertex.x, vertex.y, vertex.z );
  5192. }
  5193. var faces = [];
  5194. var normals = [];
  5195. var normalsHash = {};
  5196. var colors = [];
  5197. var colorsHash = {};
  5198. var uvs = [];
  5199. var uvsHash = {};
  5200. for ( var i = 0; i < this.faces.length; i ++ ) {
  5201. var face = this.faces[ i ];
  5202. var hasMaterial = true;
  5203. var hasFaceUv = false; // deprecated
  5204. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  5205. var hasFaceNormal = face.normal.length() > 0;
  5206. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  5207. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  5208. var hasFaceVertexColor = face.vertexColors.length > 0;
  5209. var faceType = 0;
  5210. faceType = setBit( faceType, 0, 0 ); // isQuad
  5211. faceType = setBit( faceType, 1, hasMaterial );
  5212. faceType = setBit( faceType, 2, hasFaceUv );
  5213. faceType = setBit( faceType, 3, hasFaceVertexUv );
  5214. faceType = setBit( faceType, 4, hasFaceNormal );
  5215. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  5216. faceType = setBit( faceType, 6, hasFaceColor );
  5217. faceType = setBit( faceType, 7, hasFaceVertexColor );
  5218. faces.push( faceType );
  5219. faces.push( face.a, face.b, face.c );
  5220. faces.push( face.materialIndex );
  5221. if ( hasFaceVertexUv ) {
  5222. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  5223. faces.push(
  5224. getUvIndex( faceVertexUvs[ 0 ] ),
  5225. getUvIndex( faceVertexUvs[ 1 ] ),
  5226. getUvIndex( faceVertexUvs[ 2 ] )
  5227. );
  5228. }
  5229. if ( hasFaceNormal ) {
  5230. faces.push( getNormalIndex( face.normal ) );
  5231. }
  5232. if ( hasFaceVertexNormal ) {
  5233. var vertexNormals = face.vertexNormals;
  5234. faces.push(
  5235. getNormalIndex( vertexNormals[ 0 ] ),
  5236. getNormalIndex( vertexNormals[ 1 ] ),
  5237. getNormalIndex( vertexNormals[ 2 ] )
  5238. );
  5239. }
  5240. if ( hasFaceColor ) {
  5241. faces.push( getColorIndex( face.color ) );
  5242. }
  5243. if ( hasFaceVertexColor ) {
  5244. var vertexColors = face.vertexColors;
  5245. faces.push(
  5246. getColorIndex( vertexColors[ 0 ] ),
  5247. getColorIndex( vertexColors[ 1 ] ),
  5248. getColorIndex( vertexColors[ 2 ] )
  5249. );
  5250. }
  5251. }
  5252. function setBit( value, position, enabled ) {
  5253. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  5254. }
  5255. function getNormalIndex( normal ) {
  5256. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  5257. if ( normalsHash[ hash ] !== undefined ) {
  5258. return normalsHash[ hash ];
  5259. }
  5260. normalsHash[ hash ] = normals.length / 3;
  5261. normals.push( normal.x, normal.y, normal.z );
  5262. return normalsHash[ hash ];
  5263. }
  5264. function getColorIndex( color ) {
  5265. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  5266. if ( colorsHash[ hash ] !== undefined ) {
  5267. return colorsHash[ hash ];
  5268. }
  5269. colorsHash[ hash ] = colors.length;
  5270. colors.push( color.getHex() );
  5271. return colorsHash[ hash ];
  5272. }
  5273. function getUvIndex( uv ) {
  5274. var hash = uv.x.toString() + uv.y.toString();
  5275. if ( uvsHash[ hash ] !== undefined ) {
  5276. return uvsHash[ hash ];
  5277. }
  5278. uvsHash[ hash ] = uvs.length / 2;
  5279. uvs.push( uv.x, uv.y );
  5280. return uvsHash[ hash ];
  5281. }
  5282. data.data = {};
  5283. data.data.vertices = vertices;
  5284. data.data.normals = normals;
  5285. if ( colors.length > 0 ) data.data.colors = colors;
  5286. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  5287. data.data.faces = faces;
  5288. return data;
  5289. },
  5290. clone: function () {
  5291. /*
  5292. // Handle primitives
  5293. var parameters = this.parameters;
  5294. if ( parameters !== undefined ) {
  5295. var values = [];
  5296. for ( var key in parameters ) {
  5297. values.push( parameters[ key ] );
  5298. }
  5299. var geometry = Object.create( this.constructor.prototype );
  5300. this.constructor.apply( geometry, values );
  5301. return geometry;
  5302. }
  5303. return new this.constructor().copy( this );
  5304. */
  5305. return new Geometry().copy( this );
  5306. },
  5307. copy: function ( source ) {
  5308. var i, il, j, jl, k, kl;
  5309. // reset
  5310. this.vertices = [];
  5311. this.colors = [];
  5312. this.faces = [];
  5313. this.faceVertexUvs = [[]];
  5314. this.morphTargets = [];
  5315. this.morphNormals = [];
  5316. this.skinWeights = [];
  5317. this.skinIndices = [];
  5318. this.lineDistances = [];
  5319. this.boundingBox = null;
  5320. this.boundingSphere = null;
  5321. // name
  5322. this.name = source.name;
  5323. // vertices
  5324. var vertices = source.vertices;
  5325. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  5326. this.vertices.push( vertices[ i ].clone() );
  5327. }
  5328. // colors
  5329. var colors = source.colors;
  5330. for ( i = 0, il = colors.length; i < il; i ++ ) {
  5331. this.colors.push( colors[ i ].clone() );
  5332. }
  5333. // faces
  5334. var faces = source.faces;
  5335. for ( i = 0, il = faces.length; i < il; i ++ ) {
  5336. this.faces.push( faces[ i ].clone() );
  5337. }
  5338. // face vertex uvs
  5339. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  5340. var faceVertexUvs = source.faceVertexUvs[ i ];
  5341. if ( this.faceVertexUvs[ i ] === undefined ) {
  5342. this.faceVertexUvs[ i ] = [];
  5343. }
  5344. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  5345. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  5346. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  5347. var uv = uvs[ k ];
  5348. uvsCopy.push( uv.clone() );
  5349. }
  5350. this.faceVertexUvs[ i ].push( uvsCopy );
  5351. }
  5352. }
  5353. // morph targets
  5354. var morphTargets = source.morphTargets;
  5355. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  5356. var morphTarget = {};
  5357. morphTarget.name = morphTargets[ i ].name;
  5358. // vertices
  5359. if ( morphTargets[ i ].vertices !== undefined ) {
  5360. morphTarget.vertices = [];
  5361. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  5362. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  5363. }
  5364. }
  5365. // normals
  5366. if ( morphTargets[ i ].normals !== undefined ) {
  5367. morphTarget.normals = [];
  5368. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  5369. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  5370. }
  5371. }
  5372. this.morphTargets.push( morphTarget );
  5373. }
  5374. // morph normals
  5375. var morphNormals = source.morphNormals;
  5376. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  5377. var morphNormal = {};
  5378. // vertex normals
  5379. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  5380. morphNormal.vertexNormals = [];
  5381. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  5382. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  5383. var destVertexNormal = {};
  5384. destVertexNormal.a = srcVertexNormal.a.clone();
  5385. destVertexNormal.b = srcVertexNormal.b.clone();
  5386. destVertexNormal.c = srcVertexNormal.c.clone();
  5387. morphNormal.vertexNormals.push( destVertexNormal );
  5388. }
  5389. }
  5390. // face normals
  5391. if ( morphNormals[ i ].faceNormals !== undefined ) {
  5392. morphNormal.faceNormals = [];
  5393. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  5394. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  5395. }
  5396. }
  5397. this.morphNormals.push( morphNormal );
  5398. }
  5399. // skin weights
  5400. var skinWeights = source.skinWeights;
  5401. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  5402. this.skinWeights.push( skinWeights[ i ].clone() );
  5403. }
  5404. // skin indices
  5405. var skinIndices = source.skinIndices;
  5406. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  5407. this.skinIndices.push( skinIndices[ i ].clone() );
  5408. }
  5409. // line distances
  5410. var lineDistances = source.lineDistances;
  5411. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  5412. this.lineDistances.push( lineDistances[ i ] );
  5413. }
  5414. // bounding box
  5415. var boundingBox = source.boundingBox;
  5416. if ( boundingBox !== null ) {
  5417. this.boundingBox = boundingBox.clone();
  5418. }
  5419. // bounding sphere
  5420. var boundingSphere = source.boundingSphere;
  5421. if ( boundingSphere !== null ) {
  5422. this.boundingSphere = boundingSphere.clone();
  5423. }
  5424. // update flags
  5425. this.elementsNeedUpdate = source.elementsNeedUpdate;
  5426. this.verticesNeedUpdate = source.verticesNeedUpdate;
  5427. this.uvsNeedUpdate = source.uvsNeedUpdate;
  5428. this.normalsNeedUpdate = source.normalsNeedUpdate;
  5429. this.colorsNeedUpdate = source.colorsNeedUpdate;
  5430. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  5431. this.groupsNeedUpdate = source.groupsNeedUpdate;
  5432. return this;
  5433. },
  5434. dispose: function () {
  5435. this.dispatchEvent( { type: 'dispose' } );
  5436. }
  5437. };
  5438. Object.assign( Geometry.prototype, EventDispatcher.prototype );
  5439. /**
  5440. * @author alteredq / http://alteredqualia.com/
  5441. * @author mrdoob / http://mrdoob.com/
  5442. */
  5443. function BufferGeometry() {
  5444. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  5445. this.uuid = _Math.generateUUID();
  5446. this.name = '';
  5447. this.type = 'BufferGeometry';
  5448. this.index = null;
  5449. this.attributes = {};
  5450. this.morphAttributes = {};
  5451. this.groups = [];
  5452. this.boundingBox = null;
  5453. this.boundingSphere = null;
  5454. this.drawRange = { start: 0, count: Infinity };
  5455. }
  5456. BufferGeometry.prototype = {
  5457. constructor: BufferGeometry,
  5458. isBufferGeometry: true,
  5459. getIndex: function () {
  5460. return this.index;
  5461. },
  5462. setIndex: function ( index ) {
  5463. if ( Array.isArray( index ) ) {
  5464. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5465. } else {
  5466. this.index = index;
  5467. }
  5468. },
  5469. addAttribute: function ( name, attribute ) {
  5470. if ( ( attribute && attribute.isBufferAttribute ) === false && ( attribute && attribute.isInterleavedBufferAttribute ) === false ) {
  5471. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  5472. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  5473. return;
  5474. }
  5475. if ( name === 'index' ) {
  5476. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  5477. this.setIndex( attribute );
  5478. return;
  5479. }
  5480. this.attributes[ name ] = attribute;
  5481. return this;
  5482. },
  5483. getAttribute: function ( name ) {
  5484. return this.attributes[ name ];
  5485. },
  5486. removeAttribute: function ( name ) {
  5487. delete this.attributes[ name ];
  5488. return this;
  5489. },
  5490. addGroup: function ( start, count, materialIndex ) {
  5491. this.groups.push( {
  5492. start: start,
  5493. count: count,
  5494. materialIndex: materialIndex !== undefined ? materialIndex : 0
  5495. } );
  5496. },
  5497. clearGroups: function () {
  5498. this.groups = [];
  5499. },
  5500. setDrawRange: function ( start, count ) {
  5501. this.drawRange.start = start;
  5502. this.drawRange.count = count;
  5503. },
  5504. applyMatrix: function ( matrix ) {
  5505. var position = this.attributes.position;
  5506. if ( position !== undefined ) {
  5507. matrix.applyToBufferAttribute( position );
  5508. position.needsUpdate = true;
  5509. }
  5510. var normal = this.attributes.normal;
  5511. if ( normal !== undefined ) {
  5512. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5513. normalMatrix.applyToBufferAttribute( normal );
  5514. normal.needsUpdate = true;
  5515. }
  5516. if ( this.boundingBox !== null ) {
  5517. this.computeBoundingBox();
  5518. }
  5519. if ( this.boundingSphere !== null ) {
  5520. this.computeBoundingSphere();
  5521. }
  5522. return this;
  5523. },
  5524. rotateX: function () {
  5525. // rotate geometry around world x-axis
  5526. var m1;
  5527. return function rotateX( angle ) {
  5528. if ( m1 === undefined ) m1 = new Matrix4();
  5529. m1.makeRotationX( angle );
  5530. this.applyMatrix( m1 );
  5531. return this;
  5532. };
  5533. }(),
  5534. rotateY: function () {
  5535. // rotate geometry around world y-axis
  5536. var m1;
  5537. return function rotateY( angle ) {
  5538. if ( m1 === undefined ) m1 = new Matrix4();
  5539. m1.makeRotationY( angle );
  5540. this.applyMatrix( m1 );
  5541. return this;
  5542. };
  5543. }(),
  5544. rotateZ: function () {
  5545. // rotate geometry around world z-axis
  5546. var m1;
  5547. return function rotateZ( angle ) {
  5548. if ( m1 === undefined ) m1 = new Matrix4();
  5549. m1.makeRotationZ( angle );
  5550. this.applyMatrix( m1 );
  5551. return this;
  5552. };
  5553. }(),
  5554. translate: function () {
  5555. // translate geometry
  5556. var m1;
  5557. return function translate( x, y, z ) {
  5558. if ( m1 === undefined ) m1 = new Matrix4();
  5559. m1.makeTranslation( x, y, z );
  5560. this.applyMatrix( m1 );
  5561. return this;
  5562. };
  5563. }(),
  5564. scale: function () {
  5565. // scale geometry
  5566. var m1;
  5567. return function scale( x, y, z ) {
  5568. if ( m1 === undefined ) m1 = new Matrix4();
  5569. m1.makeScale( x, y, z );
  5570. this.applyMatrix( m1 );
  5571. return this;
  5572. };
  5573. }(),
  5574. lookAt: function () {
  5575. var obj;
  5576. return function lookAt( vector ) {
  5577. if ( obj === undefined ) obj = new Object3D();
  5578. obj.lookAt( vector );
  5579. obj.updateMatrix();
  5580. this.applyMatrix( obj.matrix );
  5581. };
  5582. }(),
  5583. center: function () {
  5584. this.computeBoundingBox();
  5585. var offset = this.boundingBox.getCenter().negate();
  5586. this.translate( offset.x, offset.y, offset.z );
  5587. return offset;
  5588. },
  5589. setFromObject: function ( object ) {
  5590. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  5591. var geometry = object.geometry;
  5592. if ( object.isPoints || object.isLine ) {
  5593. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  5594. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  5595. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  5596. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  5597. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  5598. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  5599. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  5600. }
  5601. if ( geometry.boundingSphere !== null ) {
  5602. this.boundingSphere = geometry.boundingSphere.clone();
  5603. }
  5604. if ( geometry.boundingBox !== null ) {
  5605. this.boundingBox = geometry.boundingBox.clone();
  5606. }
  5607. } else if ( object.isMesh ) {
  5608. if ( geometry && geometry.isGeometry ) {
  5609. this.fromGeometry( geometry );
  5610. }
  5611. }
  5612. return this;
  5613. },
  5614. updateFromObject: function ( object ) {
  5615. var geometry = object.geometry;
  5616. if ( object.isMesh ) {
  5617. var direct = geometry.__directGeometry;
  5618. if ( geometry.elementsNeedUpdate === true ) {
  5619. direct = undefined;
  5620. geometry.elementsNeedUpdate = false;
  5621. }
  5622. if ( direct === undefined ) {
  5623. return this.fromGeometry( geometry );
  5624. }
  5625. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  5626. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  5627. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  5628. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  5629. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  5630. geometry.verticesNeedUpdate = false;
  5631. geometry.normalsNeedUpdate = false;
  5632. geometry.colorsNeedUpdate = false;
  5633. geometry.uvsNeedUpdate = false;
  5634. geometry.groupsNeedUpdate = false;
  5635. geometry = direct;
  5636. }
  5637. var attribute;
  5638. if ( geometry.verticesNeedUpdate === true ) {
  5639. attribute = this.attributes.position;
  5640. if ( attribute !== undefined ) {
  5641. attribute.copyVector3sArray( geometry.vertices );
  5642. attribute.needsUpdate = true;
  5643. }
  5644. geometry.verticesNeedUpdate = false;
  5645. }
  5646. if ( geometry.normalsNeedUpdate === true ) {
  5647. attribute = this.attributes.normal;
  5648. if ( attribute !== undefined ) {
  5649. attribute.copyVector3sArray( geometry.normals );
  5650. attribute.needsUpdate = true;
  5651. }
  5652. geometry.normalsNeedUpdate = false;
  5653. }
  5654. if ( geometry.colorsNeedUpdate === true ) {
  5655. attribute = this.attributes.color;
  5656. if ( attribute !== undefined ) {
  5657. attribute.copyColorsArray( geometry.colors );
  5658. attribute.needsUpdate = true;
  5659. }
  5660. geometry.colorsNeedUpdate = false;
  5661. }
  5662. if ( geometry.uvsNeedUpdate ) {
  5663. attribute = this.attributes.uv;
  5664. if ( attribute !== undefined ) {
  5665. attribute.copyVector2sArray( geometry.uvs );
  5666. attribute.needsUpdate = true;
  5667. }
  5668. geometry.uvsNeedUpdate = false;
  5669. }
  5670. if ( geometry.lineDistancesNeedUpdate ) {
  5671. attribute = this.attributes.lineDistance;
  5672. if ( attribute !== undefined ) {
  5673. attribute.copyArray( geometry.lineDistances );
  5674. attribute.needsUpdate = true;
  5675. }
  5676. geometry.lineDistancesNeedUpdate = false;
  5677. }
  5678. if ( geometry.groupsNeedUpdate ) {
  5679. geometry.computeGroups( object.geometry );
  5680. this.groups = geometry.groups;
  5681. geometry.groupsNeedUpdate = false;
  5682. }
  5683. return this;
  5684. },
  5685. fromGeometry: function ( geometry ) {
  5686. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  5687. return this.fromDirectGeometry( geometry.__directGeometry );
  5688. },
  5689. fromDirectGeometry: function ( geometry ) {
  5690. var positions = new Float32Array( geometry.vertices.length * 3 );
  5691. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  5692. if ( geometry.normals.length > 0 ) {
  5693. var normals = new Float32Array( geometry.normals.length * 3 );
  5694. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  5695. }
  5696. if ( geometry.colors.length > 0 ) {
  5697. var colors = new Float32Array( geometry.colors.length * 3 );
  5698. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  5699. }
  5700. if ( geometry.uvs.length > 0 ) {
  5701. var uvs = new Float32Array( geometry.uvs.length * 2 );
  5702. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  5703. }
  5704. if ( geometry.uvs2.length > 0 ) {
  5705. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  5706. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  5707. }
  5708. if ( geometry.indices.length > 0 ) {
  5709. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  5710. var indices = new TypeArray( geometry.indices.length * 3 );
  5711. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  5712. }
  5713. // groups
  5714. this.groups = geometry.groups;
  5715. // morphs
  5716. for ( var name in geometry.morphTargets ) {
  5717. var array = [];
  5718. var morphTargets = geometry.morphTargets[ name ];
  5719. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  5720. var morphTarget = morphTargets[ i ];
  5721. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  5722. array.push( attribute.copyVector3sArray( morphTarget ) );
  5723. }
  5724. this.morphAttributes[ name ] = array;
  5725. }
  5726. // skinning
  5727. if ( geometry.skinIndices.length > 0 ) {
  5728. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  5729. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  5730. }
  5731. if ( geometry.skinWeights.length > 0 ) {
  5732. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  5733. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  5734. }
  5735. //
  5736. if ( geometry.boundingSphere !== null ) {
  5737. this.boundingSphere = geometry.boundingSphere.clone();
  5738. }
  5739. if ( geometry.boundingBox !== null ) {
  5740. this.boundingBox = geometry.boundingBox.clone();
  5741. }
  5742. return this;
  5743. },
  5744. computeBoundingBox: function () {
  5745. if ( this.boundingBox === null ) {
  5746. this.boundingBox = new Box3();
  5747. }
  5748. var position = this.attributes.position;
  5749. if ( position !== undefined ) {
  5750. this.boundingBox.setFromBufferAttribute( position );
  5751. } else {
  5752. this.boundingBox.makeEmpty();
  5753. }
  5754. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5755. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  5756. }
  5757. },
  5758. computeBoundingSphere: function () {
  5759. var box = new Box3();
  5760. var vector = new Vector3();
  5761. return function computeBoundingSphere() {
  5762. if ( this.boundingSphere === null ) {
  5763. this.boundingSphere = new Sphere();
  5764. }
  5765. var position = this.attributes.position;
  5766. if ( position ) {
  5767. var center = this.boundingSphere.center;
  5768. box.setFromBufferAttribute( position );
  5769. box.getCenter( center );
  5770. // hoping to find a boundingSphere with a radius smaller than the
  5771. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5772. var maxRadiusSq = 0;
  5773. for ( var i = 0, il = position.count; i < il; i ++ ) {
  5774. vector.x = position.getX( i );
  5775. vector.y = position.getY( i );
  5776. vector.z = position.getZ( i );
  5777. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5778. }
  5779. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5780. if ( isNaN( this.boundingSphere.radius ) ) {
  5781. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  5782. }
  5783. }
  5784. };
  5785. }(),
  5786. computeFaceNormals: function () {
  5787. // backwards compatibility
  5788. },
  5789. computeVertexNormals: function () {
  5790. var index = this.index;
  5791. var attributes = this.attributes;
  5792. var groups = this.groups;
  5793. if ( attributes.position ) {
  5794. var positions = attributes.position.array;
  5795. if ( attributes.normal === undefined ) {
  5796. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  5797. } else {
  5798. // reset existing normals to zero
  5799. var array = attributes.normal.array;
  5800. for ( var i = 0, il = array.length; i < il; i ++ ) {
  5801. array[ i ] = 0;
  5802. }
  5803. }
  5804. var normals = attributes.normal.array;
  5805. var vA, vB, vC;
  5806. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  5807. var cb = new Vector3(), ab = new Vector3();
  5808. // indexed elements
  5809. if ( index ) {
  5810. var indices = index.array;
  5811. if ( groups.length === 0 ) {
  5812. this.addGroup( 0, indices.length );
  5813. }
  5814. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  5815. var group = groups[ j ];
  5816. var start = group.start;
  5817. var count = group.count;
  5818. for ( var i = start, il = start + count; i < il; i += 3 ) {
  5819. vA = indices[ i + 0 ] * 3;
  5820. vB = indices[ i + 1 ] * 3;
  5821. vC = indices[ i + 2 ] * 3;
  5822. pA.fromArray( positions, vA );
  5823. pB.fromArray( positions, vB );
  5824. pC.fromArray( positions, vC );
  5825. cb.subVectors( pC, pB );
  5826. ab.subVectors( pA, pB );
  5827. cb.cross( ab );
  5828. normals[ vA ] += cb.x;
  5829. normals[ vA + 1 ] += cb.y;
  5830. normals[ vA + 2 ] += cb.z;
  5831. normals[ vB ] += cb.x;
  5832. normals[ vB + 1 ] += cb.y;
  5833. normals[ vB + 2 ] += cb.z;
  5834. normals[ vC ] += cb.x;
  5835. normals[ vC + 1 ] += cb.y;
  5836. normals[ vC + 2 ] += cb.z;
  5837. }
  5838. }
  5839. } else {
  5840. // non-indexed elements (unconnected triangle soup)
  5841. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  5842. pA.fromArray( positions, i );
  5843. pB.fromArray( positions, i + 3 );
  5844. pC.fromArray( positions, i + 6 );
  5845. cb.subVectors( pC, pB );
  5846. ab.subVectors( pA, pB );
  5847. cb.cross( ab );
  5848. normals[ i ] = cb.x;
  5849. normals[ i + 1 ] = cb.y;
  5850. normals[ i + 2 ] = cb.z;
  5851. normals[ i + 3 ] = cb.x;
  5852. normals[ i + 4 ] = cb.y;
  5853. normals[ i + 5 ] = cb.z;
  5854. normals[ i + 6 ] = cb.x;
  5855. normals[ i + 7 ] = cb.y;
  5856. normals[ i + 8 ] = cb.z;
  5857. }
  5858. }
  5859. this.normalizeNormals();
  5860. attributes.normal.needsUpdate = true;
  5861. }
  5862. },
  5863. merge: function ( geometry, offset ) {
  5864. if ( ( geometry && geometry.isBufferGeometry ) === false ) {
  5865. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  5866. return;
  5867. }
  5868. if ( offset === undefined ) offset = 0;
  5869. var attributes = this.attributes;
  5870. for ( var key in attributes ) {
  5871. if ( geometry.attributes[ key ] === undefined ) continue;
  5872. var attribute1 = attributes[ key ];
  5873. var attributeArray1 = attribute1.array;
  5874. var attribute2 = geometry.attributes[ key ];
  5875. var attributeArray2 = attribute2.array;
  5876. var attributeSize = attribute2.itemSize;
  5877. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  5878. attributeArray1[ j ] = attributeArray2[ i ];
  5879. }
  5880. }
  5881. return this;
  5882. },
  5883. normalizeNormals: function () {
  5884. var normals = this.attributes.normal.array;
  5885. var x, y, z, n;
  5886. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5887. x = normals[ i ];
  5888. y = normals[ i + 1 ];
  5889. z = normals[ i + 2 ];
  5890. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5891. normals[ i ] *= n;
  5892. normals[ i + 1 ] *= n;
  5893. normals[ i + 2 ] *= n;
  5894. }
  5895. },
  5896. toNonIndexed: function () {
  5897. if ( this.index === null ) {
  5898. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  5899. return this;
  5900. }
  5901. var geometry2 = new BufferGeometry();
  5902. var indices = this.index.array;
  5903. var attributes = this.attributes;
  5904. for ( var name in attributes ) {
  5905. var attribute = attributes[ name ];
  5906. var array = attribute.array;
  5907. var itemSize = attribute.itemSize;
  5908. var array2 = new array.constructor( indices.length * itemSize );
  5909. var index = 0, index2 = 0;
  5910. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  5911. index = indices[ i ] * itemSize;
  5912. for ( var j = 0; j < itemSize; j ++ ) {
  5913. array2[ index2 ++ ] = array[ index ++ ];
  5914. }
  5915. }
  5916. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  5917. }
  5918. return geometry2;
  5919. },
  5920. toJSON: function () {
  5921. var data = {
  5922. metadata: {
  5923. version: 4.4,
  5924. type: 'BufferGeometry',
  5925. generator: 'BufferGeometry.toJSON'
  5926. }
  5927. };
  5928. // standard BufferGeometry serialization
  5929. data.uuid = this.uuid;
  5930. data.type = this.type;
  5931. if ( this.name !== '' ) data.name = this.name;
  5932. if ( this.parameters !== undefined ) {
  5933. var parameters = this.parameters;
  5934. for ( var key in parameters ) {
  5935. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  5936. }
  5937. return data;
  5938. }
  5939. data.data = { attributes: {} };
  5940. var index = this.index;
  5941. if ( index !== null ) {
  5942. var array = Array.prototype.slice.call( index.array );
  5943. data.data.index = {
  5944. type: index.array.constructor.name,
  5945. array: array
  5946. };
  5947. }
  5948. var attributes = this.attributes;
  5949. for ( var key in attributes ) {
  5950. var attribute = attributes[ key ];
  5951. var array = Array.prototype.slice.call( attribute.array );
  5952. data.data.attributes[ key ] = {
  5953. itemSize: attribute.itemSize,
  5954. type: attribute.array.constructor.name,
  5955. array: array,
  5956. normalized: attribute.normalized
  5957. };
  5958. }
  5959. var groups = this.groups;
  5960. if ( groups.length > 0 ) {
  5961. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  5962. }
  5963. var boundingSphere = this.boundingSphere;
  5964. if ( boundingSphere !== null ) {
  5965. data.data.boundingSphere = {
  5966. center: boundingSphere.center.toArray(),
  5967. radius: boundingSphere.radius
  5968. };
  5969. }
  5970. return data;
  5971. },
  5972. clone: function () {
  5973. /*
  5974. // Handle primitives
  5975. var parameters = this.parameters;
  5976. if ( parameters !== undefined ) {
  5977. var values = [];
  5978. for ( var key in parameters ) {
  5979. values.push( parameters[ key ] );
  5980. }
  5981. var geometry = Object.create( this.constructor.prototype );
  5982. this.constructor.apply( geometry, values );
  5983. return geometry;
  5984. }
  5985. return new this.constructor().copy( this );
  5986. */
  5987. return new BufferGeometry().copy( this );
  5988. },
  5989. copy: function ( source ) {
  5990. var name, i, l;
  5991. // reset
  5992. this.index = null;
  5993. this.attributes = {};
  5994. this.morphAttributes = {};
  5995. this.groups = [];
  5996. this.boundingBox = null;
  5997. this.boundingSphere = null;
  5998. // name
  5999. this.name = source.name;
  6000. // index
  6001. var index = source.index;
  6002. if ( index !== null ) {
  6003. this.setIndex( index.clone() );
  6004. }
  6005. // attributes
  6006. var attributes = source.attributes;
  6007. for ( name in attributes ) {
  6008. var attribute = attributes[ name ];
  6009. this.addAttribute( name, attribute.clone() );
  6010. }
  6011. // morph attributes
  6012. var morphAttributes = source.morphAttributes;
  6013. for ( name in morphAttributes ) {
  6014. var array = [];
  6015. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6016. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6017. array.push( morphAttribute[ i ].clone() );
  6018. }
  6019. this.morphAttributes[ name ] = array;
  6020. }
  6021. // groups
  6022. var groups = source.groups;
  6023. for ( i = 0, l = groups.length; i < l; i ++ ) {
  6024. var group = groups[ i ];
  6025. this.addGroup( group.start, group.count, group.materialIndex );
  6026. }
  6027. // bounding box
  6028. var boundingBox = source.boundingBox;
  6029. if ( boundingBox !== null ) {
  6030. this.boundingBox = boundingBox.clone();
  6031. }
  6032. // bounding sphere
  6033. var boundingSphere = source.boundingSphere;
  6034. if ( boundingSphere !== null ) {
  6035. this.boundingSphere = boundingSphere.clone();
  6036. }
  6037. // draw range
  6038. this.drawRange.start = source.drawRange.start;
  6039. this.drawRange.count = source.drawRange.count;
  6040. return this;
  6041. },
  6042. dispose: function () {
  6043. this.dispatchEvent( { type: 'dispose' } );
  6044. }
  6045. };
  6046. BufferGeometry.MaxIndex = 65535;
  6047. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype );
  6048. /**
  6049. * @author mrdoob / http://mrdoob.com/
  6050. */
  6051. function Uniform( value ) {
  6052. if ( typeof value === 'string' ) {
  6053. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  6054. value = arguments[ 1 ];
  6055. }
  6056. this.value = value;
  6057. }
  6058. Uniform.prototype.clone = function () {
  6059. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  6060. };
  6061. /**
  6062. * @author zz85 / http://www.lab4games.net/zz85/blog
  6063. * Extensible curve object
  6064. *
  6065. * Some common of Curve methods
  6066. * .getPoint(t), getTangent(t)
  6067. * .getPointAt(u), getTangentAt(u)
  6068. * .getPoints(), .getSpacedPoints()
  6069. * .getLength()
  6070. * .updateArcLengths()
  6071. *
  6072. * This following classes subclasses THREE.Curve:
  6073. *
  6074. * -- 2d classes --
  6075. * THREE.LineCurve
  6076. * THREE.QuadraticBezierCurve
  6077. * THREE.CubicBezierCurve
  6078. * THREE.SplineCurve
  6079. * THREE.ArcCurve
  6080. * THREE.EllipseCurve
  6081. *
  6082. * -- 3d classes --
  6083. * THREE.LineCurve3
  6084. * THREE.QuadraticBezierCurve3
  6085. * THREE.CubicBezierCurve3
  6086. * THREE.CatmullRomCurve3
  6087. *
  6088. * A series of curves can be represented as a THREE.CurvePath
  6089. *
  6090. **/
  6091. /**************************************************************
  6092. * Abstract Curve base class
  6093. **************************************************************/
  6094. function Curve() {}
  6095. Curve.prototype = {
  6096. constructor: Curve,
  6097. // Virtual base class method to overwrite and implement in subclasses
  6098. // - t [0 .. 1]
  6099. getPoint: function ( t ) {
  6100. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  6101. return null;
  6102. },
  6103. // Get point at relative position in curve according to arc length
  6104. // - u [0 .. 1]
  6105. getPointAt: function ( u ) {
  6106. var t = this.getUtoTmapping( u );
  6107. return this.getPoint( t );
  6108. },
  6109. // Get sequence of points using getPoint( t )
  6110. getPoints: function ( divisions ) {
  6111. if ( isNaN( divisions ) ) divisions = 5;
  6112. var points = [];
  6113. for ( var d = 0; d <= divisions; d ++ ) {
  6114. points.push( this.getPoint( d / divisions ) );
  6115. }
  6116. return points;
  6117. },
  6118. // Get sequence of points using getPointAt( u )
  6119. getSpacedPoints: function ( divisions ) {
  6120. if ( isNaN( divisions ) ) divisions = 5;
  6121. var points = [];
  6122. for ( var d = 0; d <= divisions; d ++ ) {
  6123. points.push( this.getPointAt( d / divisions ) );
  6124. }
  6125. return points;
  6126. },
  6127. // Get total curve arc length
  6128. getLength: function () {
  6129. var lengths = this.getLengths();
  6130. return lengths[ lengths.length - 1 ];
  6131. },
  6132. // Get list of cumulative segment lengths
  6133. getLengths: function ( divisions ) {
  6134. if ( isNaN( divisions ) ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  6135. if ( this.cacheArcLengths
  6136. && ( this.cacheArcLengths.length === divisions + 1 )
  6137. && ! this.needsUpdate ) {
  6138. //console.log( "cached", this.cacheArcLengths );
  6139. return this.cacheArcLengths;
  6140. }
  6141. this.needsUpdate = false;
  6142. var cache = [];
  6143. var current, last = this.getPoint( 0 );
  6144. var p, sum = 0;
  6145. cache.push( 0 );
  6146. for ( p = 1; p <= divisions; p ++ ) {
  6147. current = this.getPoint ( p / divisions );
  6148. sum += current.distanceTo( last );
  6149. cache.push( sum );
  6150. last = current;
  6151. }
  6152. this.cacheArcLengths = cache;
  6153. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  6154. },
  6155. updateArcLengths: function() {
  6156. this.needsUpdate = true;
  6157. this.getLengths();
  6158. },
  6159. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  6160. getUtoTmapping: function ( u, distance ) {
  6161. var arcLengths = this.getLengths();
  6162. var i = 0, il = arcLengths.length;
  6163. var targetArcLength; // The targeted u distance value to get
  6164. if ( distance ) {
  6165. targetArcLength = distance;
  6166. } else {
  6167. targetArcLength = u * arcLengths[ il - 1 ];
  6168. }
  6169. //var time = Date.now();
  6170. // binary search for the index with largest value smaller than target u distance
  6171. var low = 0, high = il - 1, comparison;
  6172. while ( low <= high ) {
  6173. 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
  6174. comparison = arcLengths[ i ] - targetArcLength;
  6175. if ( comparison < 0 ) {
  6176. low = i + 1;
  6177. } else if ( comparison > 0 ) {
  6178. high = i - 1;
  6179. } else {
  6180. high = i;
  6181. break;
  6182. // DONE
  6183. }
  6184. }
  6185. i = high;
  6186. //console.log('b' , i, low, high, Date.now()- time);
  6187. if ( arcLengths[ i ] === targetArcLength ) {
  6188. var t = i / ( il - 1 );
  6189. return t;
  6190. }
  6191. // we could get finer grain at lengths, or use simple interpolation between two points
  6192. var lengthBefore = arcLengths[ i ];
  6193. var lengthAfter = arcLengths[ i + 1 ];
  6194. var segmentLength = lengthAfter - lengthBefore;
  6195. // determine where we are between the 'before' and 'after' points
  6196. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  6197. // add that fractional amount to t
  6198. var t = ( i + segmentFraction ) / ( il - 1 );
  6199. return t;
  6200. },
  6201. // Returns a unit vector tangent at t
  6202. // In case any sub curve does not implement its tangent derivation,
  6203. // 2 points a small delta apart will be used to find its gradient
  6204. // which seems to give a reasonable approximation
  6205. getTangent: function( t ) {
  6206. var delta = 0.0001;
  6207. var t1 = t - delta;
  6208. var t2 = t + delta;
  6209. // Capping in case of danger
  6210. if ( t1 < 0 ) t1 = 0;
  6211. if ( t2 > 1 ) t2 = 1;
  6212. var pt1 = this.getPoint( t1 );
  6213. var pt2 = this.getPoint( t2 );
  6214. var vec = pt2.clone().sub( pt1 );
  6215. return vec.normalize();
  6216. },
  6217. getTangentAt: function ( u ) {
  6218. var t = this.getUtoTmapping( u );
  6219. return this.getTangent( t );
  6220. },
  6221. computeFrenetFrames: function ( segments, closed ) {
  6222. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  6223. var normal = new Vector3();
  6224. var tangents = [];
  6225. var normals = [];
  6226. var binormals = [];
  6227. var vec = new Vector3();
  6228. var mat = new Matrix4();
  6229. var i, u, theta;
  6230. // compute the tangent vectors for each segment on the curve
  6231. for ( i = 0; i <= segments; i ++ ) {
  6232. u = i / segments;
  6233. tangents[ i ] = this.getTangentAt( u );
  6234. tangents[ i ].normalize();
  6235. }
  6236. // select an initial normal vector perpendicular to the first tangent vector,
  6237. // and in the direction of the minimum tangent xyz component
  6238. normals[ 0 ] = new Vector3();
  6239. binormals[ 0 ] = new Vector3();
  6240. var min = Number.MAX_VALUE;
  6241. var tx = Math.abs( tangents[ 0 ].x );
  6242. var ty = Math.abs( tangents[ 0 ].y );
  6243. var tz = Math.abs( tangents[ 0 ].z );
  6244. if ( tx <= min ) {
  6245. min = tx;
  6246. normal.set( 1, 0, 0 );
  6247. }
  6248. if ( ty <= min ) {
  6249. min = ty;
  6250. normal.set( 0, 1, 0 );
  6251. }
  6252. if ( tz <= min ) {
  6253. normal.set( 0, 0, 1 );
  6254. }
  6255. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  6256. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  6257. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  6258. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  6259. for ( i = 1; i <= segments; i ++ ) {
  6260. normals[ i ] = normals[ i - 1 ].clone();
  6261. binormals[ i ] = binormals[ i - 1 ].clone();
  6262. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  6263. if ( vec.length() > Number.EPSILON ) {
  6264. vec.normalize();
  6265. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  6266. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  6267. }
  6268. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  6269. }
  6270. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  6271. if ( closed === true ) {
  6272. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  6273. theta /= segments;
  6274. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  6275. theta = - theta;
  6276. }
  6277. for ( i = 1; i <= segments; i ++ ) {
  6278. // twist a little...
  6279. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  6280. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  6281. }
  6282. }
  6283. return {
  6284. tangents: tangents,
  6285. normals: normals,
  6286. binormals: binormals
  6287. };
  6288. }
  6289. };
  6290. /**
  6291. * @author zz85 https://github.com/zz85
  6292. *
  6293. * Centripetal CatmullRom Curve - which is useful for avoiding
  6294. * cusps and self-intersections in non-uniform catmull rom curves.
  6295. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  6296. *
  6297. * curve.type accepts centripetal(default), chordal and catmullrom
  6298. * curve.tension is used for catmullrom which defaults to 0.5
  6299. */
  6300. /*
  6301. Based on an optimized c++ solution in
  6302. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  6303. - http://ideone.com/NoEbVM
  6304. This CubicPoly class could be used for reusing some variables and calculations,
  6305. but for three.js curve use, it could be possible inlined and flatten into a single function call
  6306. which can be placed in CurveUtils.
  6307. */
  6308. function CubicPoly() {
  6309. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  6310. /*
  6311. * Compute coefficients for a cubic polynomial
  6312. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  6313. * such that
  6314. * p(0) = x0, p(1) = x1
  6315. * and
  6316. * p'(0) = t0, p'(1) = t1.
  6317. */
  6318. function init( x0, x1, t0, t1 ) {
  6319. c0 = x0;
  6320. c1 = t0;
  6321. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  6322. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  6323. }
  6324. return {
  6325. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  6326. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  6327. },
  6328. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  6329. // compute tangents when parameterized in [t1,t2]
  6330. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  6331. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  6332. // rescale tangents for parametrization in [0,1]
  6333. t1 *= dt1;
  6334. t2 *= dt1;
  6335. init( x1, x2, t1, t2 );
  6336. },
  6337. calc: function ( t ) {
  6338. var t2 = t * t;
  6339. var t3 = t2 * t;
  6340. return c0 + c1 * t + c2 * t2 + c3 * t3;
  6341. }
  6342. };
  6343. }
  6344. //
  6345. var tmp = new Vector3();
  6346. var px = new CubicPoly();
  6347. var py = new CubicPoly();
  6348. var pz = new CubicPoly();
  6349. function CatmullRomCurve3( p /* array of Vector3 */ ) {
  6350. this.points = p || [];
  6351. this.closed = false;
  6352. }
  6353. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  6354. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  6355. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  6356. var points = this.points;
  6357. var l = points.length;
  6358. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  6359. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  6360. var intPoint = Math.floor( point );
  6361. var weight = point - intPoint;
  6362. if ( this.closed ) {
  6363. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  6364. } else if ( weight === 0 && intPoint === l - 1 ) {
  6365. intPoint = l - 2;
  6366. weight = 1;
  6367. }
  6368. var p0, p1, p2, p3; // 4 points
  6369. if ( this.closed || intPoint > 0 ) {
  6370. p0 = points[ ( intPoint - 1 ) % l ];
  6371. } else {
  6372. // extrapolate first point
  6373. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  6374. p0 = tmp;
  6375. }
  6376. p1 = points[ intPoint % l ];
  6377. p2 = points[ ( intPoint + 1 ) % l ];
  6378. if ( this.closed || intPoint + 2 < l ) {
  6379. p3 = points[ ( intPoint + 2 ) % l ];
  6380. } else {
  6381. // extrapolate last point
  6382. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  6383. p3 = tmp;
  6384. }
  6385. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  6386. // init Centripetal / Chordal Catmull-Rom
  6387. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  6388. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  6389. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  6390. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  6391. // safety check for repeated points
  6392. if ( dt1 < 1e-4 ) dt1 = 1.0;
  6393. if ( dt0 < 1e-4 ) dt0 = dt1;
  6394. if ( dt2 < 1e-4 ) dt2 = dt1;
  6395. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  6396. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  6397. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  6398. } else if ( this.type === 'catmullrom' ) {
  6399. var tension = this.tension !== undefined ? this.tension : 0.5;
  6400. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  6401. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  6402. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  6403. }
  6404. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  6405. };
  6406. /**
  6407. * @author bhouston / http://clara.io
  6408. */
  6409. function Ray( origin, direction ) {
  6410. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  6411. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  6412. }
  6413. Ray.prototype = {
  6414. constructor: Ray,
  6415. set: function ( origin, direction ) {
  6416. this.origin.copy( origin );
  6417. this.direction.copy( direction );
  6418. return this;
  6419. },
  6420. clone: function () {
  6421. return new this.constructor().copy( this );
  6422. },
  6423. copy: function ( ray ) {
  6424. this.origin.copy( ray.origin );
  6425. this.direction.copy( ray.direction );
  6426. return this;
  6427. },
  6428. at: function ( t, optionalTarget ) {
  6429. var result = optionalTarget || new Vector3();
  6430. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  6431. },
  6432. lookAt: function ( v ) {
  6433. this.direction.copy( v ).sub( this.origin ).normalize();
  6434. return this;
  6435. },
  6436. recast: function () {
  6437. var v1 = new Vector3();
  6438. return function recast( t ) {
  6439. this.origin.copy( this.at( t, v1 ) );
  6440. return this;
  6441. };
  6442. }(),
  6443. closestPointToPoint: function ( point, optionalTarget ) {
  6444. var result = optionalTarget || new Vector3();
  6445. result.subVectors( point, this.origin );
  6446. var directionDistance = result.dot( this.direction );
  6447. if ( directionDistance < 0 ) {
  6448. return result.copy( this.origin );
  6449. }
  6450. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  6451. },
  6452. distanceToPoint: function ( point ) {
  6453. return Math.sqrt( this.distanceSqToPoint( point ) );
  6454. },
  6455. distanceSqToPoint: function () {
  6456. var v1 = new Vector3();
  6457. return function distanceSqToPoint( point ) {
  6458. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  6459. // point behind the ray
  6460. if ( directionDistance < 0 ) {
  6461. return this.origin.distanceToSquared( point );
  6462. }
  6463. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  6464. return v1.distanceToSquared( point );
  6465. };
  6466. }(),
  6467. distanceSqToSegment: function () {
  6468. var segCenter = new Vector3();
  6469. var segDir = new Vector3();
  6470. var diff = new Vector3();
  6471. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  6472. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  6473. // It returns the min distance between the ray and the segment
  6474. // defined by v0 and v1
  6475. // It can also set two optional targets :
  6476. // - The closest point on the ray
  6477. // - The closest point on the segment
  6478. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  6479. segDir.copy( v1 ).sub( v0 ).normalize();
  6480. diff.copy( this.origin ).sub( segCenter );
  6481. var segExtent = v0.distanceTo( v1 ) * 0.5;
  6482. var a01 = - this.direction.dot( segDir );
  6483. var b0 = diff.dot( this.direction );
  6484. var b1 = - diff.dot( segDir );
  6485. var c = diff.lengthSq();
  6486. var det = Math.abs( 1 - a01 * a01 );
  6487. var s0, s1, sqrDist, extDet;
  6488. if ( det > 0 ) {
  6489. // The ray and segment are not parallel.
  6490. s0 = a01 * b1 - b0;
  6491. s1 = a01 * b0 - b1;
  6492. extDet = segExtent * det;
  6493. if ( s0 >= 0 ) {
  6494. if ( s1 >= - extDet ) {
  6495. if ( s1 <= extDet ) {
  6496. // region 0
  6497. // Minimum at interior points of ray and segment.
  6498. var invDet = 1 / det;
  6499. s0 *= invDet;
  6500. s1 *= invDet;
  6501. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  6502. } else {
  6503. // region 1
  6504. s1 = segExtent;
  6505. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6506. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6507. }
  6508. } else {
  6509. // region 5
  6510. s1 = - segExtent;
  6511. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6512. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6513. }
  6514. } else {
  6515. if ( s1 <= - extDet ) {
  6516. // region 4
  6517. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  6518. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6519. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6520. } else if ( s1 <= extDet ) {
  6521. // region 3
  6522. s0 = 0;
  6523. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6524. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  6525. } else {
  6526. // region 2
  6527. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  6528. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6529. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6530. }
  6531. }
  6532. } else {
  6533. // Ray and segment are parallel.
  6534. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  6535. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6536. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6537. }
  6538. if ( optionalPointOnRay ) {
  6539. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  6540. }
  6541. if ( optionalPointOnSegment ) {
  6542. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  6543. }
  6544. return sqrDist;
  6545. };
  6546. }(),
  6547. intersectSphere: function () {
  6548. var v1 = new Vector3();
  6549. return function intersectSphere( sphere, optionalTarget ) {
  6550. v1.subVectors( sphere.center, this.origin );
  6551. var tca = v1.dot( this.direction );
  6552. var d2 = v1.dot( v1 ) - tca * tca;
  6553. var radius2 = sphere.radius * sphere.radius;
  6554. if ( d2 > radius2 ) return null;
  6555. var thc = Math.sqrt( radius2 - d2 );
  6556. // t0 = first intersect point - entrance on front of sphere
  6557. var t0 = tca - thc;
  6558. // t1 = second intersect point - exit point on back of sphere
  6559. var t1 = tca + thc;
  6560. // test to see if both t0 and t1 are behind the ray - if so, return null
  6561. if ( t0 < 0 && t1 < 0 ) return null;
  6562. // test to see if t0 is behind the ray:
  6563. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6564. // in order to always return an intersect point that is in front of the ray.
  6565. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  6566. // else t0 is in front of the ray, so return the first collision point scaled by t0
  6567. return this.at( t0, optionalTarget );
  6568. };
  6569. }(),
  6570. intersectsSphere: function ( sphere ) {
  6571. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  6572. },
  6573. distanceToPlane: function ( plane ) {
  6574. var denominator = plane.normal.dot( this.direction );
  6575. if ( denominator === 0 ) {
  6576. // line is coplanar, return origin
  6577. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  6578. return 0;
  6579. }
  6580. // Null is preferable to undefined since undefined means.... it is undefined
  6581. return null;
  6582. }
  6583. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  6584. // Return if the ray never intersects the plane
  6585. return t >= 0 ? t : null;
  6586. },
  6587. intersectPlane: function ( plane, optionalTarget ) {
  6588. var t = this.distanceToPlane( plane );
  6589. if ( t === null ) {
  6590. return null;
  6591. }
  6592. return this.at( t, optionalTarget );
  6593. },
  6594. intersectsPlane: function ( plane ) {
  6595. // check if the ray lies on the plane first
  6596. var distToPoint = plane.distanceToPoint( this.origin );
  6597. if ( distToPoint === 0 ) {
  6598. return true;
  6599. }
  6600. var denominator = plane.normal.dot( this.direction );
  6601. if ( denominator * distToPoint < 0 ) {
  6602. return true;
  6603. }
  6604. // ray origin is behind the plane (and is pointing behind it)
  6605. return false;
  6606. },
  6607. intersectBox: function ( box, optionalTarget ) {
  6608. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  6609. var invdirx = 1 / this.direction.x,
  6610. invdiry = 1 / this.direction.y,
  6611. invdirz = 1 / this.direction.z;
  6612. var origin = this.origin;
  6613. if ( invdirx >= 0 ) {
  6614. tmin = ( box.min.x - origin.x ) * invdirx;
  6615. tmax = ( box.max.x - origin.x ) * invdirx;
  6616. } else {
  6617. tmin = ( box.max.x - origin.x ) * invdirx;
  6618. tmax = ( box.min.x - origin.x ) * invdirx;
  6619. }
  6620. if ( invdiry >= 0 ) {
  6621. tymin = ( box.min.y - origin.y ) * invdiry;
  6622. tymax = ( box.max.y - origin.y ) * invdiry;
  6623. } else {
  6624. tymin = ( box.max.y - origin.y ) * invdiry;
  6625. tymax = ( box.min.y - origin.y ) * invdiry;
  6626. }
  6627. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  6628. // These lines also handle the case where tmin or tmax is NaN
  6629. // (result of 0 * Infinity). x !== x returns true if x is NaN
  6630. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  6631. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  6632. if ( invdirz >= 0 ) {
  6633. tzmin = ( box.min.z - origin.z ) * invdirz;
  6634. tzmax = ( box.max.z - origin.z ) * invdirz;
  6635. } else {
  6636. tzmin = ( box.max.z - origin.z ) * invdirz;
  6637. tzmax = ( box.min.z - origin.z ) * invdirz;
  6638. }
  6639. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  6640. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  6641. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  6642. //return point closest to the ray (positive side)
  6643. if ( tmax < 0 ) return null;
  6644. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  6645. },
  6646. intersectsBox: ( function () {
  6647. var v = new Vector3();
  6648. return function intersectsBox( box ) {
  6649. return this.intersectBox( box, v ) !== null;
  6650. };
  6651. } )(),
  6652. intersectTriangle: function () {
  6653. // Compute the offset origin, edges, and normal.
  6654. var diff = new Vector3();
  6655. var edge1 = new Vector3();
  6656. var edge2 = new Vector3();
  6657. var normal = new Vector3();
  6658. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  6659. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6660. edge1.subVectors( b, a );
  6661. edge2.subVectors( c, a );
  6662. normal.crossVectors( edge1, edge2 );
  6663. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6664. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6665. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6666. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6667. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6668. var DdN = this.direction.dot( normal );
  6669. var sign;
  6670. if ( DdN > 0 ) {
  6671. if ( backfaceCulling ) return null;
  6672. sign = 1;
  6673. } else if ( DdN < 0 ) {
  6674. sign = - 1;
  6675. DdN = - DdN;
  6676. } else {
  6677. return null;
  6678. }
  6679. diff.subVectors( this.origin, a );
  6680. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  6681. // b1 < 0, no intersection
  6682. if ( DdQxE2 < 0 ) {
  6683. return null;
  6684. }
  6685. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  6686. // b2 < 0, no intersection
  6687. if ( DdE1xQ < 0 ) {
  6688. return null;
  6689. }
  6690. // b1+b2 > 1, no intersection
  6691. if ( DdQxE2 + DdE1xQ > DdN ) {
  6692. return null;
  6693. }
  6694. // Line intersects triangle, check if ray does.
  6695. var QdN = - sign * diff.dot( normal );
  6696. // t < 0, no intersection
  6697. if ( QdN < 0 ) {
  6698. return null;
  6699. }
  6700. // Ray intersects triangle.
  6701. return this.at( QdN / DdN, optionalTarget );
  6702. };
  6703. }(),
  6704. applyMatrix4: function ( matrix4 ) {
  6705. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  6706. this.origin.applyMatrix4( matrix4 );
  6707. this.direction.sub( this.origin );
  6708. this.direction.normalize();
  6709. return this;
  6710. },
  6711. equals: function ( ray ) {
  6712. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  6713. }
  6714. };
  6715. /**
  6716. * @author mrdoob / http://mrdoob.com/
  6717. * @author alteredq / http://alteredqualia.com/
  6718. */
  6719. var materialId = 0;
  6720. function Material() {
  6721. Object.defineProperty( this, 'id', { value: materialId ++ } );
  6722. this.uuid = _Math.generateUUID();
  6723. this.name = '';
  6724. this.type = 'Material';
  6725. this.fog = true;
  6726. this.lights = true;
  6727. this.blending = NormalBlending;
  6728. this.side = FrontSide;
  6729. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  6730. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  6731. this.opacity = 1;
  6732. this.transparent = false;
  6733. this.blendSrc = SrcAlphaFactor;
  6734. this.blendDst = OneMinusSrcAlphaFactor;
  6735. this.blendEquation = AddEquation;
  6736. this.blendSrcAlpha = null;
  6737. this.blendDstAlpha = null;
  6738. this.blendEquationAlpha = null;
  6739. this.depthFunc = LessEqualDepth;
  6740. this.depthTest = true;
  6741. this.depthWrite = true;
  6742. this.clippingPlanes = null;
  6743. this.clipIntersection = false;
  6744. this.clipShadows = false;
  6745. this.colorWrite = true;
  6746. this.precision = null; // override the renderer's default precision for this material
  6747. this.polygonOffset = false;
  6748. this.polygonOffsetFactor = 0;
  6749. this.polygonOffsetUnits = 0;
  6750. this.alphaTest = 0;
  6751. this.premultipliedAlpha = false;
  6752. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  6753. this.visible = true;
  6754. this._needsUpdate = true;
  6755. }
  6756. Material.prototype = {
  6757. constructor: Material,
  6758. isMaterial: true,
  6759. get needsUpdate() {
  6760. return this._needsUpdate;
  6761. },
  6762. set needsUpdate( value ) {
  6763. if ( value === true ) this.update();
  6764. this._needsUpdate = value;
  6765. },
  6766. setValues: function ( values ) {
  6767. if ( values === undefined ) return;
  6768. for ( var key in values ) {
  6769. var newValue = values[ key ];
  6770. if ( newValue === undefined ) {
  6771. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  6772. continue;
  6773. }
  6774. var currentValue = this[ key ];
  6775. if ( currentValue === undefined ) {
  6776. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  6777. continue;
  6778. }
  6779. if ( currentValue && currentValue.isColor ) {
  6780. currentValue.set( newValue );
  6781. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  6782. currentValue.copy( newValue );
  6783. } else if ( key === 'overdraw' ) {
  6784. // ensure overdraw is backwards-compatible with legacy boolean type
  6785. this[ key ] = Number( newValue );
  6786. } else {
  6787. this[ key ] = newValue;
  6788. }
  6789. }
  6790. },
  6791. toJSON: function ( meta ) {
  6792. var isRoot = meta === undefined;
  6793. if ( isRoot ) {
  6794. meta = {
  6795. textures: {},
  6796. images: {}
  6797. };
  6798. }
  6799. var data = {
  6800. metadata: {
  6801. version: 4.4,
  6802. type: 'Material',
  6803. generator: 'Material.toJSON'
  6804. }
  6805. };
  6806. // standard Material serialization
  6807. data.uuid = this.uuid;
  6808. data.type = this.type;
  6809. if ( this.name !== '' ) data.name = this.name;
  6810. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  6811. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  6812. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  6813. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  6814. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  6815. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  6816. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  6817. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  6818. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  6819. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  6820. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  6821. if ( this.bumpMap && this.bumpMap.isTexture ) {
  6822. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  6823. data.bumpScale = this.bumpScale;
  6824. }
  6825. if ( this.normalMap && this.normalMap.isTexture ) {
  6826. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  6827. data.normalScale = this.normalScale.toArray();
  6828. }
  6829. if ( this.displacementMap && this.displacementMap.isTexture ) {
  6830. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  6831. data.displacementScale = this.displacementScale;
  6832. data.displacementBias = this.displacementBias;
  6833. }
  6834. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  6835. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  6836. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  6837. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  6838. if ( this.envMap && this.envMap.isTexture ) {
  6839. data.envMap = this.envMap.toJSON( meta ).uuid;
  6840. data.reflectivity = this.reflectivity; // Scale behind envMap
  6841. }
  6842. if ( this.gradientMap && this.gradientMap.isTexture ) {
  6843. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  6844. }
  6845. if ( this.size !== undefined ) data.size = this.size;
  6846. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  6847. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  6848. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  6849. if ( this.side !== FrontSide ) data.side = this.side;
  6850. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  6851. if ( this.opacity < 1 ) data.opacity = this.opacity;
  6852. if ( this.transparent === true ) data.transparent = this.transparent;
  6853. data.depthFunc = this.depthFunc;
  6854. data.depthTest = this.depthTest;
  6855. data.depthWrite = this.depthWrite;
  6856. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  6857. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  6858. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  6859. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  6860. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  6861. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  6862. data.skinning = this.skinning;
  6863. data.morphTargets = this.morphTargets;
  6864. // TODO: Copied from Object3D.toJSON
  6865. function extractFromCache( cache ) {
  6866. var values = [];
  6867. for ( var key in cache ) {
  6868. var data = cache[ key ];
  6869. delete data.metadata;
  6870. values.push( data );
  6871. }
  6872. return values;
  6873. }
  6874. if ( isRoot ) {
  6875. var textures = extractFromCache( meta.textures );
  6876. var images = extractFromCache( meta.images );
  6877. if ( textures.length > 0 ) data.textures = textures;
  6878. if ( images.length > 0 ) data.images = images;
  6879. }
  6880. return data;
  6881. },
  6882. clone: function () {
  6883. return new this.constructor().copy( this );
  6884. },
  6885. copy: function ( source ) {
  6886. this.name = source.name;
  6887. this.fog = source.fog;
  6888. this.lights = source.lights;
  6889. this.blending = source.blending;
  6890. this.side = source.side;
  6891. this.shading = source.shading;
  6892. this.vertexColors = source.vertexColors;
  6893. this.opacity = source.opacity;
  6894. this.transparent = source.transparent;
  6895. this.blendSrc = source.blendSrc;
  6896. this.blendDst = source.blendDst;
  6897. this.blendEquation = source.blendEquation;
  6898. this.blendSrcAlpha = source.blendSrcAlpha;
  6899. this.blendDstAlpha = source.blendDstAlpha;
  6900. this.blendEquationAlpha = source.blendEquationAlpha;
  6901. this.depthFunc = source.depthFunc;
  6902. this.depthTest = source.depthTest;
  6903. this.depthWrite = source.depthWrite;
  6904. this.colorWrite = source.colorWrite;
  6905. this.precision = source.precision;
  6906. this.polygonOffset = source.polygonOffset;
  6907. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6908. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6909. this.alphaTest = source.alphaTest;
  6910. this.premultipliedAlpha = source.premultipliedAlpha;
  6911. this.overdraw = source.overdraw;
  6912. this.visible = source.visible;
  6913. this.clipShadows = source.clipShadows;
  6914. this.clipIntersection = source.clipIntersection;
  6915. var srcPlanes = source.clippingPlanes,
  6916. dstPlanes = null;
  6917. if ( srcPlanes !== null ) {
  6918. var n = srcPlanes.length;
  6919. dstPlanes = new Array( n );
  6920. for ( var i = 0; i !== n; ++ i )
  6921. dstPlanes[ i ] = srcPlanes[ i ].clone();
  6922. }
  6923. this.clippingPlanes = dstPlanes;
  6924. return this;
  6925. },
  6926. update: function () {
  6927. this.dispatchEvent( { type: 'update' } );
  6928. },
  6929. dispose: function () {
  6930. this.dispatchEvent( { type: 'dispose' } );
  6931. }
  6932. };
  6933. Object.assign( Material.prototype, EventDispatcher.prototype );
  6934. /**
  6935. * @author mrdoob / http://mrdoob.com/
  6936. * @author alteredq / http://alteredqualia.com/
  6937. *
  6938. * parameters = {
  6939. * color: <hex>,
  6940. * opacity: <float>,
  6941. *
  6942. * linewidth: <float>,
  6943. * linecap: "round",
  6944. * linejoin: "round"
  6945. * }
  6946. */
  6947. function LineBasicMaterial( parameters ) {
  6948. Material.call( this );
  6949. this.type = 'LineBasicMaterial';
  6950. this.color = new Color( 0xffffff );
  6951. this.linewidth = 1;
  6952. this.linecap = 'round';
  6953. this.linejoin = 'round';
  6954. this.lights = false;
  6955. this.setValues( parameters );
  6956. }
  6957. LineBasicMaterial.prototype = Object.create( Material.prototype );
  6958. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  6959. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  6960. LineBasicMaterial.prototype.copy = function ( source ) {
  6961. Material.prototype.copy.call( this, source );
  6962. this.color.copy( source.color );
  6963. this.linewidth = source.linewidth;
  6964. this.linecap = source.linecap;
  6965. this.linejoin = source.linejoin;
  6966. return this;
  6967. };
  6968. /**
  6969. * @author mrdoob / http://mrdoob.com/
  6970. */
  6971. function Line( geometry, material, mode ) {
  6972. if ( mode === 1 ) {
  6973. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  6974. return new LineSegments( geometry, material );
  6975. }
  6976. Object3D.call( this );
  6977. this.type = 'Line';
  6978. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  6979. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6980. }
  6981. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  6982. constructor: Line,
  6983. isLine: true,
  6984. raycast: ( function () {
  6985. var inverseMatrix = new Matrix4();
  6986. var ray = new Ray();
  6987. var sphere = new Sphere();
  6988. return function raycast( raycaster, intersects ) {
  6989. var precision = raycaster.linePrecision;
  6990. var precisionSq = precision * precision;
  6991. var geometry = this.geometry;
  6992. var matrixWorld = this.matrixWorld;
  6993. // Checking boundingSphere distance to ray
  6994. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6995. sphere.copy( geometry.boundingSphere );
  6996. sphere.applyMatrix4( matrixWorld );
  6997. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  6998. //
  6999. inverseMatrix.getInverse( matrixWorld );
  7000. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  7001. var vStart = new Vector3();
  7002. var vEnd = new Vector3();
  7003. var interSegment = new Vector3();
  7004. var interRay = new Vector3();
  7005. var step = (this && this.isLineSegments) ? 2 : 1;
  7006. if ( geometry.isBufferGeometry ) {
  7007. var index = geometry.index;
  7008. var attributes = geometry.attributes;
  7009. var positions = attributes.position.array;
  7010. if ( index !== null ) {
  7011. var indices = index.array;
  7012. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  7013. var a = indices[ i ];
  7014. var b = indices[ i + 1 ];
  7015. vStart.fromArray( positions, a * 3 );
  7016. vEnd.fromArray( positions, b * 3 );
  7017. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  7018. if ( distSq > precisionSq ) continue;
  7019. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  7020. var distance = raycaster.ray.origin.distanceTo( interRay );
  7021. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  7022. intersects.push( {
  7023. distance: distance,
  7024. // What do we want? intersection point on the ray or on the segment??
  7025. // point: raycaster.ray.at( distance ),
  7026. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  7027. index: i,
  7028. face: null,
  7029. faceIndex: null,
  7030. object: this
  7031. } );
  7032. }
  7033. } else {
  7034. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  7035. vStart.fromArray( positions, 3 * i );
  7036. vEnd.fromArray( positions, 3 * i + 3 );
  7037. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  7038. if ( distSq > precisionSq ) continue;
  7039. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  7040. var distance = raycaster.ray.origin.distanceTo( interRay );
  7041. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  7042. intersects.push( {
  7043. distance: distance,
  7044. // What do we want? intersection point on the ray or on the segment??
  7045. // point: raycaster.ray.at( distance ),
  7046. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  7047. index: i,
  7048. face: null,
  7049. faceIndex: null,
  7050. object: this
  7051. } );
  7052. }
  7053. }
  7054. } else if ( geometry.isGeometry ) {
  7055. var vertices = geometry.vertices;
  7056. var nbVertices = vertices.length;
  7057. for ( var i = 0; i < nbVertices - 1; i += step ) {
  7058. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  7059. if ( distSq > precisionSq ) continue;
  7060. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  7061. var distance = raycaster.ray.origin.distanceTo( interRay );
  7062. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  7063. intersects.push( {
  7064. distance: distance,
  7065. // What do we want? intersection point on the ray or on the segment??
  7066. // point: raycaster.ray.at( distance ),
  7067. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  7068. index: i,
  7069. face: null,
  7070. faceIndex: null,
  7071. object: this
  7072. } );
  7073. }
  7074. }
  7075. };
  7076. }() ),
  7077. clone: function () {
  7078. return new this.constructor( this.geometry, this.material ).copy( this );
  7079. }
  7080. } );
  7081. /**
  7082. * @author mrdoob / http://mrdoob.com/
  7083. */
  7084. function LineSegments( geometry, material ) {
  7085. Line.call( this, geometry, material );
  7086. this.type = 'LineSegments';
  7087. }
  7088. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  7089. constructor: LineSegments,
  7090. isLineSegments: true
  7091. } );
  7092. /**
  7093. * @author mrdoob / http://mrdoob.com/
  7094. */
  7095. function BoxHelper( object, color ) {
  7096. if ( color === undefined ) color = 0xffff00;
  7097. var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  7098. var positions = new Float32Array( 8 * 3 );
  7099. var geometry = new BufferGeometry();
  7100. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  7101. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  7102. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  7103. if ( object !== undefined ) {
  7104. this.update( object );
  7105. }
  7106. }
  7107. BoxHelper.prototype = Object.create( LineSegments.prototype );
  7108. BoxHelper.prototype.constructor = BoxHelper;
  7109. BoxHelper.prototype.update = ( function () {
  7110. var box = new Box3();
  7111. return function update( object ) {
  7112. if ( object && object.isBox3 ) {
  7113. box.copy( object );
  7114. } else {
  7115. box.setFromObject( object );
  7116. }
  7117. if ( box.isEmpty() ) return;
  7118. var min = box.min;
  7119. var max = box.max;
  7120. /*
  7121. 5____4
  7122. 1/___0/|
  7123. | 6__|_7
  7124. 2/___3/
  7125. 0: max.x, max.y, max.z
  7126. 1: min.x, max.y, max.z
  7127. 2: min.x, min.y, max.z
  7128. 3: max.x, min.y, max.z
  7129. 4: max.x, max.y, min.z
  7130. 5: min.x, max.y, min.z
  7131. 6: min.x, min.y, min.z
  7132. 7: max.x, min.y, min.z
  7133. */
  7134. var position = this.geometry.attributes.position;
  7135. var array = position.array;
  7136. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  7137. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  7138. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  7139. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  7140. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  7141. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  7142. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  7143. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  7144. position.needsUpdate = true;
  7145. this.geometry.computeBoundingSphere();
  7146. };
  7147. } )();
  7148. /**
  7149. * @author mrdoob / http://mrdoob.com/
  7150. */
  7151. function GridHelper( size, divisions, color1, color2 ) {
  7152. size = size || 10;
  7153. divisions = divisions || 10;
  7154. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  7155. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  7156. var center = divisions / 2;
  7157. var step = size / divisions;
  7158. var halfSize = size / 2;
  7159. var vertices = [], colors = [];
  7160. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  7161. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  7162. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  7163. var color = i === center ? color1 : color2;
  7164. color.toArray( colors, j ); j += 3;
  7165. color.toArray( colors, j ); j += 3;
  7166. color.toArray( colors, j ); j += 3;
  7167. color.toArray( colors, j ); j += 3;
  7168. }
  7169. var geometry = new BufferGeometry();
  7170. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7171. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  7172. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  7173. LineSegments.call( this, geometry, material );
  7174. }
  7175. GridHelper.prototype = Object.create( LineSegments.prototype );
  7176. GridHelper.prototype.constructor = GridHelper;
  7177. /**
  7178. * @author mrdoob / http://mrdoob.com/
  7179. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  7180. */
  7181. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  7182. Geometry.call( this );
  7183. this.type = 'BoxGeometry';
  7184. this.parameters = {
  7185. width: width,
  7186. height: height,
  7187. depth: depth,
  7188. widthSegments: widthSegments,
  7189. heightSegments: heightSegments,
  7190. depthSegments: depthSegments
  7191. };
  7192. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  7193. this.mergeVertices();
  7194. }
  7195. BoxGeometry.prototype = Object.create( Geometry.prototype );
  7196. BoxGeometry.prototype.constructor = BoxGeometry;
  7197. /**
  7198. * @author Mugen87 / https://github.com/Mugen87
  7199. */
  7200. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  7201. BufferGeometry.call( this );
  7202. this.type = 'BoxBufferGeometry';
  7203. this.parameters = {
  7204. width: width,
  7205. height: height,
  7206. depth: depth,
  7207. widthSegments: widthSegments,
  7208. heightSegments: heightSegments,
  7209. depthSegments: depthSegments
  7210. };
  7211. var scope = this;
  7212. // segments
  7213. widthSegments = Math.floor( widthSegments ) || 1;
  7214. heightSegments = Math.floor( heightSegments ) || 1;
  7215. depthSegments = Math.floor( depthSegments ) || 1;
  7216. // buffers
  7217. var indices = [];
  7218. var vertices = [];
  7219. var normals = [];
  7220. var uvs = [];
  7221. // helper variables
  7222. var numberOfVertices = 0;
  7223. var groupStart = 0;
  7224. // build each side of the box geometry
  7225. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7226. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7227. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7228. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7229. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7230. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7231. // build geometry
  7232. this.setIndex( indices );
  7233. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7234. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7235. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7236. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7237. var segmentWidth = width / gridX;
  7238. var segmentHeight = height / gridY;
  7239. var widthHalf = width / 2;
  7240. var heightHalf = height / 2;
  7241. var depthHalf = depth / 2;
  7242. var gridX1 = gridX + 1;
  7243. var gridY1 = gridY + 1;
  7244. var vertexCounter = 0;
  7245. var groupCount = 0;
  7246. var ix, iy;
  7247. var vector = new Vector3();
  7248. // generate vertices, normals and uvs
  7249. for ( iy = 0; iy < gridY1; iy ++ ) {
  7250. var y = iy * segmentHeight - heightHalf;
  7251. for ( ix = 0; ix < gridX1; ix ++ ) {
  7252. var x = ix * segmentWidth - widthHalf;
  7253. // set values to correct vector component
  7254. vector[ u ] = x * udir;
  7255. vector[ v ] = y * vdir;
  7256. vector[ w ] = depthHalf;
  7257. // now apply vector to vertex buffer
  7258. vertices.push( vector.x, vector.y, vector.z );
  7259. // set values to correct vector component
  7260. vector[ u ] = 0;
  7261. vector[ v ] = 0;
  7262. vector[ w ] = depth > 0 ? 1 : - 1;
  7263. // now apply vector to normal buffer
  7264. normals.push( vector.x, vector.y, vector.z );
  7265. // uvs
  7266. uvs.push( ix / gridX );
  7267. uvs.push( 1 - ( iy / gridY ) );
  7268. // counters
  7269. vertexCounter += 1;
  7270. }
  7271. }
  7272. // indices
  7273. // 1. you need three indices to draw a single face
  7274. // 2. a single segment consists of two faces
  7275. // 3. so we need to generate six (2*3) indices per segment
  7276. for ( iy = 0; iy < gridY; iy ++ ) {
  7277. for ( ix = 0; ix < gridX; ix ++ ) {
  7278. var a = numberOfVertices + ix + gridX1 * iy;
  7279. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7280. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7281. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7282. // faces
  7283. indices.push( a, b, d );
  7284. indices.push( b, c, d );
  7285. // increase counter
  7286. groupCount += 6;
  7287. }
  7288. }
  7289. // add a group to the geometry. this will ensure multi material support
  7290. scope.addGroup( groupStart, groupCount, materialIndex );
  7291. // calculate new start value for groups
  7292. groupStart += groupCount;
  7293. // update total number of vertices
  7294. numberOfVertices += vertexCounter;
  7295. }
  7296. }
  7297. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  7298. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  7299. /**
  7300. * @author WestLangley / http://github.com/WestLangley
  7301. * @author Mugen87 / https://github.com/Mugen87
  7302. */
  7303. function EdgesGeometry( geometry, thresholdAngle ) {
  7304. BufferGeometry.call( this );
  7305. this.type = 'EdgesGeometry';
  7306. this.parameters = {
  7307. thresholdAngle: thresholdAngle
  7308. };
  7309. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  7310. // buffer
  7311. var vertices = [];
  7312. // helper variables
  7313. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  7314. var edge = [ 0, 0 ], edges = {};
  7315. var key, keys = [ 'a', 'b', 'c' ];
  7316. // prepare source geometry
  7317. var geometry2;
  7318. if ( geometry.isBufferGeometry ) {
  7319. geometry2 = new Geometry();
  7320. geometry2.fromBufferGeometry( geometry );
  7321. } else {
  7322. geometry2 = geometry.clone();
  7323. }
  7324. geometry2.mergeVertices();
  7325. geometry2.computeFaceNormals();
  7326. var sourceVertices = geometry2.vertices;
  7327. var faces = geometry2.faces;
  7328. // now create a data structure where each entry represents an edge with its adjoining faces
  7329. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  7330. var face = faces[ i ];
  7331. for ( var j = 0; j < 3; j ++ ) {
  7332. edge[ 0 ] = face[ keys[ j ] ];
  7333. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  7334. edge.sort( sortFunction );
  7335. key = edge.toString();
  7336. if ( edges[ key ] === undefined ) {
  7337. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  7338. } else {
  7339. edges[ key ].face2 = i;
  7340. }
  7341. }
  7342. }
  7343. // generate vertices
  7344. for ( key in edges ) {
  7345. var e = edges[ key ];
  7346. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  7347. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  7348. var vertex = sourceVertices[ e.index1 ];
  7349. vertices.push( vertex.x, vertex.y, vertex.z );
  7350. vertex = sourceVertices[ e.index2 ];
  7351. vertices.push( vertex.x, vertex.y, vertex.z );
  7352. }
  7353. }
  7354. // build geometry
  7355. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7356. // custom array sort function
  7357. function sortFunction( a, b ) {
  7358. return a - b;
  7359. }
  7360. }
  7361. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  7362. EdgesGeometry.prototype.constructor = EdgesGeometry;
  7363. /**
  7364. * @author zz85 / http://www.lab4games.net/zz85/blog
  7365. */
  7366. var ShapeUtils = {
  7367. // calculate area of the contour polygon
  7368. area: function ( contour ) {
  7369. var n = contour.length;
  7370. var a = 0.0;
  7371. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  7372. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  7373. }
  7374. return a * 0.5;
  7375. },
  7376. triangulate: ( function () {
  7377. /**
  7378. * This code is a quick port of code written in C++ which was submitted to
  7379. * flipcode.com by John W. Ratcliff // July 22, 2000
  7380. * See original code and more information here:
  7381. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  7382. *
  7383. * ported to actionscript by Zevan Rosser
  7384. * www.actionsnippet.com
  7385. *
  7386. * ported to javascript by Joshua Koo
  7387. * http://www.lab4games.net/zz85/blog
  7388. *
  7389. */
  7390. function snip( contour, u, v, w, n, verts ) {
  7391. var p;
  7392. var ax, ay, bx, by;
  7393. var cx, cy, px, py;
  7394. ax = contour[ verts[ u ] ].x;
  7395. ay = contour[ verts[ u ] ].y;
  7396. bx = contour[ verts[ v ] ].x;
  7397. by = contour[ verts[ v ] ].y;
  7398. cx = contour[ verts[ w ] ].x;
  7399. cy = contour[ verts[ w ] ].y;
  7400. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  7401. var aX, aY, bX, bY, cX, cY;
  7402. var apx, apy, bpx, bpy, cpx, cpy;
  7403. var cCROSSap, bCROSScp, aCROSSbp;
  7404. aX = cx - bx; aY = cy - by;
  7405. bX = ax - cx; bY = ay - cy;
  7406. cX = bx - ax; cY = by - ay;
  7407. for ( p = 0; p < n; p ++ ) {
  7408. px = contour[ verts[ p ] ].x;
  7409. py = contour[ verts[ p ] ].y;
  7410. if ( ( ( px === ax ) && ( py === ay ) ) ||
  7411. ( ( px === bx ) && ( py === by ) ) ||
  7412. ( ( px === cx ) && ( py === cy ) ) ) continue;
  7413. apx = px - ax; apy = py - ay;
  7414. bpx = px - bx; bpy = py - by;
  7415. cpx = px - cx; cpy = py - cy;
  7416. // see if p is inside triangle abc
  7417. aCROSSbp = aX * bpy - aY * bpx;
  7418. cCROSSap = cX * apy - cY * apx;
  7419. bCROSScp = bX * cpy - bY * cpx;
  7420. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  7421. }
  7422. return true;
  7423. }
  7424. // takes in an contour array and returns
  7425. return function triangulate( contour, indices ) {
  7426. var n = contour.length;
  7427. if ( n < 3 ) return null;
  7428. var result = [],
  7429. verts = [],
  7430. vertIndices = [];
  7431. /* we want a counter-clockwise polygon in verts */
  7432. var u, v, w;
  7433. if ( ShapeUtils.area( contour ) > 0.0 ) {
  7434. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  7435. } else {
  7436. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  7437. }
  7438. var nv = n;
  7439. /* remove nv - 2 vertices, creating 1 triangle every time */
  7440. var count = 2 * nv; /* error detection */
  7441. for ( v = nv - 1; nv > 2; ) {
  7442. /* if we loop, it is probably a non-simple polygon */
  7443. if ( ( count -- ) <= 0 ) {
  7444. //** Triangulate: ERROR - probable bad polygon!
  7445. //throw ( "Warning, unable to triangulate polygon!" );
  7446. //return null;
  7447. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  7448. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  7449. if ( indices ) return vertIndices;
  7450. return result;
  7451. }
  7452. /* three consecutive vertices in current polygon, <u,v,w> */
  7453. u = v; if ( nv <= u ) u = 0; /* previous */
  7454. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  7455. w = v + 1; if ( nv <= w ) w = 0; /* next */
  7456. if ( snip( contour, u, v, w, nv, verts ) ) {
  7457. var a, b, c, s, t;
  7458. /* true names of the vertices */
  7459. a = verts[ u ];
  7460. b = verts[ v ];
  7461. c = verts[ w ];
  7462. /* output Triangle */
  7463. result.push( [ contour[ a ],
  7464. contour[ b ],
  7465. contour[ c ] ] );
  7466. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  7467. /* remove v from the remaining polygon */
  7468. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  7469. verts[ s ] = verts[ t ];
  7470. }
  7471. nv --;
  7472. /* reset error detection counter */
  7473. count = 2 * nv;
  7474. }
  7475. }
  7476. if ( indices ) return vertIndices;
  7477. return result;
  7478. }
  7479. } )(),
  7480. triangulateShape: function ( contour, holes ) {
  7481. function removeDupEndPts(points) {
  7482. var l = points.length;
  7483. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  7484. points.pop();
  7485. }
  7486. }
  7487. removeDupEndPts( contour );
  7488. holes.forEach( removeDupEndPts );
  7489. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  7490. // inOtherPt needs to be collinear to the inSegment
  7491. if ( inSegPt1.x !== inSegPt2.x ) {
  7492. if ( inSegPt1.x < inSegPt2.x ) {
  7493. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  7494. } else {
  7495. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  7496. }
  7497. } else {
  7498. if ( inSegPt1.y < inSegPt2.y ) {
  7499. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  7500. } else {
  7501. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  7502. }
  7503. }
  7504. }
  7505. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  7506. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  7507. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  7508. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  7509. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  7510. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  7511. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  7512. if ( Math.abs( limit ) > Number.EPSILON ) {
  7513. // not parallel
  7514. var perpSeg2;
  7515. if ( limit > 0 ) {
  7516. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  7517. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  7518. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  7519. } else {
  7520. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  7521. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  7522. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  7523. }
  7524. // i.e. to reduce rounding errors
  7525. // intersection at endpoint of segment#1?
  7526. if ( perpSeg2 === 0 ) {
  7527. if ( ( inExcludeAdjacentSegs ) &&
  7528. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  7529. return [ inSeg1Pt1 ];
  7530. }
  7531. if ( perpSeg2 === limit ) {
  7532. if ( ( inExcludeAdjacentSegs ) &&
  7533. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  7534. return [ inSeg1Pt2 ];
  7535. }
  7536. // intersection at endpoint of segment#2?
  7537. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  7538. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  7539. // return real intersection point
  7540. var factorSeg1 = perpSeg2 / limit;
  7541. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  7542. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  7543. } else {
  7544. // parallel or collinear
  7545. if ( ( perpSeg1 !== 0 ) ||
  7546. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  7547. // they are collinear or degenerate
  7548. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  7549. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  7550. // both segments are points
  7551. if ( seg1Pt && seg2Pt ) {
  7552. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  7553. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  7554. return [ inSeg1Pt1 ]; // they are the same point
  7555. }
  7556. // segment#1 is a single point
  7557. if ( seg1Pt ) {
  7558. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  7559. return [ inSeg1Pt1 ];
  7560. }
  7561. // segment#2 is a single point
  7562. if ( seg2Pt ) {
  7563. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  7564. return [ inSeg2Pt1 ];
  7565. }
  7566. // they are collinear segments, which might overlap
  7567. var seg1min, seg1max, seg1minVal, seg1maxVal;
  7568. var seg2min, seg2max, seg2minVal, seg2maxVal;
  7569. if ( seg1dx !== 0 ) {
  7570. // the segments are NOT on a vertical line
  7571. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  7572. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  7573. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  7574. } else {
  7575. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  7576. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  7577. }
  7578. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  7579. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  7580. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  7581. } else {
  7582. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  7583. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  7584. }
  7585. } else {
  7586. // the segments are on a vertical line
  7587. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  7588. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  7589. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  7590. } else {
  7591. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  7592. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  7593. }
  7594. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  7595. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  7596. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  7597. } else {
  7598. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  7599. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  7600. }
  7601. }
  7602. if ( seg1minVal <= seg2minVal ) {
  7603. if ( seg1maxVal < seg2minVal ) return [];
  7604. if ( seg1maxVal === seg2minVal ) {
  7605. if ( inExcludeAdjacentSegs ) return [];
  7606. return [ seg2min ];
  7607. }
  7608. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  7609. return [ seg2min, seg2max ];
  7610. } else {
  7611. if ( seg1minVal > seg2maxVal ) return [];
  7612. if ( seg1minVal === seg2maxVal ) {
  7613. if ( inExcludeAdjacentSegs ) return [];
  7614. return [ seg1min ];
  7615. }
  7616. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  7617. return [ seg1min, seg2max ];
  7618. }
  7619. }
  7620. }
  7621. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  7622. // The order of legs is important
  7623. // translation of all points, so that Vertex is at (0,0)
  7624. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  7625. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  7626. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  7627. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  7628. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  7629. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  7630. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  7631. // angle != 180 deg.
  7632. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  7633. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  7634. if ( from2toAngle > 0 ) {
  7635. // main angle < 180 deg.
  7636. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  7637. } else {
  7638. // main angle > 180 deg.
  7639. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  7640. }
  7641. } else {
  7642. // angle == 180 deg.
  7643. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  7644. return ( from2otherAngle > 0 );
  7645. }
  7646. }
  7647. function removeHoles( contour, holes ) {
  7648. var shape = contour.concat(); // work on this shape
  7649. var hole;
  7650. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  7651. // Check if hole point lies within angle around shape point
  7652. var lastShapeIdx = shape.length - 1;
  7653. var prevShapeIdx = inShapeIdx - 1;
  7654. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  7655. var nextShapeIdx = inShapeIdx + 1;
  7656. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  7657. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  7658. if ( ! insideAngle ) {
  7659. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  7660. return false;
  7661. }
  7662. // Check if shape point lies within angle around hole point
  7663. var lastHoleIdx = hole.length - 1;
  7664. var prevHoleIdx = inHoleIdx - 1;
  7665. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  7666. var nextHoleIdx = inHoleIdx + 1;
  7667. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  7668. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  7669. if ( ! insideAngle ) {
  7670. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  7671. return false;
  7672. }
  7673. return true;
  7674. }
  7675. function intersectsShapeEdge( inShapePt, inHolePt ) {
  7676. // checks for intersections with shape edges
  7677. var sIdx, nextIdx, intersection;
  7678. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  7679. nextIdx = sIdx + 1; nextIdx %= shape.length;
  7680. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  7681. if ( intersection.length > 0 ) return true;
  7682. }
  7683. return false;
  7684. }
  7685. var indepHoles = [];
  7686. function intersectsHoleEdge( inShapePt, inHolePt ) {
  7687. // checks for intersections with hole edges
  7688. var ihIdx, chkHole,
  7689. hIdx, nextIdx, intersection;
  7690. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  7691. chkHole = holes[ indepHoles[ ihIdx ]];
  7692. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  7693. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  7694. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  7695. if ( intersection.length > 0 ) return true;
  7696. }
  7697. }
  7698. return false;
  7699. }
  7700. var holeIndex, shapeIndex,
  7701. shapePt, holePt,
  7702. holeIdx, cutKey, failedCuts = [],
  7703. tmpShape1, tmpShape2,
  7704. tmpHole1, tmpHole2;
  7705. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  7706. indepHoles.push( h );
  7707. }
  7708. var minShapeIndex = 0;
  7709. var counter = indepHoles.length * 2;
  7710. while ( indepHoles.length > 0 ) {
  7711. counter --;
  7712. if ( counter < 0 ) {
  7713. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  7714. break;
  7715. }
  7716. // search for shape-vertex and hole-vertex,
  7717. // which can be connected without intersections
  7718. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  7719. shapePt = shape[ shapeIndex ];
  7720. holeIndex = - 1;
  7721. // search for hole which can be reached without intersections
  7722. for ( var h = 0; h < indepHoles.length; h ++ ) {
  7723. holeIdx = indepHoles[ h ];
  7724. // prevent multiple checks
  7725. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  7726. if ( failedCuts[ cutKey ] !== undefined ) continue;
  7727. hole = holes[ holeIdx ];
  7728. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  7729. holePt = hole[ h2 ];
  7730. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  7731. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  7732. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  7733. holeIndex = h2;
  7734. indepHoles.splice( h, 1 );
  7735. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  7736. tmpShape2 = shape.slice( shapeIndex );
  7737. tmpHole1 = hole.slice( holeIndex );
  7738. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  7739. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  7740. minShapeIndex = shapeIndex;
  7741. // Debug only, to show the selected cuts
  7742. // glob_CutLines.push( [ shapePt, holePt ] );
  7743. break;
  7744. }
  7745. if ( holeIndex >= 0 ) break; // hole-vertex found
  7746. failedCuts[ cutKey ] = true; // remember failure
  7747. }
  7748. if ( holeIndex >= 0 ) break; // hole-vertex found
  7749. }
  7750. }
  7751. return shape; /* shape with no holes */
  7752. }
  7753. var i, il, f, face,
  7754. key, index,
  7755. allPointsMap = {};
  7756. // 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.
  7757. var allpoints = contour.concat();
  7758. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  7759. Array.prototype.push.apply( allpoints, holes[ h ] );
  7760. }
  7761. //console.log( "allpoints",allpoints, allpoints.length );
  7762. // prepare all points map
  7763. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  7764. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  7765. if ( allPointsMap[ key ] !== undefined ) {
  7766. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  7767. }
  7768. allPointsMap[ key ] = i;
  7769. }
  7770. // remove holes by cutting paths to holes and adding them to the shape
  7771. var shapeWithoutHoles = removeHoles( contour, holes );
  7772. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  7773. //console.log( "triangles",triangles, triangles.length );
  7774. // check all face vertices against all points map
  7775. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  7776. face = triangles[ i ];
  7777. for ( f = 0; f < 3; f ++ ) {
  7778. key = face[ f ].x + ":" + face[ f ].y;
  7779. index = allPointsMap[ key ];
  7780. if ( index !== undefined ) {
  7781. face[ f ] = index;
  7782. }
  7783. }
  7784. }
  7785. return triangles.concat();
  7786. },
  7787. isClockWise: function ( pts ) {
  7788. return ShapeUtils.area( pts ) < 0;
  7789. }
  7790. };
  7791. /**
  7792. * @author zz85 / http://www.lab4games.net/zz85/blog
  7793. *
  7794. * Creates extruded geometry from a path shape.
  7795. *
  7796. * parameters = {
  7797. *
  7798. * curveSegments: <int>, // number of points on the curves
  7799. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  7800. * amount: <int>, // Depth to extrude the shape
  7801. *
  7802. * bevelEnabled: <bool>, // turn on bevel
  7803. * bevelThickness: <float>, // how deep into the original shape bevel goes
  7804. * bevelSize: <float>, // how far from shape outline is bevel
  7805. * bevelSegments: <int>, // number of bevel layers
  7806. *
  7807. * extrudePath: <THREE.Curve> // curve to extrude shape along
  7808. * frames: <Object> // containing arrays of tangents, normals, binormals
  7809. *
  7810. * uvGenerator: <Object> // object that provides UV generator functions
  7811. *
  7812. * }
  7813. **/
  7814. function ExtrudeGeometry( shapes, options ) {
  7815. if ( typeof( shapes ) === "undefined" ) {
  7816. shapes = [];
  7817. return;
  7818. }
  7819. Geometry.call( this );
  7820. this.type = 'ExtrudeGeometry';
  7821. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  7822. this.addShapeList( shapes, options );
  7823. this.computeFaceNormals();
  7824. // can't really use automatic vertex normals
  7825. // as then front and back sides get smoothed too
  7826. // should do separate smoothing just for sides
  7827. //this.computeVertexNormals();
  7828. //console.log( "took", ( Date.now() - startTime ) );
  7829. }
  7830. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  7831. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  7832. ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  7833. var sl = shapes.length;
  7834. for ( var s = 0; s < sl; s ++ ) {
  7835. var shape = shapes[ s ];
  7836. this.addShape( shape, options );
  7837. }
  7838. };
  7839. ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  7840. var amount = options.amount !== undefined ? options.amount : 100;
  7841. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  7842. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  7843. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  7844. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  7845. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  7846. var steps = options.steps !== undefined ? options.steps : 1;
  7847. var extrudePath = options.extrudePath;
  7848. var extrudePts, extrudeByPath = false;
  7849. // Use default WorldUVGenerator if no UV generators are specified.
  7850. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  7851. var splineTube, binormal, normal, position2;
  7852. if ( extrudePath ) {
  7853. extrudePts = extrudePath.getSpacedPoints( steps );
  7854. extrudeByPath = true;
  7855. bevelEnabled = false; // bevels not supported for path extrusion
  7856. // SETUP TNB variables
  7857. // TODO1 - have a .isClosed in spline?
  7858. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  7859. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  7860. binormal = new Vector3();
  7861. normal = new Vector3();
  7862. position2 = new Vector3();
  7863. }
  7864. // Safeguards if bevels are not enabled
  7865. if ( ! bevelEnabled ) {
  7866. bevelSegments = 0;
  7867. bevelThickness = 0;
  7868. bevelSize = 0;
  7869. }
  7870. // Variables initialization
  7871. var ahole, h, hl; // looping of holes
  7872. var scope = this;
  7873. var shapesOffset = this.vertices.length;
  7874. var shapePoints = shape.extractPoints( curveSegments );
  7875. var vertices = shapePoints.shape;
  7876. var holes = shapePoints.holes;
  7877. var reverse = ! ShapeUtils.isClockWise( vertices );
  7878. if ( reverse ) {
  7879. vertices = vertices.reverse();
  7880. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  7881. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  7882. ahole = holes[ h ];
  7883. if ( ShapeUtils.isClockWise( ahole ) ) {
  7884. holes[ h ] = ahole.reverse();
  7885. }
  7886. }
  7887. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  7888. }
  7889. var faces = ShapeUtils.triangulateShape( vertices, holes );
  7890. /* Vertices */
  7891. var contour = vertices; // vertices has all points but contour has only points of circumference
  7892. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  7893. ahole = holes[ h ];
  7894. vertices = vertices.concat( ahole );
  7895. }
  7896. function scalePt2( pt, vec, size ) {
  7897. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  7898. return vec.clone().multiplyScalar( size ).add( pt );
  7899. }
  7900. var b, bs, t, z,
  7901. vert, vlen = vertices.length,
  7902. face, flen = faces.length;
  7903. // Find directions for point movement
  7904. function getBevelVec( inPt, inPrev, inNext ) {
  7905. // computes for inPt the corresponding point inPt' on a new contour
  7906. // shifted by 1 unit (length of normalized vector) to the left
  7907. // if we walk along contour clockwise, this new contour is outside the old one
  7908. //
  7909. // inPt' is the intersection of the two lines parallel to the two
  7910. // adjacent edges of inPt at a distance of 1 unit on the left side.
  7911. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  7912. // good reading for geometry algorithms (here: line-line intersection)
  7913. // http://geomalgorithms.com/a05-_intersect-1.html
  7914. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  7915. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  7916. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  7917. // check for collinear edges
  7918. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  7919. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  7920. // not collinear
  7921. // length of vectors for normalizing
  7922. var v_prev_len = Math.sqrt( v_prev_lensq );
  7923. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  7924. // shift adjacent points by unit vectors to the left
  7925. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  7926. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  7927. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  7928. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  7929. // scaling factor for v_prev to intersection point
  7930. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  7931. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  7932. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  7933. // vector from inPt to intersection point
  7934. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  7935. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  7936. // Don't normalize!, otherwise sharp corners become ugly
  7937. // but prevent crazy spikes
  7938. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  7939. if ( v_trans_lensq <= 2 ) {
  7940. return new Vector2( v_trans_x, v_trans_y );
  7941. } else {
  7942. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  7943. }
  7944. } else {
  7945. // handle special case of collinear edges
  7946. var direction_eq = false; // assumes: opposite
  7947. if ( v_prev_x > Number.EPSILON ) {
  7948. if ( v_next_x > Number.EPSILON ) {
  7949. direction_eq = true;
  7950. }
  7951. } else {
  7952. if ( v_prev_x < - Number.EPSILON ) {
  7953. if ( v_next_x < - Number.EPSILON ) {
  7954. direction_eq = true;
  7955. }
  7956. } else {
  7957. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  7958. direction_eq = true;
  7959. }
  7960. }
  7961. }
  7962. if ( direction_eq ) {
  7963. // console.log("Warning: lines are a straight sequence");
  7964. v_trans_x = - v_prev_y;
  7965. v_trans_y = v_prev_x;
  7966. shrink_by = Math.sqrt( v_prev_lensq );
  7967. } else {
  7968. // console.log("Warning: lines are a straight spike");
  7969. v_trans_x = v_prev_x;
  7970. v_trans_y = v_prev_y;
  7971. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  7972. }
  7973. }
  7974. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  7975. }
  7976. var contourMovements = [];
  7977. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  7978. if ( j === il ) j = 0;
  7979. if ( k === il ) k = 0;
  7980. // (j)---(i)---(k)
  7981. // console.log('i,j,k', i, j , k)
  7982. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  7983. }
  7984. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  7985. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  7986. ahole = holes[ h ];
  7987. oneHoleMovements = [];
  7988. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  7989. if ( j === il ) j = 0;
  7990. if ( k === il ) k = 0;
  7991. // (j)---(i)---(k)
  7992. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  7993. }
  7994. holesMovements.push( oneHoleMovements );
  7995. verticesMovements = verticesMovements.concat( oneHoleMovements );
  7996. }
  7997. // Loop bevelSegments, 1 for the front, 1 for the back
  7998. for ( b = 0; b < bevelSegments; b ++ ) {
  7999. //for ( b = bevelSegments; b > 0; b -- ) {
  8000. t = b / bevelSegments;
  8001. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  8002. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  8003. // contract shape
  8004. for ( i = 0, il = contour.length; i < il; i ++ ) {
  8005. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  8006. v( vert.x, vert.y, - z );
  8007. }
  8008. // expand holes
  8009. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  8010. ahole = holes[ h ];
  8011. oneHoleMovements = holesMovements[ h ];
  8012. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  8013. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  8014. v( vert.x, vert.y, - z );
  8015. }
  8016. }
  8017. }
  8018. bs = bevelSize;
  8019. // Back facing vertices
  8020. for ( i = 0; i < vlen; i ++ ) {
  8021. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  8022. if ( ! extrudeByPath ) {
  8023. v( vert.x, vert.y, 0 );
  8024. } else {
  8025. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  8026. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  8027. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  8028. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  8029. v( position2.x, position2.y, position2.z );
  8030. }
  8031. }
  8032. // Add stepped vertices...
  8033. // Including front facing vertices
  8034. var s;
  8035. for ( s = 1; s <= steps; s ++ ) {
  8036. for ( i = 0; i < vlen; i ++ ) {
  8037. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  8038. if ( ! extrudeByPath ) {
  8039. v( vert.x, vert.y, amount / steps * s );
  8040. } else {
  8041. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  8042. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  8043. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  8044. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  8045. v( position2.x, position2.y, position2.z );
  8046. }
  8047. }
  8048. }
  8049. // Add bevel segments planes
  8050. //for ( b = 1; b <= bevelSegments; b ++ ) {
  8051. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  8052. t = b / bevelSegments;
  8053. z = bevelThickness * Math.cos ( t * Math.PI / 2 );
  8054. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  8055. // contract shape
  8056. for ( i = 0, il = contour.length; i < il; i ++ ) {
  8057. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  8058. v( vert.x, vert.y, amount + z );
  8059. }
  8060. // expand holes
  8061. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  8062. ahole = holes[ h ];
  8063. oneHoleMovements = holesMovements[ h ];
  8064. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  8065. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  8066. if ( ! extrudeByPath ) {
  8067. v( vert.x, vert.y, amount + z );
  8068. } else {
  8069. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  8070. }
  8071. }
  8072. }
  8073. }
  8074. /* Faces */
  8075. // Top and bottom faces
  8076. buildLidFaces();
  8077. // Sides faces
  8078. buildSideFaces();
  8079. ///// Internal functions
  8080. function buildLidFaces() {
  8081. if ( bevelEnabled ) {
  8082. var layer = 0; // steps + 1
  8083. var offset = vlen * layer;
  8084. // Bottom faces
  8085. for ( i = 0; i < flen; i ++ ) {
  8086. face = faces[ i ];
  8087. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  8088. }
  8089. layer = steps + bevelSegments * 2;
  8090. offset = vlen * layer;
  8091. // Top faces
  8092. for ( i = 0; i < flen; i ++ ) {
  8093. face = faces[ i ];
  8094. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  8095. }
  8096. } else {
  8097. // Bottom faces
  8098. for ( i = 0; i < flen; i ++ ) {
  8099. face = faces[ i ];
  8100. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  8101. }
  8102. // Top faces
  8103. for ( i = 0; i < flen; i ++ ) {
  8104. face = faces[ i ];
  8105. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  8106. }
  8107. }
  8108. }
  8109. // Create faces for the z-sides of the shape
  8110. function buildSideFaces() {
  8111. var layeroffset = 0;
  8112. sidewalls( contour, layeroffset );
  8113. layeroffset += contour.length;
  8114. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  8115. ahole = holes[ h ];
  8116. sidewalls( ahole, layeroffset );
  8117. //, true
  8118. layeroffset += ahole.length;
  8119. }
  8120. }
  8121. function sidewalls( contour, layeroffset ) {
  8122. var j, k;
  8123. i = contour.length;
  8124. while ( -- i >= 0 ) {
  8125. j = i;
  8126. k = i - 1;
  8127. if ( k < 0 ) k = contour.length - 1;
  8128. //console.log('b', i,j, i-1, k,vertices.length);
  8129. var s = 0, sl = steps + bevelSegments * 2;
  8130. for ( s = 0; s < sl; s ++ ) {
  8131. var slen1 = vlen * s;
  8132. var slen2 = vlen * ( s + 1 );
  8133. var a = layeroffset + j + slen1,
  8134. b = layeroffset + k + slen1,
  8135. c = layeroffset + k + slen2,
  8136. d = layeroffset + j + slen2;
  8137. f4( a, b, c, d, contour, s, sl, j, k );
  8138. }
  8139. }
  8140. }
  8141. function v( x, y, z ) {
  8142. scope.vertices.push( new Vector3( x, y, z ) );
  8143. }
  8144. function f3( a, b, c ) {
  8145. a += shapesOffset;
  8146. b += shapesOffset;
  8147. c += shapesOffset;
  8148. scope.faces.push( new Face3( a, b, c, null, null, 0 ) );
  8149. var uvs = uvgen.generateTopUV( scope, a, b, c );
  8150. scope.faceVertexUvs[ 0 ].push( uvs );
  8151. }
  8152. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  8153. a += shapesOffset;
  8154. b += shapesOffset;
  8155. c += shapesOffset;
  8156. d += shapesOffset;
  8157. scope.faces.push( new Face3( a, b, d, null, null, 1 ) );
  8158. scope.faces.push( new Face3( b, c, d, null, null, 1 ) );
  8159. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  8160. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  8161. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  8162. }
  8163. };
  8164. ExtrudeGeometry.WorldUVGenerator = {
  8165. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  8166. var vertices = geometry.vertices;
  8167. var a = vertices[ indexA ];
  8168. var b = vertices[ indexB ];
  8169. var c = vertices[ indexC ];
  8170. return [
  8171. new Vector2( a.x, a.y ),
  8172. new Vector2( b.x, b.y ),
  8173. new Vector2( c.x, c.y )
  8174. ];
  8175. },
  8176. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  8177. var vertices = geometry.vertices;
  8178. var a = vertices[ indexA ];
  8179. var b = vertices[ indexB ];
  8180. var c = vertices[ indexC ];
  8181. var d = vertices[ indexD ];
  8182. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  8183. return [
  8184. new Vector2( a.x, 1 - a.z ),
  8185. new Vector2( b.x, 1 - b.z ),
  8186. new Vector2( c.x, 1 - c.z ),
  8187. new Vector2( d.x, 1 - d.z )
  8188. ];
  8189. } else {
  8190. return [
  8191. new Vector2( a.y, 1 - a.z ),
  8192. new Vector2( b.y, 1 - b.z ),
  8193. new Vector2( c.y, 1 - c.z ),
  8194. new Vector2( d.y, 1 - d.z )
  8195. ];
  8196. }
  8197. }
  8198. };
  8199. /**
  8200. * @author jonobr1 / http://jonobr1.com
  8201. */
  8202. function ShapeGeometry( shapes, curveSegments ) {
  8203. Geometry.call( this );
  8204. this.type = 'ShapeGeometry';
  8205. if ( typeof curveSegments === 'object' ) {
  8206. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  8207. curveSegments = curveSegments.curveSegments;
  8208. }
  8209. this.parameters = {
  8210. shapes: shapes,
  8211. curveSegments: curveSegments
  8212. };
  8213. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  8214. this.mergeVertices();
  8215. }
  8216. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  8217. ShapeGeometry.prototype.constructor = ShapeGeometry;
  8218. /**
  8219. * @author Mugen87 / https://github.com/Mugen87
  8220. */
  8221. function ShapeBufferGeometry( shapes, curveSegments ) {
  8222. BufferGeometry.call( this );
  8223. this.type = 'ShapeBufferGeometry';
  8224. this.parameters = {
  8225. shapes: shapes,
  8226. curveSegments: curveSegments
  8227. };
  8228. curveSegments = curveSegments || 12;
  8229. // buffers
  8230. var indices = [];
  8231. var vertices = [];
  8232. var normals = [];
  8233. var uvs = [];
  8234. // helper variables
  8235. var groupStart = 0;
  8236. var groupCount = 0;
  8237. // allow single and array values for "shapes" parameter
  8238. if ( Array.isArray( shapes ) === false ) {
  8239. addShape( shapes );
  8240. } else {
  8241. for ( var i = 0; i < shapes.length; i ++ ) {
  8242. addShape( shapes[ i ] );
  8243. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  8244. groupStart += groupCount;
  8245. groupCount = 0;
  8246. }
  8247. }
  8248. // build geometry
  8249. this.setIndex( indices );
  8250. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8251. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8252. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8253. // helper functions
  8254. function addShape( shape ) {
  8255. var i, l, shapeHole;
  8256. var indexOffset = vertices.length / 3;
  8257. var points = shape.extractPoints( curveSegments );
  8258. var shapeVertices = points.shape;
  8259. var shapeHoles = points.holes;
  8260. // check direction of vertices
  8261. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  8262. shapeVertices = shapeVertices.reverse();
  8263. // also check if holes are in the opposite direction
  8264. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  8265. shapeHole = shapeHoles[ i ];
  8266. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  8267. shapeHoles[ i ] = shapeHole.reverse();
  8268. }
  8269. }
  8270. }
  8271. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  8272. // join vertices of inner and outer paths to a single array
  8273. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  8274. shapeHole = shapeHoles[ i ];
  8275. shapeVertices = shapeVertices.concat( shapeHole );
  8276. }
  8277. // vertices, normals, uvs
  8278. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  8279. var vertex = shapeVertices[ i ];
  8280. vertices.push( vertex.x, vertex.y, 0 );
  8281. normals.push( 0, 0, 1 );
  8282. uvs.push( vertex.x, vertex.y ); // world uvs
  8283. }
  8284. // incides
  8285. for ( i = 0, l = faces.length; i < l; i ++ ) {
  8286. var face = faces[ i ];
  8287. var a = face[ 0 ] + indexOffset;
  8288. var b = face[ 1 ] + indexOffset;
  8289. var c = face[ 2 ] + indexOffset;
  8290. indices.push( a, b, c );
  8291. groupCount += 3;
  8292. }
  8293. }
  8294. }
  8295. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  8296. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  8297. /**
  8298. * @author mrdoob / http://mrdoob.com/
  8299. * @author Mugen87 / https://github.com/Mugen87
  8300. */
  8301. function WireframeGeometry( geometry ) {
  8302. BufferGeometry.call( this );
  8303. this.type = 'WireframeGeometry';
  8304. // buffer
  8305. var vertices = [];
  8306. // helper variables
  8307. var i, j, l, o, ol;
  8308. var edge = [ 0, 0 ], edges = {}, e;
  8309. var key, keys = [ 'a', 'b', 'c' ];
  8310. var vertex;
  8311. // different logic for Geometry and BufferGeometry
  8312. if ( geometry && geometry.isGeometry ) {
  8313. // create a data structure that contains all edges without duplicates
  8314. var faces = geometry.faces;
  8315. for ( i = 0, l = faces.length; i < l; i ++ ) {
  8316. var face = faces[ i ];
  8317. for ( j = 0; j < 3; j ++ ) {
  8318. edge[ 0 ] = face[ keys[ j ] ];
  8319. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  8320. edge.sort( sortFunction ); // sorting prevents duplicates
  8321. key = edge.toString();
  8322. if ( edges[ key ] === undefined ) {
  8323. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  8324. }
  8325. }
  8326. }
  8327. // generate vertices
  8328. for ( key in edges ) {
  8329. e = edges[ key ];
  8330. vertex = geometry.vertices[ e.index1 ];
  8331. vertices.push( vertex.x, vertex.y, vertex.z );
  8332. vertex = geometry.vertices[ e.index2 ];
  8333. vertices.push( vertex.x, vertex.y, vertex.z );
  8334. }
  8335. } else if ( geometry && geometry.isBufferGeometry ) {
  8336. var position, indices, groups;
  8337. var group, start, count;
  8338. var index1, index2;
  8339. vertex = new Vector3();
  8340. if ( geometry.index !== null ) {
  8341. // indexed BufferGeometry
  8342. position = geometry.attributes.position;
  8343. indices = geometry.index;
  8344. groups = geometry.groups;
  8345. if ( groups.length === 0 ) {
  8346. geometry.addGroup( 0, indices.count );
  8347. }
  8348. // create a data structure that contains all eges without duplicates
  8349. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  8350. group = groups[ o ];
  8351. start = group.start;
  8352. count = group.count;
  8353. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  8354. for ( j = 0; j < 3; j ++ ) {
  8355. edge[ 0 ] = indices.getX( i + j );
  8356. edge[ 1 ] = indices.getX( i + ( j + 1 ) % 3 );
  8357. edge.sort( sortFunction ); // sorting prevents duplicates
  8358. key = edge.toString();
  8359. if ( edges[ key ] === undefined ) {
  8360. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  8361. }
  8362. }
  8363. }
  8364. }
  8365. // generate vertices
  8366. for ( key in edges ) {
  8367. e = edges[ key ];
  8368. vertex.fromBufferAttribute( position, e.index1 );
  8369. vertices.push( vertex.x, vertex.y, vertex.z );
  8370. vertex.fromBufferAttribute( position, e.index2 );
  8371. vertices.push( vertex.x, vertex.y, vertex.z );
  8372. }
  8373. } else {
  8374. // non-indexed BufferGeometry
  8375. position = geometry.attributes.position;
  8376. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  8377. for ( j = 0; j < 3; j ++ ) {
  8378. // three edges per triangle, an edge is represented as (index1, index2)
  8379. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  8380. index1 = 3 * i + j;
  8381. vertex.fromBufferAttribute( position, index1 );
  8382. vertices.push( vertex.x, vertex.y, vertex.z );
  8383. index2 = 3 * i + ( ( j + 1 ) % 3 );
  8384. vertex.fromBufferAttribute( position, index2 );
  8385. vertices.push( vertex.x, vertex.y, vertex.z );
  8386. }
  8387. }
  8388. }
  8389. }
  8390. // build geometry
  8391. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8392. // custom array sort function
  8393. function sortFunction( a, b ) {
  8394. return a - b;
  8395. }
  8396. }
  8397. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  8398. WireframeGeometry.prototype.constructor = WireframeGeometry;
  8399. /**
  8400. * @author mrdoob / http://mrdoob.com/
  8401. * @author alteredq / http://alteredqualia.com/
  8402. */
  8403. function Light( color, intensity ) {
  8404. Object3D.call( this );
  8405. this.type = 'Light';
  8406. this.color = new Color( color );
  8407. this.intensity = intensity !== undefined ? intensity : 1;
  8408. this.receiveShadow = undefined;
  8409. }
  8410. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  8411. constructor: Light,
  8412. isLight: true,
  8413. copy: function ( source ) {
  8414. Object3D.prototype.copy.call( this, source );
  8415. this.color.copy( source.color );
  8416. this.intensity = source.intensity;
  8417. return this;
  8418. },
  8419. toJSON: function ( meta ) {
  8420. var data = Object3D.prototype.toJSON.call( this, meta );
  8421. data.object.color = this.color.getHex();
  8422. data.object.intensity = this.intensity;
  8423. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  8424. if ( this.distance !== undefined ) data.object.distance = this.distance;
  8425. if ( this.angle !== undefined ) data.object.angle = this.angle;
  8426. if ( this.decay !== undefined ) data.object.decay = this.decay;
  8427. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  8428. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  8429. return data;
  8430. }
  8431. } );
  8432. /**
  8433. * @author mrdoob / http://mrdoob.com/
  8434. */
  8435. var Cache = {
  8436. enabled: false,
  8437. files: {},
  8438. add: function ( key, file ) {
  8439. if ( this.enabled === false ) return;
  8440. // console.log( 'THREE.Cache', 'Adding key:', key );
  8441. this.files[ key ] = file;
  8442. },
  8443. get: function ( key ) {
  8444. if ( this.enabled === false ) return;
  8445. // console.log( 'THREE.Cache', 'Checking key:', key );
  8446. return this.files[ key ];
  8447. },
  8448. remove: function ( key ) {
  8449. delete this.files[ key ];
  8450. },
  8451. clear: function () {
  8452. this.files = {};
  8453. }
  8454. };
  8455. /**
  8456. * @author mrdoob / http://mrdoob.com/
  8457. */
  8458. function LoadingManager( onLoad, onProgress, onError ) {
  8459. var scope = this;
  8460. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  8461. this.onStart = undefined;
  8462. this.onLoad = onLoad;
  8463. this.onProgress = onProgress;
  8464. this.onError = onError;
  8465. this.itemStart = function ( url ) {
  8466. itemsTotal ++;
  8467. if ( isLoading === false ) {
  8468. if ( scope.onStart !== undefined ) {
  8469. scope.onStart( url, itemsLoaded, itemsTotal );
  8470. }
  8471. }
  8472. isLoading = true;
  8473. };
  8474. this.itemEnd = function ( url ) {
  8475. itemsLoaded ++;
  8476. if ( scope.onProgress !== undefined ) {
  8477. scope.onProgress( url, itemsLoaded, itemsTotal );
  8478. }
  8479. if ( itemsLoaded === itemsTotal ) {
  8480. isLoading = false;
  8481. if ( scope.onLoad !== undefined ) {
  8482. scope.onLoad();
  8483. }
  8484. }
  8485. };
  8486. this.itemError = function ( url ) {
  8487. if ( scope.onError !== undefined ) {
  8488. scope.onError( url );
  8489. }
  8490. };
  8491. }
  8492. var DefaultLoadingManager = new LoadingManager();
  8493. /**
  8494. * @author mrdoob / http://mrdoob.com/
  8495. */
  8496. function FileLoader( manager ) {
  8497. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  8498. }
  8499. Object.assign( FileLoader.prototype, {
  8500. load: function ( url, onLoad, onProgress, onError ) {
  8501. if ( url === undefined ) url = '';
  8502. if ( this.path !== undefined ) url = this.path + url;
  8503. var scope = this;
  8504. var cached = Cache.get( url );
  8505. if ( cached !== undefined ) {
  8506. scope.manager.itemStart( url );
  8507. setTimeout( function () {
  8508. if ( onLoad ) onLoad( cached );
  8509. scope.manager.itemEnd( url );
  8510. }, 0 );
  8511. return cached;
  8512. }
  8513. // Check for data: URI
  8514. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  8515. var dataUriRegexResult = url.match( dataUriRegex );
  8516. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  8517. if ( dataUriRegexResult ) {
  8518. var mimeType = dataUriRegexResult[ 1 ];
  8519. var isBase64 = !! dataUriRegexResult[ 2 ];
  8520. var data = dataUriRegexResult[ 3 ];
  8521. data = window.decodeURIComponent( data );
  8522. if ( isBase64 ) data = window.atob( data );
  8523. try {
  8524. var response;
  8525. var responseType = ( this.responseType || '' ).toLowerCase();
  8526. switch ( responseType ) {
  8527. case 'arraybuffer':
  8528. case 'blob':
  8529. response = new ArrayBuffer( data.length );
  8530. var view = new Uint8Array( response );
  8531. for ( var i = 0; i < data.length; i ++ ) {
  8532. view[ i ] = data.charCodeAt( i );
  8533. }
  8534. if ( responseType === 'blob' ) {
  8535. response = new Blob( [ response ], { type: mimeType } );
  8536. }
  8537. break;
  8538. case 'document':
  8539. var parser = new DOMParser();
  8540. response = parser.parseFromString( data, mimeType );
  8541. break;
  8542. case 'json':
  8543. response = JSON.parse( data );
  8544. break;
  8545. default: // 'text' or other
  8546. response = data;
  8547. break;
  8548. }
  8549. // Wait for next browser tick
  8550. window.setTimeout( function () {
  8551. if ( onLoad ) onLoad( response );
  8552. scope.manager.itemEnd( url );
  8553. }, 0 );
  8554. } catch ( error ) {
  8555. // Wait for next browser tick
  8556. window.setTimeout( function () {
  8557. if ( onError ) onError( error );
  8558. scope.manager.itemError( url );
  8559. }, 0 );
  8560. }
  8561. } else {
  8562. var request = new XMLHttpRequest();
  8563. request.open( 'GET', url, true );
  8564. request.addEventListener( 'load', function ( event ) {
  8565. var response = event.target.response;
  8566. Cache.add( url, response );
  8567. if ( this.status === 200 ) {
  8568. if ( onLoad ) onLoad( response );
  8569. scope.manager.itemEnd( url );
  8570. } else if ( this.status === 0 ) {
  8571. // Some browsers return HTTP Status 0 when using non-http protocol
  8572. // e.g. 'file://' or 'data://'. Handle as success.
  8573. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  8574. if ( onLoad ) onLoad( response );
  8575. scope.manager.itemEnd( url );
  8576. } else {
  8577. if ( onError ) onError( event );
  8578. scope.manager.itemError( url );
  8579. }
  8580. }, false );
  8581. if ( onProgress !== undefined ) {
  8582. request.addEventListener( 'progress', function ( event ) {
  8583. onProgress( event );
  8584. }, false );
  8585. }
  8586. request.addEventListener( 'error', function ( event ) {
  8587. if ( onError ) onError( event );
  8588. scope.manager.itemError( url );
  8589. }, false );
  8590. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  8591. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  8592. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  8593. request.send( null );
  8594. }
  8595. scope.manager.itemStart( url );
  8596. return request;
  8597. },
  8598. setPath: function ( value ) {
  8599. this.path = value;
  8600. return this;
  8601. },
  8602. setResponseType: function ( value ) {
  8603. this.responseType = value;
  8604. return this;
  8605. },
  8606. setWithCredentials: function ( value ) {
  8607. this.withCredentials = value;
  8608. return this;
  8609. },
  8610. setMimeType: function ( value ) {
  8611. this.mimeType = value;
  8612. return this;
  8613. }
  8614. } );
  8615. var context;
  8616. var AudioContext = {
  8617. getContext: function () {
  8618. if ( context === undefined ) {
  8619. context = new ( window.AudioContext || window.webkitAudioContext )();
  8620. }
  8621. return context;
  8622. },
  8623. setContext: function ( value ) {
  8624. context = value;
  8625. }
  8626. };
  8627. /**
  8628. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  8629. */
  8630. function AudioLoader( manager ) {
  8631. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  8632. }
  8633. Object.assign( AudioLoader.prototype, {
  8634. load: function ( url, onLoad, onProgress, onError ) {
  8635. var loader = new FileLoader( this.manager );
  8636. loader.setResponseType( 'arraybuffer' );
  8637. loader.load( url, function ( buffer ) {
  8638. var context = AudioContext.getContext();
  8639. context.decodeAudioData( buffer, function ( audioBuffer ) {
  8640. onLoad( audioBuffer );
  8641. } );
  8642. }, onProgress, onError );
  8643. }
  8644. } );
  8645. /**
  8646. * @author mrdoob / http://mrdoob.com/
  8647. */
  8648. function ImageLoader( manager ) {
  8649. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  8650. }
  8651. Object.assign( ImageLoader.prototype, {
  8652. load: function ( url, onLoad, onProgress, onError ) {
  8653. if ( url === undefined ) url = '';
  8654. if ( this.path !== undefined ) url = this.path + url;
  8655. var scope = this;
  8656. var cached = Cache.get( url );
  8657. if ( cached !== undefined ) {
  8658. scope.manager.itemStart( url );
  8659. setTimeout( function () {
  8660. if ( onLoad ) onLoad( cached );
  8661. scope.manager.itemEnd( url );
  8662. }, 0 );
  8663. return cached;
  8664. }
  8665. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  8666. image.addEventListener( 'load', function () {
  8667. Cache.add( url, this );
  8668. if ( onLoad ) onLoad( this );
  8669. scope.manager.itemEnd( url );
  8670. }, false );
  8671. /*
  8672. image.addEventListener( 'progress', function ( event ) {
  8673. if ( onProgress ) onProgress( event );
  8674. }, false );
  8675. */
  8676. image.addEventListener( 'error', function ( event ) {
  8677. if ( onError ) onError( event );
  8678. scope.manager.itemError( url );
  8679. }, false );
  8680. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  8681. scope.manager.itemStart( url );
  8682. image.src = url;
  8683. return image;
  8684. },
  8685. setCrossOrigin: function ( value ) {
  8686. this.crossOrigin = value;
  8687. return this;
  8688. },
  8689. setPath: function ( value ) {
  8690. this.path = value;
  8691. return this;
  8692. }
  8693. } );
  8694. /**
  8695. * @author mrdoob / http://mrdoob.com/
  8696. * @author alteredq / http://alteredqualia.com/
  8697. * @author szimek / https://github.com/szimek/
  8698. */
  8699. var textureId = 0;
  8700. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  8701. Object.defineProperty( this, 'id', { value: textureId ++ } );
  8702. this.uuid = _Math.generateUUID();
  8703. this.name = '';
  8704. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  8705. this.mipmaps = [];
  8706. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  8707. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  8708. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  8709. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  8710. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  8711. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8712. this.format = format !== undefined ? format : RGBAFormat;
  8713. this.type = type !== undefined ? type : UnsignedByteType;
  8714. this.offset = new Vector2( 0, 0 );
  8715. this.repeat = new Vector2( 1, 1 );
  8716. this.generateMipmaps = true;
  8717. this.premultiplyAlpha = false;
  8718. this.flipY = true;
  8719. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8720. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  8721. //
  8722. // Also changing the encoding after already used by a Material will not automatically make the Material
  8723. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  8724. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  8725. this.version = 0;
  8726. this.onUpdate = null;
  8727. }
  8728. Texture.DEFAULT_IMAGE = undefined;
  8729. Texture.DEFAULT_MAPPING = UVMapping;
  8730. Texture.prototype = {
  8731. constructor: Texture,
  8732. isTexture: true,
  8733. set needsUpdate( value ) {
  8734. if ( value === true ) this.version ++;
  8735. },
  8736. clone: function () {
  8737. return new this.constructor().copy( this );
  8738. },
  8739. copy: function ( source ) {
  8740. this.image = source.image;
  8741. this.mipmaps = source.mipmaps.slice( 0 );
  8742. this.mapping = source.mapping;
  8743. this.wrapS = source.wrapS;
  8744. this.wrapT = source.wrapT;
  8745. this.magFilter = source.magFilter;
  8746. this.minFilter = source.minFilter;
  8747. this.anisotropy = source.anisotropy;
  8748. this.format = source.format;
  8749. this.type = source.type;
  8750. this.offset.copy( source.offset );
  8751. this.repeat.copy( source.repeat );
  8752. this.generateMipmaps = source.generateMipmaps;
  8753. this.premultiplyAlpha = source.premultiplyAlpha;
  8754. this.flipY = source.flipY;
  8755. this.unpackAlignment = source.unpackAlignment;
  8756. this.encoding = source.encoding;
  8757. return this;
  8758. },
  8759. toJSON: function ( meta ) {
  8760. if ( meta.textures[ this.uuid ] !== undefined ) {
  8761. return meta.textures[ this.uuid ];
  8762. }
  8763. function getDataURL( image ) {
  8764. var canvas;
  8765. if ( image.toDataURL !== undefined ) {
  8766. canvas = image;
  8767. } else {
  8768. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  8769. canvas.width = image.width;
  8770. canvas.height = image.height;
  8771. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  8772. }
  8773. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  8774. return canvas.toDataURL( 'image/jpeg', 0.6 );
  8775. } else {
  8776. return canvas.toDataURL( 'image/png' );
  8777. }
  8778. }
  8779. var output = {
  8780. metadata: {
  8781. version: 4.4,
  8782. type: 'Texture',
  8783. generator: 'Texture.toJSON'
  8784. },
  8785. uuid: this.uuid,
  8786. name: this.name,
  8787. mapping: this.mapping,
  8788. repeat: [ this.repeat.x, this.repeat.y ],
  8789. offset: [ this.offset.x, this.offset.y ],
  8790. wrap: [ this.wrapS, this.wrapT ],
  8791. minFilter: this.minFilter,
  8792. magFilter: this.magFilter,
  8793. anisotropy: this.anisotropy,
  8794. flipY: this.flipY
  8795. };
  8796. if ( this.image !== undefined ) {
  8797. // TODO: Move to THREE.Image
  8798. var image = this.image;
  8799. if ( image.uuid === undefined ) {
  8800. image.uuid = _Math.generateUUID(); // UGH
  8801. }
  8802. if ( meta.images[ image.uuid ] === undefined ) {
  8803. meta.images[ image.uuid ] = {
  8804. uuid: image.uuid,
  8805. url: getDataURL( image )
  8806. };
  8807. }
  8808. output.image = image.uuid;
  8809. }
  8810. meta.textures[ this.uuid ] = output;
  8811. return output;
  8812. },
  8813. dispose: function () {
  8814. this.dispatchEvent( { type: 'dispose' } );
  8815. },
  8816. transformUv: function ( uv ) {
  8817. if ( this.mapping !== UVMapping ) return;
  8818. uv.multiply( this.repeat );
  8819. uv.add( this.offset );
  8820. if ( uv.x < 0 || uv.x > 1 ) {
  8821. switch ( this.wrapS ) {
  8822. case RepeatWrapping:
  8823. uv.x = uv.x - Math.floor( uv.x );
  8824. break;
  8825. case ClampToEdgeWrapping:
  8826. uv.x = uv.x < 0 ? 0 : 1;
  8827. break;
  8828. case MirroredRepeatWrapping:
  8829. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  8830. uv.x = Math.ceil( uv.x ) - uv.x;
  8831. } else {
  8832. uv.x = uv.x - Math.floor( uv.x );
  8833. }
  8834. break;
  8835. }
  8836. }
  8837. if ( uv.y < 0 || uv.y > 1 ) {
  8838. switch ( this.wrapT ) {
  8839. case RepeatWrapping:
  8840. uv.y = uv.y - Math.floor( uv.y );
  8841. break;
  8842. case ClampToEdgeWrapping:
  8843. uv.y = uv.y < 0 ? 0 : 1;
  8844. break;
  8845. case MirroredRepeatWrapping:
  8846. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  8847. uv.y = Math.ceil( uv.y ) - uv.y;
  8848. } else {
  8849. uv.y = uv.y - Math.floor( uv.y );
  8850. }
  8851. break;
  8852. }
  8853. }
  8854. if ( this.flipY ) {
  8855. uv.y = 1 - uv.y;
  8856. }
  8857. }
  8858. };
  8859. Object.assign( Texture.prototype, EventDispatcher.prototype );
  8860. /**
  8861. * @author mrdoob / http://mrdoob.com/
  8862. */
  8863. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  8864. images = images !== undefined ? images : [];
  8865. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  8866. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  8867. this.flipY = false;
  8868. }
  8869. CubeTexture.prototype = Object.create( Texture.prototype );
  8870. CubeTexture.prototype.constructor = CubeTexture;
  8871. CubeTexture.prototype.isCubeTexture = true;
  8872. Object.defineProperty( CubeTexture.prototype, 'images', {
  8873. get: function () {
  8874. return this.image;
  8875. },
  8876. set: function ( value ) {
  8877. this.image = value;
  8878. }
  8879. } );
  8880. /**
  8881. * @author mrdoob / http://mrdoob.com/
  8882. */
  8883. function CubeTextureLoader( manager ) {
  8884. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  8885. }
  8886. Object.assign( CubeTextureLoader.prototype, {
  8887. load: function ( urls, onLoad, onProgress, onError ) {
  8888. var texture = new CubeTexture();
  8889. var loader = new ImageLoader( this.manager );
  8890. loader.setCrossOrigin( this.crossOrigin );
  8891. loader.setPath( this.path );
  8892. var loaded = 0;
  8893. function loadTexture( i ) {
  8894. loader.load( urls[ i ], function ( image ) {
  8895. texture.images[ i ] = image;
  8896. loaded ++;
  8897. if ( loaded === 6 ) {
  8898. texture.needsUpdate = true;
  8899. if ( onLoad ) onLoad( texture );
  8900. }
  8901. }, undefined, onError );
  8902. }
  8903. for ( var i = 0; i < urls.length; ++ i ) {
  8904. loadTexture( i );
  8905. }
  8906. return texture;
  8907. },
  8908. setCrossOrigin: function ( value ) {
  8909. this.crossOrigin = value;
  8910. return this;
  8911. },
  8912. setPath: function ( value ) {
  8913. this.path = value;
  8914. return this;
  8915. }
  8916. } );
  8917. /**
  8918. * @author alteredq / http://alteredqualia.com/
  8919. */
  8920. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  8921. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  8922. this.image = { data: data, width: width, height: height };
  8923. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  8924. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  8925. this.generateMipmaps = false;
  8926. this.flipY = false;
  8927. this.unpackAlignment = 1;
  8928. }
  8929. DataTexture.prototype = Object.create( Texture.prototype );
  8930. DataTexture.prototype.constructor = DataTexture;
  8931. DataTexture.prototype.isDataTexture = true;
  8932. /**
  8933. * @author Nikos M. / https://github.com/foo123/
  8934. *
  8935. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  8936. */
  8937. function DataTextureLoader( manager ) {
  8938. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  8939. // override in sub classes
  8940. this._parser = null;
  8941. }
  8942. Object.assign( DataTextureLoader.prototype, {
  8943. load: function ( url, onLoad, onProgress, onError ) {
  8944. var scope = this;
  8945. var texture = new DataTexture();
  8946. var loader = new FileLoader( this.manager );
  8947. loader.setResponseType( 'arraybuffer' );
  8948. loader.load( url, function ( buffer ) {
  8949. var texData = scope._parser( buffer );
  8950. if ( ! texData ) return;
  8951. if ( undefined !== texData.image ) {
  8952. texture.image = texData.image;
  8953. } else if ( undefined !== texData.data ) {
  8954. texture.image.width = texData.width;
  8955. texture.image.height = texData.height;
  8956. texture.image.data = texData.data;
  8957. }
  8958. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  8959. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  8960. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  8961. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  8962. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  8963. if ( undefined !== texData.format ) {
  8964. texture.format = texData.format;
  8965. }
  8966. if ( undefined !== texData.type ) {
  8967. texture.type = texData.type;
  8968. }
  8969. if ( undefined !== texData.mipmaps ) {
  8970. texture.mipmaps = texData.mipmaps;
  8971. }
  8972. if ( 1 === texData.mipmapCount ) {
  8973. texture.minFilter = LinearFilter;
  8974. }
  8975. texture.needsUpdate = true;
  8976. if ( onLoad ) onLoad( texture, texData );
  8977. }, onProgress, onError );
  8978. return texture;
  8979. }
  8980. } );
  8981. /**
  8982. * @author mrdoob / http://mrdoob.com/
  8983. */
  8984. function TextureLoader( manager ) {
  8985. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  8986. }
  8987. Object.assign( TextureLoader.prototype, {
  8988. load: function ( url, onLoad, onProgress, onError ) {
  8989. var texture = new Texture();
  8990. var loader = new ImageLoader( this.manager );
  8991. loader.setCrossOrigin( this.crossOrigin );
  8992. loader.setPath( this.path );
  8993. loader.load( url, function ( image ) {
  8994. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  8995. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  8996. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  8997. texture.image = image;
  8998. texture.needsUpdate = true;
  8999. if ( onLoad !== undefined ) {
  9000. onLoad( texture );
  9001. }
  9002. }, onProgress, onError );
  9003. return texture;
  9004. },
  9005. setCrossOrigin: function ( value ) {
  9006. this.crossOrigin = value;
  9007. return this;
  9008. },
  9009. setPath: function ( value ) {
  9010. this.path = value;
  9011. return this;
  9012. }
  9013. } );
  9014. /**
  9015. * @author mrdoob / http://mrdoob.com/
  9016. * @author alteredq / http://alteredqualia.com/
  9017. *
  9018. * parameters = {
  9019. * color: <hex>,
  9020. * specular: <hex>,
  9021. * shininess: <float>,
  9022. * opacity: <float>,
  9023. *
  9024. * map: new THREE.Texture( <Image> ),
  9025. *
  9026. * lightMap: new THREE.Texture( <Image> ),
  9027. * lightMapIntensity: <float>
  9028. *
  9029. * aoMap: new THREE.Texture( <Image> ),
  9030. * aoMapIntensity: <float>
  9031. *
  9032. * emissive: <hex>,
  9033. * emissiveIntensity: <float>
  9034. * emissiveMap: new THREE.Texture( <Image> ),
  9035. *
  9036. * bumpMap: new THREE.Texture( <Image> ),
  9037. * bumpScale: <float>,
  9038. *
  9039. * normalMap: new THREE.Texture( <Image> ),
  9040. * normalScale: <Vector2>,
  9041. *
  9042. * displacementMap: new THREE.Texture( <Image> ),
  9043. * displacementScale: <float>,
  9044. * displacementBias: <float>,
  9045. *
  9046. * specularMap: new THREE.Texture( <Image> ),
  9047. *
  9048. * alphaMap: new THREE.Texture( <Image> ),
  9049. *
  9050. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  9051. * combine: THREE.Multiply,
  9052. * reflectivity: <float>,
  9053. * refractionRatio: <float>,
  9054. *
  9055. * wireframe: <boolean>,
  9056. * wireframeLinewidth: <float>,
  9057. *
  9058. * skinning: <bool>,
  9059. * morphTargets: <bool>,
  9060. * morphNormals: <bool>
  9061. * }
  9062. */
  9063. function MeshPhongMaterial( parameters ) {
  9064. Material.call( this );
  9065. this.type = 'MeshPhongMaterial';
  9066. this.color = new Color( 0xffffff ); // diffuse
  9067. this.specular = new Color( 0x111111 );
  9068. this.shininess = 30;
  9069. this.map = null;
  9070. this.lightMap = null;
  9071. this.lightMapIntensity = 1.0;
  9072. this.aoMap = null;
  9073. this.aoMapIntensity = 1.0;
  9074. this.emissive = new Color( 0x000000 );
  9075. this.emissiveIntensity = 1.0;
  9076. this.emissiveMap = null;
  9077. this.bumpMap = null;
  9078. this.bumpScale = 1;
  9079. this.normalMap = null;
  9080. this.normalScale = new Vector2( 1, 1 );
  9081. this.displacementMap = null;
  9082. this.displacementScale = 1;
  9083. this.displacementBias = 0;
  9084. this.specularMap = null;
  9085. this.alphaMap = null;
  9086. this.envMap = null;
  9087. this.combine = MultiplyOperation;
  9088. this.reflectivity = 1;
  9089. this.refractionRatio = 0.98;
  9090. this.wireframe = false;
  9091. this.wireframeLinewidth = 1;
  9092. this.wireframeLinecap = 'round';
  9093. this.wireframeLinejoin = 'round';
  9094. this.skinning = false;
  9095. this.morphTargets = false;
  9096. this.morphNormals = false;
  9097. this.setValues( parameters );
  9098. }
  9099. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  9100. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  9101. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  9102. MeshPhongMaterial.prototype.copy = function ( source ) {
  9103. Material.prototype.copy.call( this, source );
  9104. this.color.copy( source.color );
  9105. this.specular.copy( source.specular );
  9106. this.shininess = source.shininess;
  9107. this.map = source.map;
  9108. this.lightMap = source.lightMap;
  9109. this.lightMapIntensity = source.lightMapIntensity;
  9110. this.aoMap = source.aoMap;
  9111. this.aoMapIntensity = source.aoMapIntensity;
  9112. this.emissive.copy( source.emissive );
  9113. this.emissiveMap = source.emissiveMap;
  9114. this.emissiveIntensity = source.emissiveIntensity;
  9115. this.bumpMap = source.bumpMap;
  9116. this.bumpScale = source.bumpScale;
  9117. this.normalMap = source.normalMap;
  9118. this.normalScale.copy( source.normalScale );
  9119. this.displacementMap = source.displacementMap;
  9120. this.displacementScale = source.displacementScale;
  9121. this.displacementBias = source.displacementBias;
  9122. this.specularMap = source.specularMap;
  9123. this.alphaMap = source.alphaMap;
  9124. this.envMap = source.envMap;
  9125. this.combine = source.combine;
  9126. this.reflectivity = source.reflectivity;
  9127. this.refractionRatio = source.refractionRatio;
  9128. this.wireframe = source.wireframe;
  9129. this.wireframeLinewidth = source.wireframeLinewidth;
  9130. this.wireframeLinecap = source.wireframeLinecap;
  9131. this.wireframeLinejoin = source.wireframeLinejoin;
  9132. this.skinning = source.skinning;
  9133. this.morphTargets = source.morphTargets;
  9134. this.morphNormals = source.morphNormals;
  9135. return this;
  9136. };
  9137. /**
  9138. * @author mrdoob / http://mrdoob.com/
  9139. */
  9140. function MultiMaterial( materials ) {
  9141. this.uuid = _Math.generateUUID();
  9142. this.type = 'MultiMaterial';
  9143. this.materials = Array.isArray( materials ) ? materials : [];
  9144. this.visible = true;
  9145. }
  9146. MultiMaterial.prototype = {
  9147. constructor: MultiMaterial,
  9148. isMultiMaterial: true,
  9149. toJSON: function ( meta ) {
  9150. var output = {
  9151. metadata: {
  9152. version: 4.2,
  9153. type: 'material',
  9154. generator: 'MaterialExporter'
  9155. },
  9156. uuid: this.uuid,
  9157. type: this.type,
  9158. materials: []
  9159. };
  9160. var materials = this.materials;
  9161. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  9162. var material = materials[ i ].toJSON( meta );
  9163. delete material.metadata;
  9164. output.materials.push( material );
  9165. }
  9166. output.visible = this.visible;
  9167. return output;
  9168. },
  9169. clone: function () {
  9170. var material = new this.constructor();
  9171. for ( var i = 0; i < this.materials.length; i ++ ) {
  9172. material.materials.push( this.materials[ i ].clone() );
  9173. }
  9174. material.visible = this.visible;
  9175. return material;
  9176. }
  9177. };
  9178. /**
  9179. * @author mrdoob / http://mrdoob.com/
  9180. * @author alteredq / http://alteredqualia.com/
  9181. *
  9182. * parameters = {
  9183. * color: <hex>,
  9184. * opacity: <float>,
  9185. * map: new THREE.Texture( <Image> ),
  9186. *
  9187. * size: <float>,
  9188. * sizeAttenuation: <bool>
  9189. * }
  9190. */
  9191. function PointsMaterial( parameters ) {
  9192. Material.call( this );
  9193. this.type = 'PointsMaterial';
  9194. this.color = new Color( 0xffffff );
  9195. this.map = null;
  9196. this.size = 1;
  9197. this.sizeAttenuation = true;
  9198. this.lights = false;
  9199. this.setValues( parameters );
  9200. }
  9201. PointsMaterial.prototype = Object.create( Material.prototype );
  9202. PointsMaterial.prototype.constructor = PointsMaterial;
  9203. PointsMaterial.prototype.isPointsMaterial = true;
  9204. PointsMaterial.prototype.copy = function ( source ) {
  9205. Material.prototype.copy.call( this, source );
  9206. this.color.copy( source.color );
  9207. this.map = source.map;
  9208. this.size = source.size;
  9209. this.sizeAttenuation = source.sizeAttenuation;
  9210. return this;
  9211. };
  9212. /**
  9213. * Uniform Utilities
  9214. */
  9215. var UniformsUtils = {
  9216. merge: function ( uniforms ) {
  9217. var merged = {};
  9218. for ( var u = 0; u < uniforms.length; u ++ ) {
  9219. var tmp = this.clone( uniforms[ u ] );
  9220. for ( var p in tmp ) {
  9221. merged[ p ] = tmp[ p ];
  9222. }
  9223. }
  9224. return merged;
  9225. },
  9226. clone: function ( uniforms_src ) {
  9227. var uniforms_dst = {};
  9228. for ( var u in uniforms_src ) {
  9229. uniforms_dst[ u ] = {};
  9230. for ( var p in uniforms_src[ u ] ) {
  9231. var parameter_src = uniforms_src[ u ][ p ];
  9232. if ( parameter_src && ( parameter_src.isColor ||
  9233. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  9234. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  9235. parameter_src.isTexture ) ) {
  9236. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9237. } else if ( Array.isArray( parameter_src ) ) {
  9238. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9239. } else {
  9240. uniforms_dst[ u ][ p ] = parameter_src;
  9241. }
  9242. }
  9243. }
  9244. return uniforms_dst;
  9245. }
  9246. };
  9247. /**
  9248. * @author alteredq / http://alteredqualia.com/
  9249. *
  9250. * parameters = {
  9251. * defines: { "label" : "value" },
  9252. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  9253. *
  9254. * fragmentShader: <string>,
  9255. * vertexShader: <string>,
  9256. *
  9257. * wireframe: <boolean>,
  9258. * wireframeLinewidth: <float>,
  9259. *
  9260. * lights: <bool>,
  9261. *
  9262. * skinning: <bool>,
  9263. * morphTargets: <bool>,
  9264. * morphNormals: <bool>
  9265. * }
  9266. */
  9267. function ShaderMaterial( parameters ) {
  9268. Material.call( this );
  9269. this.type = 'ShaderMaterial';
  9270. this.defines = {};
  9271. this.uniforms = {};
  9272. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  9273. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  9274. this.linewidth = 1;
  9275. this.wireframe = false;
  9276. this.wireframeLinewidth = 1;
  9277. this.fog = false; // set to use scene fog
  9278. this.lights = false; // set to use scene lights
  9279. this.clipping = false; // set to use user-defined clipping planes
  9280. this.skinning = false; // set to use skinning attribute streams
  9281. this.morphTargets = false; // set to use morph targets
  9282. this.morphNormals = false; // set to use morph normals
  9283. this.extensions = {
  9284. derivatives: false, // set to use derivatives
  9285. fragDepth: false, // set to use fragment depth values
  9286. drawBuffers: false, // set to use draw buffers
  9287. shaderTextureLOD: false // set to use shader texture LOD
  9288. };
  9289. // When rendered geometry doesn't include these attributes but the material does,
  9290. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9291. this.defaultAttributeValues = {
  9292. 'color': [ 1, 1, 1 ],
  9293. 'uv': [ 0, 0 ],
  9294. 'uv2': [ 0, 0 ]
  9295. };
  9296. this.index0AttributeName = undefined;
  9297. if ( parameters !== undefined ) {
  9298. if ( parameters.attributes !== undefined ) {
  9299. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  9300. }
  9301. this.setValues( parameters );
  9302. }
  9303. }
  9304. ShaderMaterial.prototype = Object.create( Material.prototype );
  9305. ShaderMaterial.prototype.constructor = ShaderMaterial;
  9306. ShaderMaterial.prototype.isShaderMaterial = true;
  9307. ShaderMaterial.prototype.copy = function ( source ) {
  9308. Material.prototype.copy.call( this, source );
  9309. this.fragmentShader = source.fragmentShader;
  9310. this.vertexShader = source.vertexShader;
  9311. this.uniforms = UniformsUtils.clone( source.uniforms );
  9312. this.defines = source.defines;
  9313. this.wireframe = source.wireframe;
  9314. this.wireframeLinewidth = source.wireframeLinewidth;
  9315. this.lights = source.lights;
  9316. this.clipping = source.clipping;
  9317. this.skinning = source.skinning;
  9318. this.morphTargets = source.morphTargets;
  9319. this.morphNormals = source.morphNormals;
  9320. this.extensions = source.extensions;
  9321. return this;
  9322. };
  9323. ShaderMaterial.prototype.toJSON = function ( meta ) {
  9324. var data = Material.prototype.toJSON.call( this, meta );
  9325. data.uniforms = this.uniforms;
  9326. data.vertexShader = this.vertexShader;
  9327. data.fragmentShader = this.fragmentShader;
  9328. return data;
  9329. };
  9330. /**
  9331. * @author bhouston / http://clara.io
  9332. */
  9333. function Box2( min, max ) {
  9334. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  9335. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  9336. }
  9337. Box2.prototype = {
  9338. constructor: Box2,
  9339. set: function ( min, max ) {
  9340. this.min.copy( min );
  9341. this.max.copy( max );
  9342. return this;
  9343. },
  9344. setFromPoints: function ( points ) {
  9345. this.makeEmpty();
  9346. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9347. this.expandByPoint( points[ i ] );
  9348. }
  9349. return this;
  9350. },
  9351. setFromCenterAndSize: function () {
  9352. var v1 = new Vector2();
  9353. return function setFromCenterAndSize( center, size ) {
  9354. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  9355. this.min.copy( center ).sub( halfSize );
  9356. this.max.copy( center ).add( halfSize );
  9357. return this;
  9358. };
  9359. }(),
  9360. clone: function () {
  9361. return new this.constructor().copy( this );
  9362. },
  9363. copy: function ( box ) {
  9364. this.min.copy( box.min );
  9365. this.max.copy( box.max );
  9366. return this;
  9367. },
  9368. makeEmpty: function () {
  9369. this.min.x = this.min.y = + Infinity;
  9370. this.max.x = this.max.y = - Infinity;
  9371. return this;
  9372. },
  9373. isEmpty: function () {
  9374. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  9375. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  9376. },
  9377. getCenter: function ( optionalTarget ) {
  9378. var result = optionalTarget || new Vector2();
  9379. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  9380. },
  9381. getSize: function ( optionalTarget ) {
  9382. var result = optionalTarget || new Vector2();
  9383. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  9384. },
  9385. expandByPoint: function ( point ) {
  9386. this.min.min( point );
  9387. this.max.max( point );
  9388. return this;
  9389. },
  9390. expandByVector: function ( vector ) {
  9391. this.min.sub( vector );
  9392. this.max.add( vector );
  9393. return this;
  9394. },
  9395. expandByScalar: function ( scalar ) {
  9396. this.min.addScalar( - scalar );
  9397. this.max.addScalar( scalar );
  9398. return this;
  9399. },
  9400. containsPoint: function ( point ) {
  9401. return point.x < this.min.x || point.x > this.max.x ||
  9402. point.y < this.min.y || point.y > this.max.y ? false : true;
  9403. },
  9404. containsBox: function ( box ) {
  9405. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  9406. this.min.y <= box.min.y && box.max.y <= this.max.y;
  9407. },
  9408. getParameter: function ( point, optionalTarget ) {
  9409. // This can potentially have a divide by zero if the box
  9410. // has a size dimension of 0.
  9411. var result = optionalTarget || new Vector2();
  9412. return result.set(
  9413. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  9414. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  9415. );
  9416. },
  9417. intersectsBox: function ( box ) {
  9418. // using 6 splitting planes to rule out intersections.
  9419. return box.max.x < this.min.x || box.min.x > this.max.x ||
  9420. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  9421. },
  9422. clampPoint: function ( point, optionalTarget ) {
  9423. var result = optionalTarget || new Vector2();
  9424. return result.copy( point ).clamp( this.min, this.max );
  9425. },
  9426. distanceToPoint: function () {
  9427. var v1 = new Vector2();
  9428. return function distanceToPoint( point ) {
  9429. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  9430. return clampedPoint.sub( point ).length();
  9431. };
  9432. }(),
  9433. intersect: function ( box ) {
  9434. this.min.max( box.min );
  9435. this.max.min( box.max );
  9436. return this;
  9437. },
  9438. union: function ( box ) {
  9439. this.min.min( box.min );
  9440. this.max.max( box.max );
  9441. return this;
  9442. },
  9443. translate: function ( offset ) {
  9444. this.min.add( offset );
  9445. this.max.add( offset );
  9446. return this;
  9447. },
  9448. equals: function ( box ) {
  9449. return box.min.equals( this.min ) && box.max.equals( this.max );
  9450. }
  9451. };
  9452. /**
  9453. * @author bhouston / http://clara.io
  9454. */
  9455. function Line3( start, end ) {
  9456. this.start = ( start !== undefined ) ? start : new Vector3();
  9457. this.end = ( end !== undefined ) ? end : new Vector3();
  9458. }
  9459. Line3.prototype = {
  9460. constructor: Line3,
  9461. set: function ( start, end ) {
  9462. this.start.copy( start );
  9463. this.end.copy( end );
  9464. return this;
  9465. },
  9466. clone: function () {
  9467. return new this.constructor().copy( this );
  9468. },
  9469. copy: function ( line ) {
  9470. this.start.copy( line.start );
  9471. this.end.copy( line.end );
  9472. return this;
  9473. },
  9474. getCenter: function ( optionalTarget ) {
  9475. var result = optionalTarget || new Vector3();
  9476. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  9477. },
  9478. delta: function ( optionalTarget ) {
  9479. var result = optionalTarget || new Vector3();
  9480. return result.subVectors( this.end, this.start );
  9481. },
  9482. distanceSq: function () {
  9483. return this.start.distanceToSquared( this.end );
  9484. },
  9485. distance: function () {
  9486. return this.start.distanceTo( this.end );
  9487. },
  9488. at: function ( t, optionalTarget ) {
  9489. var result = optionalTarget || new Vector3();
  9490. return this.delta( result ).multiplyScalar( t ).add( this.start );
  9491. },
  9492. closestPointToPointParameter: function () {
  9493. var startP = new Vector3();
  9494. var startEnd = new Vector3();
  9495. return function closestPointToPointParameter( point, clampToLine ) {
  9496. startP.subVectors( point, this.start );
  9497. startEnd.subVectors( this.end, this.start );
  9498. var startEnd2 = startEnd.dot( startEnd );
  9499. var startEnd_startP = startEnd.dot( startP );
  9500. var t = startEnd_startP / startEnd2;
  9501. if ( clampToLine ) {
  9502. t = _Math.clamp( t, 0, 1 );
  9503. }
  9504. return t;
  9505. };
  9506. }(),
  9507. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  9508. var t = this.closestPointToPointParameter( point, clampToLine );
  9509. var result = optionalTarget || new Vector3();
  9510. return this.delta( result ).multiplyScalar( t ).add( this.start );
  9511. },
  9512. applyMatrix4: function ( matrix ) {
  9513. this.start.applyMatrix4( matrix );
  9514. this.end.applyMatrix4( matrix );
  9515. return this;
  9516. },
  9517. equals: function ( line ) {
  9518. return line.start.equals( this.start ) && line.end.equals( this.end );
  9519. }
  9520. };
  9521. /**
  9522. * @author bhouston / http://clara.io
  9523. */
  9524. function Plane( normal, constant ) {
  9525. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  9526. this.constant = ( constant !== undefined ) ? constant : 0;
  9527. }
  9528. Plane.prototype = {
  9529. constructor: Plane,
  9530. set: function ( normal, constant ) {
  9531. this.normal.copy( normal );
  9532. this.constant = constant;
  9533. return this;
  9534. },
  9535. setComponents: function ( x, y, z, w ) {
  9536. this.normal.set( x, y, z );
  9537. this.constant = w;
  9538. return this;
  9539. },
  9540. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  9541. this.normal.copy( normal );
  9542. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  9543. return this;
  9544. },
  9545. setFromCoplanarPoints: function () {
  9546. var v1 = new Vector3();
  9547. var v2 = new Vector3();
  9548. return function setFromCoplanarPoints( a, b, c ) {
  9549. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  9550. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  9551. this.setFromNormalAndCoplanarPoint( normal, a );
  9552. return this;
  9553. };
  9554. }(),
  9555. clone: function () {
  9556. return new this.constructor().copy( this );
  9557. },
  9558. copy: function ( plane ) {
  9559. this.normal.copy( plane.normal );
  9560. this.constant = plane.constant;
  9561. return this;
  9562. },
  9563. normalize: function () {
  9564. // Note: will lead to a divide by zero if the plane is invalid.
  9565. var inverseNormalLength = 1.0 / this.normal.length();
  9566. this.normal.multiplyScalar( inverseNormalLength );
  9567. this.constant *= inverseNormalLength;
  9568. return this;
  9569. },
  9570. negate: function () {
  9571. this.constant *= - 1;
  9572. this.normal.negate();
  9573. return this;
  9574. },
  9575. distanceToPoint: function ( point ) {
  9576. return this.normal.dot( point ) + this.constant;
  9577. },
  9578. distanceToSphere: function ( sphere ) {
  9579. return this.distanceToPoint( sphere.center ) - sphere.radius;
  9580. },
  9581. projectPoint: function ( point, optionalTarget ) {
  9582. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  9583. },
  9584. orthoPoint: function ( point, optionalTarget ) {
  9585. var perpendicularMagnitude = this.distanceToPoint( point );
  9586. var result = optionalTarget || new Vector3();
  9587. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  9588. },
  9589. intersectLine: function () {
  9590. var v1 = new Vector3();
  9591. return function intersectLine( line, optionalTarget ) {
  9592. var result = optionalTarget || new Vector3();
  9593. var direction = line.delta( v1 );
  9594. var denominator = this.normal.dot( direction );
  9595. if ( denominator === 0 ) {
  9596. // line is coplanar, return origin
  9597. if ( this.distanceToPoint( line.start ) === 0 ) {
  9598. return result.copy( line.start );
  9599. }
  9600. // Unsure if this is the correct method to handle this case.
  9601. return undefined;
  9602. }
  9603. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  9604. if ( t < 0 || t > 1 ) {
  9605. return undefined;
  9606. }
  9607. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  9608. };
  9609. }(),
  9610. intersectsLine: function ( line ) {
  9611. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  9612. var startSign = this.distanceToPoint( line.start );
  9613. var endSign = this.distanceToPoint( line.end );
  9614. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  9615. },
  9616. intersectsBox: function ( box ) {
  9617. return box.intersectsPlane( this );
  9618. },
  9619. intersectsSphere: function ( sphere ) {
  9620. return sphere.intersectsPlane( this );
  9621. },
  9622. coplanarPoint: function ( optionalTarget ) {
  9623. var result = optionalTarget || new Vector3();
  9624. return result.copy( this.normal ).multiplyScalar( - this.constant );
  9625. },
  9626. applyMatrix4: function () {
  9627. var v1 = new Vector3();
  9628. var m1 = new Matrix3();
  9629. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  9630. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  9631. // transform normal based on theory here:
  9632. // http://www.songho.ca/opengl/gl_normaltransform.html
  9633. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  9634. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  9635. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  9636. this.constant = - referencePoint.dot( normal );
  9637. return this;
  9638. };
  9639. }(),
  9640. translate: function ( offset ) {
  9641. this.constant = this.constant - offset.dot( this.normal );
  9642. return this;
  9643. },
  9644. equals: function ( plane ) {
  9645. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  9646. }
  9647. };
  9648. /**
  9649. * @author mikael emtinger / http://gomo.se/
  9650. * @author alteredq / http://alteredqualia.com/
  9651. * @author mrdoob / http://mrdoob.com/
  9652. */
  9653. function LOD() {
  9654. Object3D.call( this );
  9655. this.type = 'LOD';
  9656. Object.defineProperties( this, {
  9657. levels: {
  9658. enumerable: true,
  9659. value: []
  9660. }
  9661. } );
  9662. }
  9663. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9664. constructor: LOD,
  9665. copy: function ( source ) {
  9666. Object3D.prototype.copy.call( this, source, false );
  9667. var levels = source.levels;
  9668. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  9669. var level = levels[ i ];
  9670. this.addLevel( level.object.clone(), level.distance );
  9671. }
  9672. return this;
  9673. },
  9674. addLevel: function ( object, distance ) {
  9675. if ( distance === undefined ) distance = 0;
  9676. distance = Math.abs( distance );
  9677. var levels = this.levels;
  9678. for ( var l = 0; l < levels.length; l ++ ) {
  9679. if ( distance < levels[ l ].distance ) {
  9680. break;
  9681. }
  9682. }
  9683. levels.splice( l, 0, { distance: distance, object: object } );
  9684. this.add( object );
  9685. },
  9686. getObjectForDistance: function ( distance ) {
  9687. var levels = this.levels;
  9688. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  9689. if ( distance < levels[ i ].distance ) {
  9690. break;
  9691. }
  9692. }
  9693. return levels[ i - 1 ].object;
  9694. },
  9695. raycast: ( function () {
  9696. var matrixPosition = new Vector3();
  9697. return function raycast( raycaster, intersects ) {
  9698. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9699. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  9700. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  9701. };
  9702. }() ),
  9703. update: function () {
  9704. var v1 = new Vector3();
  9705. var v2 = new Vector3();
  9706. return function update( camera ) {
  9707. var levels = this.levels;
  9708. if ( levels.length > 1 ) {
  9709. v1.setFromMatrixPosition( camera.matrixWorld );
  9710. v2.setFromMatrixPosition( this.matrixWorld );
  9711. var distance = v1.distanceTo( v2 );
  9712. levels[ 0 ].object.visible = true;
  9713. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  9714. if ( distance >= levels[ i ].distance ) {
  9715. levels[ i - 1 ].object.visible = false;
  9716. levels[ i ].object.visible = true;
  9717. } else {
  9718. break;
  9719. }
  9720. }
  9721. for ( ; i < l; i ++ ) {
  9722. levels[ i ].object.visible = false;
  9723. }
  9724. }
  9725. };
  9726. }(),
  9727. toJSON: function ( meta ) {
  9728. var data = Object3D.prototype.toJSON.call( this, meta );
  9729. data.object.levels = [];
  9730. var levels = this.levels;
  9731. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  9732. var level = levels[ i ];
  9733. data.object.levels.push( {
  9734. object: level.object.uuid,
  9735. distance: level.distance
  9736. } );
  9737. }
  9738. return data;
  9739. }
  9740. } );
  9741. /**
  9742. * @author alteredq / http://alteredqualia.com/
  9743. */
  9744. function Points( geometry, material ) {
  9745. Object3D.call( this );
  9746. this.type = 'Points';
  9747. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  9748. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  9749. }
  9750. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9751. constructor: Points,
  9752. isPoints: true,
  9753. raycast: ( function () {
  9754. var inverseMatrix = new Matrix4();
  9755. var ray = new Ray();
  9756. var sphere = new Sphere();
  9757. return function raycast( raycaster, intersects ) {
  9758. var object = this;
  9759. var geometry = this.geometry;
  9760. var matrixWorld = this.matrixWorld;
  9761. var threshold = raycaster.params.Points.threshold;
  9762. // Checking boundingSphere distance to ray
  9763. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9764. sphere.copy( geometry.boundingSphere );
  9765. sphere.applyMatrix4( matrixWorld );
  9766. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  9767. //
  9768. inverseMatrix.getInverse( matrixWorld );
  9769. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9770. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9771. var localThresholdSq = localThreshold * localThreshold;
  9772. var position = new Vector3();
  9773. function testPoint( point, index ) {
  9774. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  9775. if ( rayPointDistanceSq < localThresholdSq ) {
  9776. var intersectPoint = ray.closestPointToPoint( point );
  9777. intersectPoint.applyMatrix4( matrixWorld );
  9778. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  9779. if ( distance < raycaster.near || distance > raycaster.far ) return;
  9780. intersects.push( {
  9781. distance: distance,
  9782. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  9783. point: intersectPoint.clone(),
  9784. index: index,
  9785. face: null,
  9786. object: object
  9787. } );
  9788. }
  9789. }
  9790. if ( geometry.isBufferGeometry ) {
  9791. var index = geometry.index;
  9792. var attributes = geometry.attributes;
  9793. var positions = attributes.position.array;
  9794. if ( index !== null ) {
  9795. var indices = index.array;
  9796. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  9797. var a = indices[ i ];
  9798. position.fromArray( positions, a * 3 );
  9799. testPoint( position, a );
  9800. }
  9801. } else {
  9802. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  9803. position.fromArray( positions, i * 3 );
  9804. testPoint( position, i );
  9805. }
  9806. }
  9807. } else {
  9808. var vertices = geometry.vertices;
  9809. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  9810. testPoint( vertices[ i ], i );
  9811. }
  9812. }
  9813. };
  9814. }() ),
  9815. clone: function () {
  9816. return new this.constructor( this.geometry, this.material ).copy( this );
  9817. }
  9818. } );
  9819. /**
  9820. * @author alteredq / http://alteredqualia.com/
  9821. *
  9822. * parameters = {
  9823. * color: <hex>,
  9824. * opacity: <float>,
  9825. * map: new THREE.Texture( <Image> ),
  9826. *
  9827. * uvOffset: new THREE.Vector2(),
  9828. * uvScale: new THREE.Vector2()
  9829. * }
  9830. */
  9831. function SpriteMaterial( parameters ) {
  9832. Material.call( this );
  9833. this.type = 'SpriteMaterial';
  9834. this.color = new Color( 0xffffff );
  9835. this.map = null;
  9836. this.rotation = 0;
  9837. this.fog = false;
  9838. this.lights = false;
  9839. this.setValues( parameters );
  9840. }
  9841. SpriteMaterial.prototype = Object.create( Material.prototype );
  9842. SpriteMaterial.prototype.constructor = SpriteMaterial;
  9843. SpriteMaterial.prototype.copy = function ( source ) {
  9844. Material.prototype.copy.call( this, source );
  9845. this.color.copy( source.color );
  9846. this.map = source.map;
  9847. this.rotation = source.rotation;
  9848. return this;
  9849. };
  9850. /**
  9851. * @author mikael emtinger / http://gomo.se/
  9852. * @author alteredq / http://alteredqualia.com/
  9853. */
  9854. function Sprite( material ) {
  9855. Object3D.call( this );
  9856. this.type = 'Sprite';
  9857. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  9858. }
  9859. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9860. constructor: Sprite,
  9861. isSprite: true,
  9862. raycast: ( function () {
  9863. var matrixPosition = new Vector3();
  9864. return function raycast( raycaster, intersects ) {
  9865. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9866. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  9867. var guessSizeSq = this.scale.x * this.scale.y / 4;
  9868. if ( distanceSq > guessSizeSq ) {
  9869. return;
  9870. }
  9871. intersects.push( {
  9872. distance: Math.sqrt( distanceSq ),
  9873. point: this.position,
  9874. face: null,
  9875. object: this
  9876. } );
  9877. };
  9878. }() ),
  9879. clone: function () {
  9880. return new this.constructor( this.material ).copy( this );
  9881. }
  9882. } );
  9883. /**
  9884. * @author tschw
  9885. *
  9886. * Uniforms of a program.
  9887. * Those form a tree structure with a special top-level container for the root,
  9888. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  9889. *
  9890. *
  9891. * Properties of inner nodes including the top-level container:
  9892. *
  9893. * .seq - array of nested uniforms
  9894. * .map - nested uniforms by name
  9895. *
  9896. *
  9897. * Methods of all nodes except the top-level container:
  9898. *
  9899. * .setValue( gl, value, [renderer] )
  9900. *
  9901. * uploads a uniform value(s)
  9902. * the 'renderer' parameter is needed for sampler uniforms
  9903. *
  9904. *
  9905. * Static methods of the top-level container (renderer factorizations):
  9906. *
  9907. * .upload( gl, seq, values, renderer )
  9908. *
  9909. * sets uniforms in 'seq' to 'values[id].value'
  9910. *
  9911. * .seqWithValue( seq, values ) : filteredSeq
  9912. *
  9913. * filters 'seq' entries with corresponding entry in values
  9914. *
  9915. *
  9916. * Methods of the top-level container (renderer factorizations):
  9917. *
  9918. * .setValue( gl, name, value )
  9919. *
  9920. * sets uniform with name 'name' to 'value'
  9921. *
  9922. * .set( gl, obj, prop )
  9923. *
  9924. * sets uniform from object and property with same name than uniform
  9925. *
  9926. * .setOptional( gl, obj, prop )
  9927. *
  9928. * like .set for an optional property of the object
  9929. *
  9930. */
  9931. var emptyTexture = new Texture();
  9932. var emptyCubeTexture = new CubeTexture();
  9933. // --- Base for inner nodes (including the root) ---
  9934. function UniformContainer() {
  9935. this.seq = [];
  9936. this.map = {};
  9937. }
  9938. // --- Utilities ---
  9939. // Array Caches (provide typed arrays for temporary by size)
  9940. var arrayCacheF32 = [];
  9941. var arrayCacheI32 = [];
  9942. // Flattening for arrays of vectors and matrices
  9943. function flatten( array, nBlocks, blockSize ) {
  9944. var firstElem = array[ 0 ];
  9945. if ( firstElem <= 0 || firstElem > 0 ) return array;
  9946. // unoptimized: ! isNaN( firstElem )
  9947. // see http://jacksondunstan.com/articles/983
  9948. var n = nBlocks * blockSize,
  9949. r = arrayCacheF32[ n ];
  9950. if ( r === undefined ) {
  9951. r = new Float32Array( n );
  9952. arrayCacheF32[ n ] = r;
  9953. }
  9954. if ( nBlocks !== 0 ) {
  9955. firstElem.toArray( r, 0 );
  9956. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  9957. offset += blockSize;
  9958. array[ i ].toArray( r, offset );
  9959. }
  9960. }
  9961. return r;
  9962. }
  9963. // Texture unit allocation
  9964. function allocTexUnits( renderer, n ) {
  9965. var r = arrayCacheI32[ n ];
  9966. if ( r === undefined ) {
  9967. r = new Int32Array( n );
  9968. arrayCacheI32[ n ] = r;
  9969. }
  9970. for ( var i = 0; i !== n; ++ i )
  9971. r[ i ] = renderer.allocTextureUnit();
  9972. return r;
  9973. }
  9974. // --- Setters ---
  9975. // Note: Defining these methods externally, because they come in a bunch
  9976. // and this way their names minify.
  9977. // Single scalar
  9978. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  9979. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  9980. // Single float vector (from flat array or THREE.VectorN)
  9981. function setValue2fv( gl, v ) {
  9982. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  9983. else gl.uniform2f( this.addr, v.x, v.y );
  9984. }
  9985. function setValue3fv( gl, v ) {
  9986. if ( v.x !== undefined )
  9987. gl.uniform3f( this.addr, v.x, v.y, v.z );
  9988. else if ( v.r !== undefined )
  9989. gl.uniform3f( this.addr, v.r, v.g, v.b );
  9990. else
  9991. gl.uniform3fv( this.addr, v );
  9992. }
  9993. function setValue4fv( gl, v ) {
  9994. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  9995. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  9996. }
  9997. // Single matrix (from flat array or MatrixN)
  9998. function setValue2fm( gl, v ) {
  9999. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  10000. }
  10001. function setValue3fm( gl, v ) {
  10002. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  10003. }
  10004. function setValue4fm( gl, v ) {
  10005. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  10006. }
  10007. // Single texture (2D / Cube)
  10008. function setValueT1( gl, v, renderer ) {
  10009. var unit = renderer.allocTextureUnit();
  10010. gl.uniform1i( this.addr, unit );
  10011. renderer.setTexture2D( v || emptyTexture, unit );
  10012. }
  10013. function setValueT6( gl, v, renderer ) {
  10014. var unit = renderer.allocTextureUnit();
  10015. gl.uniform1i( this.addr, unit );
  10016. renderer.setTextureCube( v || emptyCubeTexture, unit );
  10017. }
  10018. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10019. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  10020. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  10021. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  10022. // Helper to pick the right setter for the singular case
  10023. function getSingularSetter( type ) {
  10024. switch ( type ) {
  10025. case 0x1406: return setValue1f; // FLOAT
  10026. case 0x8b50: return setValue2fv; // _VEC2
  10027. case 0x8b51: return setValue3fv; // _VEC3
  10028. case 0x8b52: return setValue4fv; // _VEC4
  10029. case 0x8b5a: return setValue2fm; // _MAT2
  10030. case 0x8b5b: return setValue3fm; // _MAT3
  10031. case 0x8b5c: return setValue4fm; // _MAT4
  10032. case 0x8b5e: return setValueT1; // SAMPLER_2D
  10033. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  10034. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  10035. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  10036. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  10037. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  10038. }
  10039. }
  10040. // Array of scalars
  10041. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  10042. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  10043. // Array of vectors (flat or from THREE classes)
  10044. function setValueV2a( gl, v ) {
  10045. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  10046. }
  10047. function setValueV3a( gl, v ) {
  10048. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  10049. }
  10050. function setValueV4a( gl, v ) {
  10051. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  10052. }
  10053. // Array of matrices (flat or from THREE clases)
  10054. function setValueM2a( gl, v ) {
  10055. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  10056. }
  10057. function setValueM3a( gl, v ) {
  10058. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  10059. }
  10060. function setValueM4a( gl, v ) {
  10061. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  10062. }
  10063. // Array of textures (2D / Cube)
  10064. function setValueT1a( gl, v, renderer ) {
  10065. var n = v.length,
  10066. units = allocTexUnits( renderer, n );
  10067. gl.uniform1iv( this.addr, units );
  10068. for ( var i = 0; i !== n; ++ i ) {
  10069. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10070. }
  10071. }
  10072. function setValueT6a( gl, v, renderer ) {
  10073. var n = v.length,
  10074. units = allocTexUnits( renderer, n );
  10075. gl.uniform1iv( this.addr, units );
  10076. for ( var i = 0; i !== n; ++ i ) {
  10077. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10078. }
  10079. }
  10080. // Helper to pick the right setter for a pure (bottom-level) array
  10081. function getPureArraySetter( type ) {
  10082. switch ( type ) {
  10083. case 0x1406: return setValue1fv; // FLOAT
  10084. case 0x8b50: return setValueV2a; // _VEC2
  10085. case 0x8b51: return setValueV3a; // _VEC3
  10086. case 0x8b52: return setValueV4a; // _VEC4
  10087. case 0x8b5a: return setValueM2a; // _MAT2
  10088. case 0x8b5b: return setValueM3a; // _MAT3
  10089. case 0x8b5c: return setValueM4a; // _MAT4
  10090. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  10091. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  10092. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  10093. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  10094. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  10095. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  10096. }
  10097. }
  10098. // --- Uniform Classes ---
  10099. function SingleUniform( id, activeInfo, addr ) {
  10100. this.id = id;
  10101. this.addr = addr;
  10102. this.setValue = getSingularSetter( activeInfo.type );
  10103. // this.path = activeInfo.name; // DEBUG
  10104. }
  10105. function PureArrayUniform( id, activeInfo, addr ) {
  10106. this.id = id;
  10107. this.addr = addr;
  10108. this.size = activeInfo.size;
  10109. this.setValue = getPureArraySetter( activeInfo.type );
  10110. // this.path = activeInfo.name; // DEBUG
  10111. }
  10112. function StructuredUniform( id ) {
  10113. this.id = id;
  10114. UniformContainer.call( this ); // mix-in
  10115. }
  10116. StructuredUniform.prototype.setValue = function( gl, value ) {
  10117. // Note: Don't need an extra 'renderer' parameter, since samplers
  10118. // are not allowed in structured uniforms.
  10119. var seq = this.seq;
  10120. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  10121. var u = seq[ i ];
  10122. u.setValue( gl, value[ u.id ] );
  10123. }
  10124. };
  10125. // --- Top-level ---
  10126. // Parser - builds up the property tree from the path strings
  10127. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  10128. // extracts
  10129. // - the identifier (member name or array index)
  10130. // - followed by an optional right bracket (found when array index)
  10131. // - followed by an optional left bracket or dot (type of subscript)
  10132. //
  10133. // Note: These portions can be read in a non-overlapping fashion and
  10134. // allow straightforward parsing of the hierarchy that WebGL encodes
  10135. // in the uniform names.
  10136. function addUniform( container, uniformObject ) {
  10137. container.seq.push( uniformObject );
  10138. container.map[ uniformObject.id ] = uniformObject;
  10139. }
  10140. function parseUniform( activeInfo, addr, container ) {
  10141. var path = activeInfo.name,
  10142. pathLength = path.length;
  10143. // reset RegExp object, because of the early exit of a previous run
  10144. RePathPart.lastIndex = 0;
  10145. for (; ;) {
  10146. var match = RePathPart.exec( path ),
  10147. matchEnd = RePathPart.lastIndex,
  10148. id = match[ 1 ],
  10149. idIsIndex = match[ 2 ] === ']',
  10150. subscript = match[ 3 ];
  10151. if ( idIsIndex ) id = id | 0; // convert to integer
  10152. if ( subscript === undefined ||
  10153. subscript === '[' && matchEnd + 2 === pathLength ) {
  10154. // bare name or "pure" bottom-level array "[0]" suffix
  10155. addUniform( container, subscript === undefined ?
  10156. new SingleUniform( id, activeInfo, addr ) :
  10157. new PureArrayUniform( id, activeInfo, addr ) );
  10158. break;
  10159. } else {
  10160. // step into inner node / create it in case it doesn't exist
  10161. var map = container.map,
  10162. next = map[ id ];
  10163. if ( next === undefined ) {
  10164. next = new StructuredUniform( id );
  10165. addUniform( container, next );
  10166. }
  10167. container = next;
  10168. }
  10169. }
  10170. }
  10171. // Root Container
  10172. function WebGLUniforms( gl, program, renderer ) {
  10173. UniformContainer.call( this );
  10174. this.renderer = renderer;
  10175. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  10176. for ( var i = 0; i < n; ++ i ) {
  10177. var info = gl.getActiveUniform( program, i ),
  10178. path = info.name,
  10179. addr = gl.getUniformLocation( program, path );
  10180. parseUniform( info, addr, this );
  10181. }
  10182. }
  10183. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  10184. var u = this.map[ name ];
  10185. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  10186. };
  10187. WebGLUniforms.prototype.set = function( gl, object, name ) {
  10188. var u = this.map[ name ];
  10189. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  10190. };
  10191. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  10192. var v = object[ name ];
  10193. if ( v !== undefined ) this.setValue( gl, name, v );
  10194. };
  10195. // Static interface
  10196. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  10197. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  10198. var u = seq[ i ],
  10199. v = values[ u.id ];
  10200. if ( v.needsUpdate !== false ) {
  10201. // note: always updating when .needsUpdate is undefined
  10202. u.setValue( gl, v.value, renderer );
  10203. }
  10204. }
  10205. };
  10206. WebGLUniforms.seqWithValue = function( seq, values ) {
  10207. var r = [];
  10208. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  10209. var u = seq[ i ];
  10210. if ( u.id in values ) r.push( u );
  10211. }
  10212. return r;
  10213. };
  10214. var alphamap_fragment = "#ifdef USE_ALPHAMAP\r\n\r\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\r\n\r\n#endif\r\n";
  10215. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\r\n\r\n\tuniform sampler2D alphaMap;\r\n\r\n#endif\r\n";
  10216. var alphatest_fragment = "#ifdef ALPHATEST\r\n\r\n\tif ( diffuseColor.a < ALPHATEST ) discard;\r\n\r\n#endif\r\n";
  10217. var aomap_fragment = "#ifdef USE_AOMAP\r\n\r\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\r\n\r\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\r\n\r\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\r\n\r\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\r\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  10218. var aomap_pars_fragment = "#ifdef USE_AOMAP\r\n\r\n\tuniform sampler2D aoMap;\r\n\tuniform float aoMapIntensity;\r\n\r\n#endif";
  10219. var begin_vertex = "\r\nvec3 transformed = vec3( position );\r\n";
  10220. var beginnormal_vertex = "\r\nvec3 objectNormal = vec3( normal );\r\n";
  10221. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\r\n\r\n\t\tif( decayExponent > 0.0 ) {\r\n\r\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\r\n\r\n\t\t\t// based upon Frostbite 3 Moving to Physically-based Rendering\r\n\t\t\t// page 32, equation 26: E[window1]\r\n\t\t\t// http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\r\n\t\t\t// this is intended to be used on spot and point lights who are represented as luminous intensity\r\n\t\t\t// but who must be converted to luminous irradiance for surface lighting calculation\r\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\r\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\r\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\r\n\r\n#else\r\n\r\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\r\n\r\n#endif\r\n\r\n\t\t}\r\n\r\n\t\treturn 1.0;\r\n}\r\n\r\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\r\n\r\n\treturn RECIPROCAL_PI * diffuseColor;\r\n\r\n} // validated\r\n\r\n\r\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\r\n\r\n\t// Original approximation by Christophe Schlick '94\r\n\t//;float fresnel = pow( 1.0 - dotLH, 5.0 );\r\n\r\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\r\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\r\n\r\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\r\n\r\n} // validated\r\n\r\n\r\n// Microfacet Models for Refraction through Rough Surfaces - equation (34)\r\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\r\n// alpha is \"roughness squared\" in Disney’s reparameterization\r\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\r\n\r\n\t// geometry term = G(l)⋅G(v) / 4(n⋅l)(n⋅v)\r\n\r\n\tfloat a2 = pow2( alpha );\r\n\r\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\r\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\r\n\r\n\treturn 1.0 / ( gl * gv );\r\n\r\n} // validated\r\n\r\n// from page 12, listing 2 of http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\r\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\r\n\r\n\tfloat a2 = pow2( alpha );\r\n\r\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\r\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\r\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\r\n\r\n\treturn 0.5 / max( gv + gl, EPSILON );\r\n}\r\n\r\n\r\n\r\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\r\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\r\n// alpha is \"roughness squared\" in Disney’s reparameterization\r\nfloat D_GGX( const in float alpha, const in float dotNH ) {\r\n\r\n\tfloat a2 = pow2( alpha );\r\n\r\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1\r\n\r\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\r\n\r\n}\r\n\r\n\r\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\r\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\r\n\r\n\tfloat alpha = pow2( roughness ); // UE4's roughness\r\n\r\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\r\n\r\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\r\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\r\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\r\n\r\n\tvec3 F = F_Schlick( specularColor, dotLH );\r\n\r\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\r\n\r\n\tfloat D = D_GGX( alpha, dotNH );\r\n\r\n\treturn F * ( G * D );\r\n\r\n} // validated\r\n\r\n//\r\n// Rect Area Light BRDF Approximations\r\n//\r\n\r\n// Area light computation code adapted from:\r\n// http://blog.selfshadow.com/sandbox/ltc.html\r\n//\r\n// Based on paper:\r\n// Real-Time Polygonal-Light Shading with Linearly Transformed Cosines\r\n// By: Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt\r\n// https://eheitzresearch.wordpress.com/415-2/\r\n\r\nvec2 ltcTextureCoords( const in GeometricContext geometry, const in float roughness ) {\r\n\r\n\tconst float LUT_SIZE = 64.0;\r\n\tconst float LUT_SCALE = (LUT_SIZE - 1.0)/LUT_SIZE;\r\n\tconst float LUT_BIAS = 0.5/LUT_SIZE;\r\n\r\n\tvec3 N = geometry.normal;\r\n\tvec3 V = geometry.viewDir;\r\n\tvec3 P = geometry.position;\r\n\r\n\t// view angle on surface determines which LTC BRDF values we use\r\n\tfloat theta = acos( dot( N, V ) );\r\n\r\n\t// Parameterization of texture:\r\n\t// sqrt(roughness) -> [0,1]\r\n\t// theta -> [0, PI/2]\r\n\tvec2 uv = vec2(\r\n\t\tsqrt( saturate( roughness ) ),\r\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\r\n\r\n\t// Ensure we don't have nonlinearities at the look-up table's edges\r\n\t// see: http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter24.html\r\n\t// \"Shader Analysis\" section\r\n\tuv = uv * LUT_SCALE + LUT_BIAS;\r\n\r\n\treturn uv;\r\n\r\n}\r\n\r\nvoid clipQuadToHorizon( inout vec3 L[5], out int n ) {\r\n\r\n\t// detect clipping config\r\n\tint config = 0;\r\n\tif ( L[0].z > 0.0 ) config += 1;\r\n\tif ( L[1].z > 0.0 ) config += 2;\r\n\tif ( L[2].z > 0.0 ) config += 4;\r\n\tif ( L[3].z > 0.0 ) config += 8;\r\n\r\n\t// clip\r\n\tn = 0;\r\n\r\n\tif ( config == 0 ) {\r\n\r\n\t\t// clip all\r\n\r\n\t} else if ( config == 1 ) {\r\n\r\n\t\t// V1 clip V2 V3 V4\r\n\t\tn = 3;\r\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\r\n\t\tL[2] = -L[3].z * L[0] + L[0].z * L[3];\r\n\r\n\t} else if ( config == 2 ) {\r\n\r\n\t\t// V2 clip V1 V3 V4\r\n\t\tn = 3;\r\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\r\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\r\n\r\n\t} else if ( config == 3 ) {\r\n\r\n\t\t// V1 V2 clip V3 V4\r\n\t\tn = 4;\r\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\r\n\t\tL[3] = -L[3].z * L[0] + L[0].z * L[3];\r\n\r\n\t} else if ( config == 4 ) {\r\n\r\n\t\t// V3 clip V1 V2 V4\r\n\t\tn = 3;\r\n\t\tL[0] = -L[3].z * L[2] + L[2].z * L[3];\r\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\r\n\r\n\t} else if ( config == 5 ) {\r\n\r\n\t\t// V1 V3 clip V2 V4) impossible\r\n\t\tn = 0;\r\n\r\n\t} else if ( config == 6 ) {\r\n\r\n\t\t// V2 V3 clip V1 V4\r\n\t\tn = 4;\r\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\r\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\r\n\r\n\t} else if ( config == 7 ) {\r\n\r\n\t\t// V1 V2 V3 clip V4\r\n\t\tn = 5;\r\n\t\tL[4] = -L[3].z * L[0] + L[0].z * L[3];\r\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\r\n\r\n\t} else if ( config == 8 ) {\r\n\r\n\t\t// V4 clip V1 V2 V3\r\n\t\tn = 3;\r\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\r\n\t\tL[1] = -L[2].z * L[3] + L[3].z * L[2];\r\n\t\tL[2] = L[3];\r\n\r\n\t} else if ( config == 9 ) {\r\n\r\n\t\t// V1 V4 clip V2 V3\r\n\t\tn = 4;\r\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\r\n\t\tL[2] = -L[2].z * L[3] + L[3].z * L[2];\r\n\r\n\t} else if ( config == 10 ) {\r\n\r\n\t\t// V2 V4 clip V1 V3) impossible\r\n\t\tn = 0;\r\n\r\n\t} else if ( config == 11 ) {\r\n\r\n\t\t// V1 V2 V4 clip V3\r\n\t\tn = 5;\r\n\t\tL[4] = L[3];\r\n\t\tL[3] = -L[2].z * L[3] + L[3].z * L[2];\r\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\r\n\r\n\t} else if ( config == 12 ) {\r\n\r\n\t\t// V3 V4 clip V1 V2\r\n\t\tn = 4;\r\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\r\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\r\n\r\n\t} else if ( config == 13 ) {\r\n\r\n\t\t// V1 V3 V4 clip V2\r\n\t\tn = 5;\r\n\t\tL[4] = L[3];\r\n\t\tL[3] = L[2];\r\n\t\tL[2] = -L[1].z * L[2] + L[2].z * L[1];\r\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\r\n\r\n\t} else if ( config == 14 ) {\r\n\r\n\t\t// V2 V3 V4 clip V1\r\n\t\tn = 5;\r\n\t\tL[4] = -L[0].z * L[3] + L[3].z * L[0];\r\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\r\n\r\n\t} else if ( config == 15 ) {\r\n\r\n\t\t// V1 V2 V3 V4\r\n\t\tn = 4;\r\n\r\n\t}\r\n\r\n\tif ( n == 3 )\r\n\t\tL[3] = L[0];\r\n\tif ( n == 4 )\r\n\t\tL[4] = L[0];\r\n\r\n}\r\n\r\n// Equation (11) of \"Real-Time Polygonal-Light Shading with Linearly Transformed Cosines\"\r\nfloat integrateLtcBrdfOverRectEdge( vec3 v1, vec3 v2 ) {\r\n\r\n\tfloat cosTheta = dot( v1, v2 );\r\n\tfloat theta = acos( cosTheta );\r\n\tfloat res = cross( v1, v2 ).z * ( ( theta > 0.001 ) ? theta / sin( theta ) : 1.0 );\r\n\r\n\treturn res;\r\n\r\n}\r\n\r\nvoid initRectPoints( const in vec3 pos, const in vec3 halfWidth, const in vec3 halfHeight, out vec3 rectPoints[4] ) {\r\n\r\n\trectPoints[0] = pos - halfWidth - halfHeight;\r\n\trectPoints[1] = pos + halfWidth - halfHeight;\r\n\trectPoints[2] = pos + halfWidth + halfHeight;\r\n\trectPoints[3] = pos - halfWidth + halfHeight;\r\n\r\n}\r\n\r\nvec3 integrateLtcBrdfOverRect( const in GeometricContext geometry, const in mat3 brdfMat, const in vec3 rectPoints[4] ) {\r\n\r\n\tvec3 N = geometry.normal;\r\n\tvec3 V = geometry.viewDir;\r\n\tvec3 P = geometry.position;\r\n\r\n\t// construct orthonormal basis around N\r\n\tvec3 T1, T2;\r\n\tT1 = normalize(V - N * dot( V, N ));\r\n\t// TODO (abelnation): I had to negate this cross product to get proper light. Curious why sample code worked without negation\r\n\tT2 = - cross( N, T1 );\r\n\r\n\t// rotate area light in (T1, T2, N) basis\r\n\tmat3 brdfWrtSurface = brdfMat * transpose( mat3( T1, T2, N ) );\r\n\r\n\t// transformed rect relative to surface point\r\n\tvec3 clippedRect[5];\r\n\tclippedRect[0] = brdfWrtSurface * ( rectPoints[0] - P );\r\n\tclippedRect[1] = brdfWrtSurface * ( rectPoints[1] - P );\r\n\tclippedRect[2] = brdfWrtSurface * ( rectPoints[2] - P );\r\n\tclippedRect[3] = brdfWrtSurface * ( rectPoints[3] - P );\r\n\r\n\t// clip light rect to horizon, resulting in at most 5 points\r\n\t// we do this because we are integrating the BRDF over the hemisphere centered on the surface points normal\r\n\tint n;\r\n\tclipQuadToHorizon(clippedRect, n);\r\n\r\n\t// light is completely below horizon\r\n\tif ( n == 0 )\r\n\t\treturn vec3( 0, 0, 0 );\r\n\r\n\t// project clipped rect onto sphere\r\n\tclippedRect[0] = normalize( clippedRect[0] );\r\n\tclippedRect[1] = normalize( clippedRect[1] );\r\n\tclippedRect[2] = normalize( clippedRect[2] );\r\n\tclippedRect[3] = normalize( clippedRect[3] );\r\n\tclippedRect[4] = normalize( clippedRect[4] );\r\n\r\n\t// integrate\r\n\t// simplified integration only needs to be evaluated for each edge in the polygon\r\n\tfloat sum = 0.0;\r\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[0], clippedRect[1] );\r\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[1], clippedRect[2] );\r\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[2], clippedRect[3] );\r\n\tif (n >= 4)\r\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[3], clippedRect[4] );\r\n\tif (n == 5)\r\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[4], clippedRect[0] );\r\n\r\n\t// TODO (abelnation): two-sided area light\r\n\t// sum = twoSided ? abs(sum) : max(0.0, sum);\r\n\tsum = max( 0.0, sum );\r\n\t// sum = abs( sum );\r\n\r\n\tvec3 Lo_i = vec3( sum, sum, sum );\r\n\r\n\treturn Lo_i;\r\n\r\n}\r\n\r\nvec3 Rect_Area_Light_Specular_Reflectance(\r\n\t\tconst in GeometricContext geometry,\r\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight,\r\n\t\tconst in float roughness,\r\n\t\tconst in sampler2D ltcMat, const in sampler2D ltcMag ) {\r\n\r\n\tvec3 rectPoints[4];\r\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\r\n\r\n\tvec2 uv = ltcTextureCoords( geometry, roughness );\r\n\r\n\tvec4 brdfLtcApproxParams, t;\r\n\r\n\tbrdfLtcApproxParams = texture2D( ltcMat, uv );\r\n\tt = texture2D( ltcMat, uv );\r\n\r\n\tfloat brdfLtcScalar = texture2D( ltcMag, uv ).a;\r\n\r\n\t// inv(M) matrix referenced by equation (6) in paper\r\n\tmat3 brdfLtcApproxMat = mat3(\r\n\t\tvec3( 1, 0, t.y ),\r\n\t\tvec3( 0, t.z, 0 ),\r\n\t\tvec3( t.w, 0, t.x )\r\n\t);\r\n\r\n\tvec3 specularReflectance = integrateLtcBrdfOverRect( geometry, brdfLtcApproxMat, rectPoints );\r\n\tspecularReflectance *= brdfLtcScalar;\r\n\r\n\treturn specularReflectance;\r\n\r\n}\r\n\r\nvec3 Rect_Area_Light_Diffuse_Reflectance(\r\n\t\tconst in GeometricContext geometry,\r\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight ) {\r\n\r\n\tvec3 rectPoints[4];\r\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\r\n\r\n\tmat3 diffuseBrdfMat = mat3(1);\r\n\tvec3 diffuseReflectance = integrateLtcBrdfOverRect( geometry, diffuseBrdfMat, rectPoints );\r\n\r\n\treturn diffuseReflectance;\r\n\r\n}\r\n// End RectArea BRDF\r\n\r\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\r\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\r\n\r\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\r\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\r\n\r\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\r\n\r\n\tvec4 r = roughness * c0 + c1;\r\n\r\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\r\n\r\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\r\n\r\n\treturn specularColor * AB.x + AB.y;\r\n\r\n} // validated\r\n\r\n\r\nfloat G_BlinnPhong_Implicit( ) {\r\n\r\n\t// geometry term is (n dot l)(n dot v) / 4(n dot l)(n dot v)\r\n\treturn 0.25;\r\n\r\n}\r\n\r\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\r\n\r\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\r\n\r\n}\r\n\r\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\r\n\r\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\r\n\r\n\t//float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\r\n\t//float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\r\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\r\n\r\n\tvec3 F = F_Schlick( specularColor, dotLH );\r\n\r\n\tfloat G = G_BlinnPhong_Implicit( );\r\n\r\n\tfloat D = D_BlinnPhong( shininess, dotNH );\r\n\r\n\treturn F * ( G * D );\r\n\r\n} // validated\r\n\r\n// source: http://simonstechblog.blogspot.ca/2011/12/microfacet-brdf.html\r\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\r\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\r\n}\r\n\r\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\r\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\r\n}\r\n";
  10222. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\r\n\r\n\tuniform sampler2D bumpMap;\r\n\tuniform float bumpScale;\r\n\r\n\t// Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\r\n\t// http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\r\n\r\n\t// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\r\n\r\n\tvec2 dHdxy_fwd() {\r\n\r\n\t\tvec2 dSTdx = dFdx( vUv );\r\n\t\tvec2 dSTdy = dFdy( vUv );\r\n\r\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\r\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\r\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\r\n\r\n\t\treturn vec2( dBx, dBy );\r\n\r\n\t}\r\n\r\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\r\n\r\n\t\tvec3 vSigmaX = dFdx( surf_pos );\r\n\t\tvec3 vSigmaY = dFdy( surf_pos );\r\n\t\tvec3 vN = surf_norm;\t\t// normalized\r\n\r\n\t\tvec3 R1 = cross( vSigmaY, vN );\r\n\t\tvec3 R2 = cross( vN, vSigmaX );\r\n\r\n\t\tfloat fDet = dot( vSigmaX, R1 );\r\n\r\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\r\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\r\n\r\n\t}\r\n\r\n#endif\r\n";
  10223. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\r\n\r\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\r\n\r\n\t\tvec4 plane = clippingPlanes[ i ];\r\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\r\n\r\n\t}\r\n\t\t\r\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\r\n\r\n\t\tbool clipped = true;\r\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\r\n\t\t\tvec4 plane = clippingPlanes[ i ];\r\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\r\n\t\t}\r\n\r\n\t\tif ( clipped ) discard;\r\n\t\r\n\t#endif\r\n\r\n#endif\r\n";
  10224. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\r\n\r\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\r\n\t\tvarying vec3 vViewPosition;\r\n\t#endif\r\n\r\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\r\n\r\n#endif\r\n";
  10225. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\r\n\tvarying vec3 vViewPosition;\r\n#endif\r\n";
  10226. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\r\n\tvViewPosition = - mvPosition.xyz;\r\n#endif\r\n\r\n";
  10227. var color_fragment = "#ifdef USE_COLOR\r\n\r\n\tdiffuseColor.rgb *= vColor;\r\n\r\n#endif";
  10228. var color_pars_fragment = "#ifdef USE_COLOR\r\n\r\n\tvarying vec3 vColor;\r\n\r\n#endif\r\n";
  10229. var color_pars_vertex = "#ifdef USE_COLOR\r\n\r\n\tvarying vec3 vColor;\r\n\r\n#endif";
  10230. var color_vertex = "#ifdef USE_COLOR\r\n\r\n\tvColor.xyz = color.xyz;\r\n\r\n#endif";
  10231. var common = "#define PI 3.14159265359\r\n#define PI2 6.28318530718\r\n#define PI_HALF 1.5707963267949\r\n#define RECIPROCAL_PI 0.31830988618\r\n#define RECIPROCAL_PI2 0.15915494\r\n#define LOG2 1.442695\r\n#define EPSILON 1e-6\r\n\r\n#define saturate(a) clamp( a, 0.0, 1.0 )\r\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\r\n\r\nfloat pow2( const in float x ) { return x*x; }\r\nfloat pow3( const in float x ) { return x*x*x; }\r\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\r\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\r\n// expects values in the range of [0,1]x[0,1], returns values in the [0,1] range.\r\n// do not collapse into a single function per: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\r\nhighp float rand( const in vec2 uv ) {\r\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\r\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\r\n\treturn fract(sin(sn) * c);\r\n}\r\n\r\nstruct IncidentLight {\r\n\tvec3 color;\r\n\tvec3 direction;\r\n\tbool visible;\r\n};\r\n\r\nstruct ReflectedLight {\r\n\tvec3 directDiffuse;\r\n\tvec3 directSpecular;\r\n\tvec3 indirectDiffuse;\r\n\tvec3 indirectSpecular;\r\n};\r\n\r\nstruct GeometricContext {\r\n\tvec3 position;\r\n\tvec3 normal;\r\n\tvec3 viewDir;\r\n};\r\n\r\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\r\n\r\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\r\n\r\n}\r\n\r\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\r\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\r\n\r\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\r\n\r\n}\r\n\r\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\r\n\r\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\r\n\r\n\treturn - distance * planeNormal + point;\r\n\r\n}\r\n\r\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\r\n\r\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\r\n\r\n}\r\n\r\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\r\n\r\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\r\n\r\n}\r\n\r\nmat3 transpose( const in mat3 v ) {\r\n\r\n\tmat3 tmp;\r\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\r\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\r\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\r\n\r\n\treturn tmp;\r\n\r\n}\r\n";
  10232. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\r\n\r\n#define cubeUV_textureSize (1024.0)\r\n\r\nint getFaceFromDirection(vec3 direction) {\r\n\tvec3 absDirection = abs(direction);\r\n\tint face = -1;\r\n\tif( absDirection.x > absDirection.z ) {\r\n\t\tif(absDirection.x > absDirection.y )\r\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\r\n\t\telse\r\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\r\n\t}\r\n\telse {\r\n\t\tif(absDirection.z > absDirection.y )\r\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\r\n\t\telse\r\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\r\n\t}\r\n\treturn face;\r\n}\r\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\r\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\r\n\r\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\r\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\r\n\tfloat dxRoughness = dFdx(roughness);\r\n\tfloat dyRoughness = dFdy(roughness);\r\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\r\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\r\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\r\n\t// Clamp the value to the max mip level counts. hard coded to 6 mips\r\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\r\n\tfloat mipLevel = 0.5 * log2(d);\r\n\treturn vec2(floor(mipLevel), fract(mipLevel));\r\n}\r\n\r\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\r\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\r\n\r\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\r\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\r\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\r\n\r\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\r\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\r\n\t// float powScale = exp2(roughnessLevel + mipLevel);\r\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\r\n\t// float scale = 1.0 / exp2(roughnessLevel + 2.0 + mipLevel);\r\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\r\n\t// float mipOffset = 0.75*(1.0 - 1.0/exp2(mipLevel))/exp2(roughnessLevel);\r\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\r\n\r\n\tbool bRes = mipLevel == 0.0;\r\n\tscale = bRes && (scale < a) ? a : scale;\r\n\r\n\tvec3 r;\r\n\tvec2 offset;\r\n\tint face = getFaceFromDirection(direction);\r\n\r\n\tfloat rcpPowScale = 1.0 / powScale;\r\n\r\n\tif( face == 0) {\r\n\t\tr = vec3(direction.x, -direction.z, direction.y);\r\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\r\n\t}\r\n\telse if( face == 1) {\r\n\t\tr = vec3(direction.y, direction.x, direction.z);\r\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\r\n\t}\r\n\telse if( face == 2) {\r\n\t\tr = vec3(direction.z, direction.x, direction.y);\r\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\r\n\t}\r\n\telse if( face == 3) {\r\n\t\tr = vec3(direction.x, direction.z, direction.y);\r\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\r\n\t}\r\n\telse if( face == 4) {\r\n\t\tr = vec3(direction.y, direction.x, -direction.z);\r\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\r\n\t}\r\n\telse {\r\n\t\tr = vec3(direction.z, -direction.x, direction.y);\r\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\r\n\t}\r\n\tr = normalize(r);\r\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\r\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\r\n\tvec2 base = offset + vec2( texelOffset );\r\n\treturn base + s * ( scale - 2.0 * texelOffset );\r\n}\r\n\r\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\r\n\r\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\r\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\r\n\tfloat r1 = floor(roughnessVal);\r\n\tfloat r2 = r1 + 1.0;\r\n\tfloat t = fract(roughnessVal);\r\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\r\n\tfloat s = mipInfo.y;\r\n\tfloat level0 = mipInfo.x;\r\n\tfloat level1 = level0 + 1.0;\r\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\r\n\r\n\t// round to nearest mipmap if we are not interpolating.\r\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\r\n\r\n\t// Tri linear interpolation.\r\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\r\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\r\n\r\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\r\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\r\n\r\n\tvec4 result = mix(color10, color20, t);\r\n\r\n\treturn vec4(result.rgb, 1.0);\r\n}\r\n\r\n#endif\r\n";
  10233. var defaultnormal_vertex = "#ifdef FLIP_SIDED\r\n\r\n\tobjectNormal = -objectNormal;\r\n\r\n#endif\r\n\r\nvec3 transformedNormal = normalMatrix * objectNormal;\r\n";
  10234. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\r\n\r\n\tuniform sampler2D displacementMap;\r\n\tuniform float displacementScale;\r\n\tuniform float displacementBias;\r\n\r\n#endif\r\n";
  10235. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\r\n\r\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\r\n\r\n#endif\r\n";
  10236. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\r\n\r\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\r\n\r\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\r\n\r\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\r\n\r\n#endif\r\n";
  10237. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\r\n\r\n\tuniform sampler2D emissiveMap;\r\n\r\n#endif\r\n";
  10238. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\r\n";
  10239. var encodings_pars_fragment = "// For a discussion of what this is, please read this: http://lousodrome.net/blog/light/2013/05/26/gamma-correct-and-hdr-rendering-in-a-32-bits-buffer/\r\n\r\nvec4 LinearToLinear( in vec4 value ) {\r\n\treturn value;\r\n}\r\n\r\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\r\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\r\n}\r\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\r\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\r\n}\r\n\r\nvec4 sRGBToLinear( in vec4 value ) {\r\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\r\n}\r\nvec4 LinearTosRGB( in vec4 value ) {\r\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\r\n}\r\n\r\nvec4 RGBEToLinear( in vec4 value ) {\r\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\r\n}\r\nvec4 LinearToRGBE( in vec4 value ) {\r\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\r\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\r\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\r\n// return vec4( value.brg, ( 3.0 + 128.0 ) / 256.0 );\r\n}\r\n\r\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\r\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\r\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\r\n}\r\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\r\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\r\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\r\n\tM = ceil( M * 255.0 ) / 255.0;\r\n\treturn vec4( value.rgb / ( M * maxRange ), M );\r\n}\r\n\r\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\r\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\r\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\r\n}\r\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\r\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\r\n\tfloat D = max( maxRange / maxRGB, 1.0 );\r\n\tD = min( floor( D ) / 255.0, 1.0 );\r\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\r\n}\r\n\r\n// LogLuv reference: http://graphicrants.blogspot.ca/2009/04/rgbm-color-encoding.html\r\n\r\n// M matrix, for encoding\r\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\r\nvec4 LinearToLogLuv( in vec4 value ) {\r\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\r\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\r\n\tvec4 vResult;\r\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\r\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\r\n\tvResult.w = fract(Le);\r\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\r\n\treturn vResult;\r\n}\r\n\r\n// Inverse M matrix, for decoding\r\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\r\nvec4 LogLuvToLinear( in vec4 value ) {\r\n\tfloat Le = value.z * 255.0 + value.w;\r\n\tvec3 Xp_Y_XYZp;\r\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\r\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\r\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\r\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\r\n\treturn vec4( max(vRGB, 0.0), 1.0 );\r\n}\r\n";
  10240. var envmap_fragment = "#ifdef USE_ENVMAP\r\n\r\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\r\n\r\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\r\n\r\n\t\t// Transforming Normal Vectors with the Inverse Transformation\r\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\r\n\r\n\t\t#ifdef ENVMAP_MODE_REFLECTION\r\n\r\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\r\n\r\n\t\t#else\r\n\r\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\r\n\r\n\t\t#endif\r\n\r\n\t#else\r\n\r\n\t\tvec3 reflectVec = vReflect;\r\n\r\n\t#endif\r\n\r\n\t#ifdef ENVMAP_TYPE_CUBE\r\n\r\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\r\n\r\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\r\n\r\n\t\tvec2 sampleUV;\r\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\r\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\r\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\r\n\r\n\t#elif defined( ENVMAP_TYPE_SPHERE )\r\n\r\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\r\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\r\n\r\n\t#else\r\n\r\n\t\tvec4 envColor = vec4( 0.0 );\r\n\r\n\t#endif\r\n\r\n\tenvColor = envMapTexelToLinear( envColor );\r\n\r\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\r\n\r\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\r\n\r\n\t#elif defined( ENVMAP_BLENDING_MIX )\r\n\r\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\r\n\r\n\t#elif defined( ENVMAP_BLENDING_ADD )\r\n\r\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  10241. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\r\n\tuniform float reflectivity;\r\n\tuniform float envMapIntensity;\r\n#endif\r\n\r\n#ifdef USE_ENVMAP\r\n\r\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\r\n\t\tvarying vec3 vWorldPosition;\r\n\t#endif\r\n\r\n\t#ifdef ENVMAP_TYPE_CUBE\r\n\t\tuniform samplerCube envMap;\r\n\t#else\r\n\t\tuniform sampler2D envMap;\r\n\t#endif\r\n\tuniform float flipEnvMap;\r\n\r\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\r\n\t\tuniform float refractionRatio;\r\n\t#else\r\n\t\tvarying vec3 vReflect;\r\n\t#endif\r\n\r\n#endif\r\n";
  10242. var envmap_pars_vertex = "#ifdef USE_ENVMAP\r\n\r\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\r\n\t\tvarying vec3 vWorldPosition;\r\n\r\n\t#else\r\n\r\n\t\tvarying vec3 vReflect;\r\n\t\tuniform float refractionRatio;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  10243. var envmap_vertex = "#ifdef USE_ENVMAP\r\n\r\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\r\n\r\n\t\tvWorldPosition = worldPosition.xyz;\r\n\r\n\t#else\r\n\r\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\r\n\r\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\r\n\r\n\t\t#ifdef ENVMAP_MODE_REFLECTION\r\n\r\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\r\n\r\n\t\t#else\r\n\r\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\r\n\r\n\t\t#endif\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  10244. var fog_vertex = "\r\n#ifdef USE_FOG\r\nfogDepth = -mvPosition.z;\r\n#endif";
  10245. var fog_pars_vertex = "#ifdef USE_FOG\r\n\r\n varying float fogDepth;\r\n\r\n#endif\r\n";
  10246. var fog_fragment = "#ifdef USE_FOG\r\n\r\n\t#ifdef FOG_EXP2\r\n\r\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\r\n\r\n\t#else\r\n\r\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\r\n\r\n\t#endif\r\n\r\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\r\n\r\n#endif\r\n";
  10247. var fog_pars_fragment = "#ifdef USE_FOG\r\n\r\n\tuniform vec3 fogColor;\r\n\tvarying float fogDepth;\r\n\r\n\t#ifdef FOG_EXP2\r\n\r\n\t\tuniform float fogDensity;\r\n\r\n\t#else\r\n\r\n\t\tuniform float fogNear;\r\n\t\tuniform float fogFar;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  10248. var gradientmap_pars_fragment = "#ifdef TOON\r\n\r\n\tuniform sampler2D gradientMap;\r\n\r\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\r\n\r\n\t\t// dotNL will be from -1.0 to 1.0\r\n\t\tfloat dotNL = dot( normal, lightDirection );\r\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\r\n\r\n\t\t#ifdef USE_GRADIENTMAP\r\n\r\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\r\n\r\n\t\t#else\r\n\r\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\r\n\r\n\t\t#endif\r\n\r\n\r\n\t}\r\n\r\n#endif\r\n";
  10249. var lightmap_fragment = "#ifdef USE_LIGHTMAP\r\n\r\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage\r\n\r\n#endif\r\n";
  10250. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\r\n\r\n\tuniform sampler2D lightMap;\r\n\tuniform float lightMapIntensity;\r\n\r\n#endif";
  10251. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\r\n\r\nGeometricContext geometry;\r\ngeometry.position = mvPosition.xyz;\r\ngeometry.normal = normalize( transformedNormal );\r\ngeometry.viewDir = normalize( -mvPosition.xyz );\r\n\r\nGeometricContext backGeometry;\r\nbackGeometry.position = geometry.position;\r\nbackGeometry.normal = -geometry.normal;\r\nbackGeometry.viewDir = geometry.viewDir;\r\n\r\nvLightFront = vec3( 0.0 );\r\n\r\n#ifdef DOUBLE_SIDED\r\n\tvLightBack = vec3( 0.0 );\r\n#endif\r\n\r\nIncidentLight directLight;\r\nfloat dotNL;\r\nvec3 directLightColor_Diffuse;\r\n\r\n#if NUM_POINT_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\r\n\r\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\r\n\r\n\t\tdotNL = dot( geometry.normal, directLight.direction );\r\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\r\n\r\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#endif\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if NUM_SPOT_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\r\n\r\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\r\n\r\n\t\tdotNL = dot( geometry.normal, directLight.direction );\r\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\r\n\r\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#endif\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n\r\n#if NUM_DIR_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\r\n\r\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\r\n\r\n\t\tdotNL = dot( geometry.normal, directLight.direction );\r\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\r\n\r\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#endif\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if NUM_HEMI_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\r\n\r\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\r\n\r\n\t\t#endif\r\n\r\n\t}\r\n\r\n#endif\r\n";
  10252. var lights_pars = "uniform vec3 ambientLightColor;\r\n\r\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\r\n\r\n\tvec3 irradiance = ambientLightColor;\r\n\r\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\tirradiance *= PI;\r\n\r\n\t#endif\r\n\r\n\treturn irradiance;\r\n\r\n}\r\n\r\n#if NUM_DIR_LIGHTS > 0\r\n\r\n\tstruct DirectionalLight {\r\n\t\tvec3 direction;\r\n\t\tvec3 color;\r\n\r\n\t\tint shadow;\r\n\t\tfloat shadowBias;\r\n\t\tfloat shadowRadius;\r\n\t\tvec2 shadowMapSize;\r\n\t};\r\n\r\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\r\n\r\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\r\n\r\n\t\tdirectLight.color = directionalLight.color;\r\n\t\tdirectLight.direction = directionalLight.direction;\r\n\t\tdirectLight.visible = true;\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n#if NUM_POINT_LIGHTS > 0\r\n\r\n\tstruct PointLight {\r\n\t\tvec3 position;\r\n\t\tvec3 color;\r\n\t\tfloat distance;\r\n\t\tfloat decay;\r\n\r\n\t\tint shadow;\r\n\t\tfloat shadowBias;\r\n\t\tfloat shadowRadius;\r\n\t\tvec2 shadowMapSize;\r\n\t};\r\n\r\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\r\n\r\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\r\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\r\n\r\n\t\tvec3 lVector = pointLight.position - geometry.position;\r\n\t\tdirectLight.direction = normalize( lVector );\r\n\r\n\t\tfloat lightDistance = length( lVector );\r\n\r\n\t\tdirectLight.color = pointLight.color;\r\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\r\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n#if NUM_SPOT_LIGHTS > 0\r\n\r\n\tstruct SpotLight {\r\n\t\tvec3 position;\r\n\t\tvec3 direction;\r\n\t\tvec3 color;\r\n\t\tfloat distance;\r\n\t\tfloat decay;\r\n\t\tfloat coneCos;\r\n\t\tfloat penumbraCos;\r\n\r\n\t\tint shadow;\r\n\t\tfloat shadowBias;\r\n\t\tfloat shadowRadius;\r\n\t\tvec2 shadowMapSize;\r\n\t};\r\n\r\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\r\n\r\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\r\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\r\n\r\n\t\tvec3 lVector = spotLight.position - geometry.position;\r\n\t\tdirectLight.direction = normalize( lVector );\r\n\r\n\t\tfloat lightDistance = length( lVector );\r\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\r\n\r\n\t\tif ( angleCos > spotLight.coneCos ) {\r\n\r\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\r\n\r\n\t\t\tdirectLight.color = spotLight.color;\r\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\r\n\t\t\tdirectLight.visible = true;\r\n\r\n\t\t} else {\r\n\r\n\t\t\tdirectLight.color = vec3( 0.0 );\r\n\t\t\tdirectLight.visible = false;\r\n\r\n\t\t}\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n#if NUM_RECT_AREA_LIGHTS > 0\r\n\r\n\tstruct RectAreaLight {\r\n\t\tvec3 color;\r\n\t\tvec3 position;\r\n\t\tvec3 halfWidth;\r\n\t\tvec3 halfHeight;\r\n\t};\r\n\r\n\t// Pre-computed values of LinearTransformedCosine approximation of BRDF\r\n\t// BRDF approximation Texture is 64x64\r\n\tuniform sampler2D ltcMat; // RGBA Float\r\n\tuniform sampler2D ltcMag; // Alpha Float (only has w component)\r\n\r\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\r\n\r\n#endif\r\n\r\n\r\n#if NUM_HEMI_LIGHTS > 0\r\n\r\n\tstruct HemisphereLight {\r\n\t\tvec3 direction;\r\n\t\tvec3 skyColor;\r\n\t\tvec3 groundColor;\r\n\t};\r\n\r\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\r\n\r\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\r\n\r\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\r\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\r\n\r\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\r\n\r\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\t\tirradiance *= PI;\r\n\r\n\t\t#endif\r\n\r\n\t\treturn irradiance;\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\r\n\r\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\r\n\r\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\r\n\r\n\t\t#ifdef ENVMAP_TYPE_CUBE\r\n\r\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\r\n\r\n\t\t\t// TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level\r\n\t\t\t// of a specular cubemap, or just the default level of a specially created irradiance cubemap.\r\n\r\n\t\t\t#ifdef TEXTURE_LOD_EXT\r\n\r\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\r\n\r\n\t\t\t#else\r\n\r\n\t\t\t\t// force the bias high to get the last LOD level as it is the most blurred.\r\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\r\n\r\n\t\t\t#endif\r\n\r\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\r\n\r\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\r\n\r\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\r\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\r\n\r\n\t\t#else\r\n\r\n\t\t\tvec4 envMapColor = vec4( 0.0 );\r\n\r\n\t\t#endif\r\n\r\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\r\n\r\n\t}\r\n\r\n\t// taken from here: http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html\r\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\r\n\r\n\t\t//float envMapWidth = pow( 2.0, maxMIPLevelScalar );\r\n\t\t//float desiredMIPLevel = log2( envMapWidth * sqrt( 3.0 ) ) - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\r\n\r\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\r\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\r\n\r\n\t\t// clamp to allowable LOD ranges.\r\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\r\n\r\n\t}\r\n\r\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\r\n\r\n\t\t#ifdef ENVMAP_MODE_REFLECTION\r\n\r\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\r\n\r\n\t\t#else\r\n\r\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\r\n\r\n\t\t#endif\r\n\r\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\r\n\r\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\r\n\r\n\t\t#ifdef ENVMAP_TYPE_CUBE\r\n\r\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\r\n\r\n\t\t\t#ifdef TEXTURE_LOD_EXT\r\n\r\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\r\n\r\n\t\t\t#else\r\n\r\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\r\n\r\n\t\t\t#endif\r\n\r\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\r\n\r\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\r\n\r\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\r\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\r\n\r\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\r\n\r\n\t\t\tvec2 sampleUV;\r\n\t\t\tsampleUV.y = saturate( reflectVec.y * 0.5 + 0.5 );\r\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\t\t\t#ifdef TEXTURE_LOD_EXT\r\n\r\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\r\n\r\n\t\t\t#else\r\n\r\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\r\n\r\n\t\t\t#endif\r\n\r\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\r\n\r\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\r\n\r\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\r\n\r\n\t\t\t#ifdef TEXTURE_LOD_EXT\r\n\r\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\r\n\r\n\t\t\t#else\r\n\r\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\r\n\r\n\t\t\t#endif\r\n\r\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\r\n\r\n\t\t#endif\r\n\r\n\t\treturn envMapColor.rgb * envMapIntensity;\r\n\r\n\t}\r\n\r\n#endif\r\n";
  10253. var lights_phong_fragment = "BlinnPhongMaterial material;\r\nmaterial.diffuseColor = diffuseColor.rgb;\r\nmaterial.specularColor = specular;\r\nmaterial.specularShininess = shininess;\r\nmaterial.specularStrength = specularStrength;\r\n";
  10254. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n\r\nstruct BlinnPhongMaterial {\r\n\r\n\tvec3\tdiffuseColor;\r\n\tvec3\tspecularColor;\r\n\tfloat\tspecularShininess;\r\n\tfloat\tspecularStrength;\r\n\r\n};\r\n\r\n#if NUM_RECT_AREA_LIGHTS > 0\r\n\tvoid RE_Direct_RectArea_BlinnPhong( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\t\tvec3 matDiffColor = material.diffuseColor;\r\n\t\tvec3 matSpecColor = material.specularColor;\r\n\t\tvec3 lightColor = rectAreaLight.color;\r\n\r\n\t\tfloat roughness = BlinnExponentToGGXRoughness( material.specularShininess );\r\n\r\n\t\t// Evaluate Lighting Equation\r\n\t\tvec3 spec = Rect_Area_Light_Specular_Reflectance(\r\n\t\t\t\tgeometry,\r\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\r\n\t\t\t\troughness,\r\n\t\t\t\tltcMat, ltcMag );\r\n\t\tvec3 diff = Rect_Area_Light_Diffuse_Reflectance(\r\n\t\t\t\tgeometry,\r\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\r\n\r\n\t\t// TODO (abelnation): note why division by 2PI is necessary\r\n\t\treflectedLight.directSpecular += lightColor * matSpecColor * spec / PI2;\r\n\t\treflectedLight.directDiffuse += lightColor * matDiffColor * diff / PI2;\r\n\r\n\t}\r\n#endif\r\n\r\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\t#ifdef TOON\r\n\r\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\r\n\r\n\t#else\r\n\r\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\r\n\t\tvec3 irradiance = dotNL * directLight.color;\r\n\r\n\t#endif\r\n\r\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\tirradiance *= PI; // punctual light\r\n\r\n\t#endif\r\n\r\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\r\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\r\n\r\n}\r\n\r\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\r\n\r\n}\r\n\r\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\r\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_BlinnPhong\r\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\r\n\r\n#define Material_LightProbeLOD( material )\t(0)\r\n";
  10255. var lights_physical_fragment = "PhysicalMaterial material;\r\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\r\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\r\n#ifdef STANDARD\r\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\r\n#else\r\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\r\n\tmaterial.clearCoat = saturate( clearCoat ); // Burley clearcoat model\r\n\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\r\n#endif\r\n";
  10256. var lights_physical_pars_fragment = "struct PhysicalMaterial {\r\n\r\n\tvec3\tdiffuseColor;\r\n\tfloat\tspecularRoughness;\r\n\tvec3\tspecularColor;\r\n\r\n\t#ifndef STANDARD\r\n\t\tfloat clearCoat;\r\n\t\tfloat clearCoatRoughness;\r\n\t#endif\r\n\r\n};\r\n\r\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\r\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\r\n\r\n// Clear coat directional hemishperical reflectance (this approximation should be improved)\r\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\r\n\r\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\r\n\r\n}\r\n\r\n#if NUM_RECT_AREA_LIGHTS > 0\r\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\t\tvec3 matDiffColor = material.diffuseColor;\r\n\t\tvec3 matSpecColor = material.specularColor;\r\n\t\tvec3 lightColor = rectAreaLight.color;\r\n\t\tfloat roughness = material.specularRoughness;\r\n\r\n\t\tvec3 spec = Rect_Area_Light_Specular_Reflectance(\r\n\t\t\t\tgeometry,\r\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\r\n\t\t\t\troughness,\r\n\t\t\t\tltcMat, ltcMag );\r\n\t\tvec3 diff = Rect_Area_Light_Diffuse_Reflectance(\r\n\t\t\t\tgeometry,\r\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\r\n\r\n\t\treflectedLight.directSpecular += lightColor * matSpecColor * spec;\r\n\t\treflectedLight.directDiffuse += lightColor * matDiffColor * diff;\r\n\r\n\t}\r\n#endif\r\n\r\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\r\n\r\n\tvec3 irradiance = dotNL * directLight.color;\r\n\r\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\tirradiance *= PI; // punctual light\r\n\r\n\t#endif\r\n\r\n\t#ifndef STANDARD\r\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\r\n\t#else\r\n\t\tfloat clearCoatDHR = 0.0;\r\n\t#endif\r\n\r\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\r\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\r\n\r\n\t#ifndef STANDARD\r\n\r\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\r\n\r\n\t#endif\r\n\r\n}\r\n\r\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\r\n\r\n}\r\n\r\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\t#ifndef STANDARD\r\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\t\tfloat dotNL = dotNV;\r\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\r\n\t#else\r\n\t\tfloat clearCoatDHR = 0.0;\r\n\t#endif\r\n\r\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\r\n\r\n\t#ifndef STANDARD\r\n\r\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\r\n\r\n\t#endif\r\n\r\n}\r\n\r\n#define RE_Direct\t\t\t\tRE_Direct_Physical\r\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\r\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\r\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\r\n\r\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\r\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\r\n\r\n// ref: http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr_v2.pdf\r\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\r\n\r\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\r\n\r\n}\r\n";
  10257. var lights_template = "\r\n\r\nGeometricContext geometry;\r\n\r\ngeometry.position = - vViewPosition;\r\ngeometry.normal = normal;\r\ngeometry.viewDir = normalize( vViewPosition );\r\n\r\nIncidentLight directLight;\r\n\r\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\r\n\r\n\tPointLight pointLight;\r\n\r\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\r\n\r\n\t\tpointLight = pointLights[ i ];\r\n\r\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\r\n\r\n\t\t#ifdef USE_SHADOWMAP\r\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\r\n\t\t#endif\r\n\r\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\r\n\r\n\tSpotLight spotLight;\r\n\r\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\r\n\r\n\t\tspotLight = spotLights[ i ];\r\n\r\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\r\n\r\n\t\t#ifdef USE_SHADOWMAP\r\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\r\n\t\t#endif\r\n\r\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\r\n\r\n\tDirectionalLight directionalLight;\r\n\r\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\r\n\r\n\t\tdirectionalLight = directionalLights[ i ];\r\n\r\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\r\n\r\n\t\t#ifdef USE_SHADOWMAP\r\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\r\n\t\t#endif\r\n\r\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\r\n\r\n\tRectAreaLight rectAreaLight;\r\n\r\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\r\n\r\n\t\trectAreaLight = rectAreaLights[ i ];\r\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if defined( RE_IndirectDiffuse )\r\n\r\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\r\n\r\n\t#ifdef USE_LIGHTMAP\r\n\r\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\r\n\r\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\t\tlightMapIrradiance *= PI; // factor of PI should not be present; included here to prevent breakage\r\n\r\n\t\t#endif\r\n\r\n\t\tirradiance += lightMapIrradiance;\r\n\r\n\t#endif\r\n\r\n\t#if ( NUM_HEMI_LIGHTS > 0 )\r\n\r\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\r\n\r\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\r\n\r\n\t\t}\r\n\r\n\t#endif\r\n\r\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\r\n\r\n\t\t// TODO, replace 8 with the real maxMIPLevel\r\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\r\n\r\n\t#endif\r\n\r\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\r\n\r\n#endif\r\n\r\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\r\n\r\n\t// TODO, replace 8 with the real maxMIPLevel\r\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\r\n\r\n\t#ifndef STANDARD\r\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\r\n\t#else\r\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\r\n\t#endif\r\n\r\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\r\n\r\n#endif\r\n";
  10258. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\r\n\r\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\r\n\r\n#endif";
  10259. var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\r\n\r\n\tuniform float logDepthBufFC;\r\n\r\n\t#ifdef USE_LOGDEPTHBUF_EXT\r\n\r\n\t\tvarying float vFragDepth;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  10260. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\r\n\r\n\t#ifdef USE_LOGDEPTHBUF_EXT\r\n\r\n\t\tvarying float vFragDepth;\r\n\r\n\t#endif\r\n\r\n\tuniform float logDepthBufFC;\r\n\r\n#endif";
  10261. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\r\n\r\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\r\n\r\n\t#ifdef USE_LOGDEPTHBUF_EXT\r\n\r\n\t\tvFragDepth = 1.0 + gl_Position.w;\r\n\r\n\t#else\r\n\r\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  10262. var map_fragment = "#ifdef USE_MAP\r\n\r\n\tvec4 texelColor = texture2D( map, vUv );\r\n\r\n\ttexelColor = mapTexelToLinear( texelColor );\r\n\tdiffuseColor *= texelColor;\r\n\r\n#endif\r\n";
  10263. var map_pars_fragment = "#ifdef USE_MAP\r\n\r\n\tuniform sampler2D map;\r\n\r\n#endif\r\n";
  10264. var map_particle_fragment = "#ifdef USE_MAP\r\n\r\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\r\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\r\n\r\n#endif\r\n";
  10265. var map_particle_pars_fragment = "#ifdef USE_MAP\r\n\r\n\tuniform vec4 offsetRepeat;\r\n\tuniform sampler2D map;\r\n\r\n#endif\r\n";
  10266. var metalnessmap_fragment = "float metalnessFactor = metalness;\r\n\r\n#ifdef USE_METALNESSMAP\r\n\r\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\r\n\tmetalnessFactor *= texelMetalness.r;\r\n\r\n#endif\r\n";
  10267. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\r\n\r\n\tuniform sampler2D metalnessMap;\r\n\r\n#endif";
  10268. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\r\n\r\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\r\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\r\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\r\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\r\n\r\n#endif\r\n";
  10269. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\r\n\r\n\t#ifndef USE_MORPHNORMALS\r\n\r\n\tuniform float morphTargetInfluences[ 8 ];\r\n\r\n\t#else\r\n\r\n\tuniform float morphTargetInfluences[ 4 ];\r\n\r\n\t#endif\r\n\r\n#endif";
  10270. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\r\n\r\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\r\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\r\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\r\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\r\n\r\n\t#ifndef USE_MORPHNORMALS\r\n\r\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\r\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\r\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\r\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  10271. var normal_flip = "#ifdef DOUBLE_SIDED\r\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\r\n#else\r\n\tfloat flipNormal = 1.0;\r\n#endif\r\n";
  10272. var normal_fragment = "#ifdef FLAT_SHADED\r\n\r\n\t// Workaround for Adreno/Nexus5 not able able to do dFdx( vViewPosition ) ...\r\n\r\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\r\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\r\n\tvec3 normal = normalize( cross( fdx, fdy ) );\r\n\r\n#else\r\n\r\n\tvec3 normal = normalize( vNormal ) * flipNormal;\r\n\r\n#endif\r\n\r\n#ifdef USE_NORMALMAP\r\n\r\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\r\n\r\n#elif defined( USE_BUMPMAP )\r\n\r\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\r\n\r\n#endif\r\n";
  10273. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\r\n\r\n\tuniform sampler2D normalMap;\r\n\tuniform vec2 normalScale;\r\n\r\n\t// Per-Pixel Tangent Space Normal Mapping\r\n\t// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\r\n\r\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\r\n\r\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\r\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\r\n\t\tvec2 st0 = dFdx( vUv.st );\r\n\t\tvec2 st1 = dFdy( vUv.st );\r\n\r\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\r\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\r\n\t\tvec3 N = normalize( surf_norm );\r\n\r\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\r\n\t\tmapN.xy = normalScale * mapN.xy;\r\n\t\tmat3 tsn = mat3( S, T, N );\r\n\t\treturn normalize( tsn * mapN );\r\n\r\n\t}\r\n\r\n#endif\r\n";
  10274. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\r\n\treturn normalize( normal ) * 0.5 + 0.5;\r\n}\r\n\r\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\r\n\treturn 1.0 - 2.0 * rgb.xyz;\r\n}\r\n\r\nconst float PackUpscale = 256. / 255.; // fraction -> 0..1 (including 1)\r\nconst float UnpackDownscale = 255. / 256.; // 0..1 -> fraction (excluding 1)\r\n\r\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\r\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\r\n\r\nconst float ShiftRight8 = 1. / 256.;\r\n\r\nvec4 packDepthToRGBA( const in float v ) {\r\n\tvec4 r = vec4( fract( v * PackFactors ), v );\r\n\tr.yzw -= r.xyz * ShiftRight8; // tidy overflow\r\n\treturn r * PackUpscale;\r\n}\r\n\r\nfloat unpackRGBAToDepth( const in vec4 v ) {\r\n\treturn dot( v, UnpackFactors );\r\n}\r\n\r\n// NOTE: viewZ/eyeZ is < 0 when in front of the camera per OpenGL conventions\r\n\r\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\r\n\treturn ( viewZ + near ) / ( near - far );\r\n}\r\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\r\n\treturn linearClipZ * ( near - far ) - near;\r\n}\r\n\r\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\r\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\r\n}\r\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\r\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\r\n}\r\n";
  10275. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\r\n\r\n\t// Get get normal blending with premultipled, use with CustomBlending, OneFactor, OneMinusSrcAlphaFactor, AddEquation.\r\n\tgl_FragColor.rgb *= gl_FragColor.a;\r\n\r\n#endif\r\n";
  10276. var project_vertex = "#ifdef USE_SKINNING\r\n\r\n\tvec4 mvPosition = modelViewMatrix * skinned;\r\n\r\n#else\r\n\r\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\r\n\r\n#endif\r\n\r\ngl_Position = projectionMatrix * mvPosition;\r\n";
  10277. var roughnessmap_fragment = "float roughnessFactor = roughness;\r\n\r\n#ifdef USE_ROUGHNESSMAP\r\n\r\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\r\n\troughnessFactor *= texelRoughness.r;\r\n\r\n#endif\r\n";
  10278. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\r\n\r\n\tuniform sampler2D roughnessMap;\r\n\r\n#endif";
  10279. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\r\n\r\n\t#if NUM_DIR_LIGHTS > 0\r\n\r\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\r\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\t#if NUM_SPOT_LIGHTS > 0\r\n\r\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\r\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\t#if NUM_POINT_LIGHTS > 0\r\n\r\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\r\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\r\n\r\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\r\n\r\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\r\n\r\n\t}\r\n\r\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\r\n\r\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\r\n\r\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\r\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\r\n\r\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\r\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\r\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\r\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\r\n\r\n\t\tvec2 f = fract( uv * size + 0.5 );\r\n\r\n\t\tfloat a = mix( lb, lt, f.y );\r\n\t\tfloat b = mix( rb, rt, f.y );\r\n\t\tfloat c = mix( a, b, f.x );\r\n\r\n\t\treturn c;\r\n\r\n\t}\r\n\r\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\r\n\r\n\t\tshadowCoord.xyz /= shadowCoord.w;\r\n\t\tshadowCoord.z += shadowBias;\r\n\r\n\t\t// if ( something && something ) breaks ATI OpenGL shader compiler\r\n\t\t// if ( all( something, something ) ) using this instead\r\n\r\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\r\n\t\tbool inFrustum = all( inFrustumVec );\r\n\r\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\r\n\r\n\t\tbool frustumTest = all( frustumTestVec );\r\n\r\n\t\tif ( frustumTest ) {\r\n\r\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\r\n\r\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\r\n\r\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\r\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\r\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\r\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\r\n\r\n\t\t\treturn (\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\r\n\t\t\t) * ( 1.0 / 9.0 );\r\n\r\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\r\n\r\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\r\n\r\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\r\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\r\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\r\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\r\n\r\n\t\t\treturn (\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\r\n\t\t\t) * ( 1.0 / 9.0 );\r\n\r\n\t\t#else // no percentage-closer filtering:\r\n\r\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\r\n\r\n\t\t#endif\r\n\r\n\t\t}\r\n\r\n\t\treturn 1.0;\r\n\r\n\t}\r\n\r\n\t// cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D\r\n\t// vector suitable for 2D texture mapping. This code uses the following layout for the\r\n\t// 2D texture:\r\n\t//\r\n\t// xzXZ\r\n\t// y Y\r\n\t//\r\n\t// Y - Positive y direction\r\n\t// y - Negative y direction\r\n\t// X - Positive x direction\r\n\t// x - Negative x direction\r\n\t// Z - Positive z direction\r\n\t// z - Negative z direction\r\n\t//\r\n\t// Source and test bed:\r\n\t// https://gist.github.com/tschw/da10c43c467ce8afd0c4\r\n\r\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\r\n\r\n\t\t// Number of texels to avoid at the edge of each square\r\n\r\n\t\tvec3 absV = abs( v );\r\n\r\n\t\t// Intersect unit cube\r\n\r\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\r\n\t\tabsV *= scaleToCube;\r\n\r\n\t\t// Apply scale to avoid seams\r\n\r\n\t\t// two texels less per square (one texel will do for NEAREST)\r\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\r\n\r\n\t\t// Unwrap\r\n\r\n\t\t// space: -1 ... 1 range for each square\r\n\t\t//\r\n\t\t// #X##\t\tdim := ( 4 , 2 )\r\n\t\t// # #\t\tcenter := ( 1 , 1 )\r\n\r\n\t\tvec2 planar = v.xy;\r\n\r\n\t\tfloat almostATexel = 1.5 * texelSizeY;\r\n\t\tfloat almostOne = 1.0 - almostATexel;\r\n\r\n\t\tif ( absV.z >= almostOne ) {\r\n\r\n\t\t\tif ( v.z > 0.0 )\r\n\t\t\t\tplanar.x = 4.0 - v.x;\r\n\r\n\t\t} else if ( absV.x >= almostOne ) {\r\n\r\n\t\t\tfloat signX = sign( v.x );\r\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\r\n\r\n\t\t} else if ( absV.y >= almostOne ) {\r\n\r\n\t\t\tfloat signY = sign( v.y );\r\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\r\n\t\t\tplanar.y = v.z * signY - 2.0;\r\n\r\n\t\t}\r\n\r\n\t\t// Transform to UV space\r\n\r\n\t\t// scale := 0.5 / dim\r\n\t\t// translate := ( center + 0.5 ) / dim\r\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\r\n\r\n\t}\r\n\r\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\r\n\r\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\r\n\r\n\t\t// for point lights, the uniform @vShadowCoord is re-purposed to hold\r\n\t\t// the distance from the light to the world-space position of the fragment.\r\n\t\tvec3 lightToPosition = shadowCoord.xyz;\r\n\r\n\t\t// bd3D = base direction 3D\r\n\t\tvec3 bd3D = normalize( lightToPosition );\r\n\t\t// dp = distance from light to fragment position\r\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\r\n\r\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\r\n\r\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\r\n\r\n\t\t\treturn (\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\r\n\t\t\t) * ( 1.0 / 9.0 );\r\n\r\n\t\t#else // no percentage-closer filtering\r\n\r\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\r\n\r\n\t\t#endif\r\n\r\n\t}\r\n\r\n#endif\r\n";
  10280. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\r\n\r\n\t#if NUM_DIR_LIGHTS > 0\r\n\r\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\r\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\t#if NUM_SPOT_LIGHTS > 0\r\n\r\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\r\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\t#if NUM_POINT_LIGHTS > 0\r\n\r\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\r\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\r\n\r\n#endif\r\n";
  10281. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\r\n\r\n\t#if NUM_DIR_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\r\n\r\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\t#if NUM_SPOT_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\r\n\r\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\t#if NUM_POINT_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\r\n\r\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\r\n\r\n#endif\r\n";
  10282. var shadowmask_pars_fragment = "float getShadowMask() {\r\n\r\n\tfloat shadow = 1.0;\r\n\r\n\t#ifdef USE_SHADOWMAP\r\n\r\n\t#if NUM_DIR_LIGHTS > 0\r\n\r\n\tDirectionalLight directionalLight;\r\n\r\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\r\n\r\n\t\tdirectionalLight = directionalLights[ i ];\r\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\t#if NUM_SPOT_LIGHTS > 0\r\n\r\n\tSpotLight spotLight;\r\n\r\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\r\n\r\n\t\tspotLight = spotLights[ i ];\r\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\t#if NUM_POINT_LIGHTS > 0\r\n\r\n\tPointLight pointLight;\r\n\r\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\r\n\r\n\t\tpointLight = pointLights[ i ];\r\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\r\n\r\n\t#endif\r\n\r\n\treturn shadow;\r\n\r\n}\r\n";
  10283. var skinbase_vertex = "#ifdef USE_SKINNING\r\n\r\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\r\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\r\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\r\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\r\n\r\n#endif";
  10284. var skinning_pars_vertex = "#ifdef USE_SKINNING\r\n\r\n\tuniform mat4 bindMatrix;\r\n\tuniform mat4 bindMatrixInverse;\r\n\r\n\t#ifdef BONE_TEXTURE\r\n\r\n\t\tuniform sampler2D boneTexture;\r\n\t\tuniform int boneTextureWidth;\r\n\t\tuniform int boneTextureHeight;\r\n\r\n\t\tmat4 getBoneMatrix( const in float i ) {\r\n\r\n\t\t\tfloat j = i * 4.0;\r\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\r\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\r\n\r\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\r\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\r\n\r\n\t\t\ty = dy * ( y + 0.5 );\r\n\r\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\r\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\r\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\r\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\r\n\r\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\r\n\r\n\t\t\treturn bone;\r\n\r\n\t\t}\r\n\r\n\t#else\r\n\r\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\r\n\r\n\t\tmat4 getBoneMatrix( const in float i ) {\r\n\r\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\r\n\t\t\treturn bone;\r\n\r\n\t\t}\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  10285. var skinning_vertex = "#ifdef USE_SKINNING\r\n\r\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\r\n\r\n\tvec4 skinned = vec4( 0.0 );\r\n\tskinned += boneMatX * skinVertex * skinWeight.x;\r\n\tskinned += boneMatY * skinVertex * skinWeight.y;\r\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\r\n\tskinned += boneMatW * skinVertex * skinWeight.w;\r\n\tskinned = bindMatrixInverse * skinned;\r\n\r\n#endif\r\n";
  10286. var skinnormal_vertex = "#ifdef USE_SKINNING\r\n\r\n\tmat4 skinMatrix = mat4( 0.0 );\r\n\tskinMatrix += skinWeight.x * boneMatX;\r\n\tskinMatrix += skinWeight.y * boneMatY;\r\n\tskinMatrix += skinWeight.z * boneMatZ;\r\n\tskinMatrix += skinWeight.w * boneMatW;\r\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\r\n\r\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\r\n\r\n#endif\r\n";
  10287. var specularmap_fragment = "float specularStrength;\r\n\r\n#ifdef USE_SPECULARMAP\r\n\r\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\r\n\tspecularStrength = texelSpecular.r;\r\n\r\n#else\r\n\r\n\tspecularStrength = 1.0;\r\n\r\n#endif";
  10288. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\r\n\r\n\tuniform sampler2D specularMap;\r\n\r\n#endif";
  10289. var tonemapping_fragment = "#if defined( TONE_MAPPING )\r\n\r\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\r\n\r\n#endif\r\n";
  10290. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\r\n\r\nuniform float toneMappingExposure;\r\nuniform float toneMappingWhitePoint;\r\n\r\n// exposure only\r\nvec3 LinearToneMapping( vec3 color ) {\r\n\r\n\treturn toneMappingExposure * color;\r\n\r\n}\r\n\r\n// source: https://www.cs.utah.edu/~reinhard/cdrom/\r\nvec3 ReinhardToneMapping( vec3 color ) {\r\n\r\n\tcolor *= toneMappingExposure;\r\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\r\n\r\n}\r\n\r\n// source: http://filmicgames.com/archives/75\r\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\r\nvec3 Uncharted2ToneMapping( vec3 color ) {\r\n\r\n\t// John Hable's filmic operator from Uncharted 2 video game\r\n\tcolor *= toneMappingExposure;\r\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\r\n\r\n}\r\n\r\n// source: http://filmicgames.com/archives/75\r\nvec3 OptimizedCineonToneMapping( vec3 color ) {\r\n\r\n\t// optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\r\n\tcolor *= toneMappingExposure;\r\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\r\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\r\n\r\n}\r\n";
  10291. var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\r\n\r\n\tvarying vec2 vUv;\r\n\r\n#endif";
  10292. var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\r\n\r\n\tvarying vec2 vUv;\r\n\tuniform vec4 offsetRepeat;\r\n\r\n#endif\r\n";
  10293. var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\r\n\r\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\r\n\r\n#endif";
  10294. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\r\n\r\n\tvarying vec2 vUv2;\r\n\r\n#endif";
  10295. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\r\n\r\n\tattribute vec2 uv2;\r\n\tvarying vec2 vUv2;\r\n\r\n#endif";
  10296. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\r\n\r\n\tvUv2 = uv2;\r\n\r\n#endif";
  10297. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\r\n\r\n\t#ifdef USE_SKINNING\r\n\r\n\t\tvec4 worldPosition = modelMatrix * skinned;\r\n\r\n\t#else\r\n\r\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  10298. var cube_frag = "uniform samplerCube tCube;\r\nuniform float tFlip;\r\nuniform float opacity;\r\n\r\nvarying vec3 vWorldPosition;\r\n\r\n#include <common>\r\n\r\nvoid main() {\r\n\r\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\r\n\tgl_FragColor.a *= opacity;\r\n\r\n}\r\n";
  10299. var cube_vert = "varying vec3 vWorldPosition;\r\n\r\n#include <common>\r\n\r\nvoid main() {\r\n\r\n\tvWorldPosition = transformDirection( position, modelMatrix );\r\n\r\n\t#include <begin_vertex>\r\n\t#include <project_vertex>\r\n\r\n}\r\n";
  10300. var depth_frag = "#if DEPTH_PACKING == 3200\r\n\r\n\tuniform float opacity;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <uv_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( 1.0 );\r\n\r\n\t#if DEPTH_PACKING == 3200\r\n\r\n\t\tdiffuseColor.a = opacity;\r\n\r\n\t#endif\r\n\r\n\t#include <map_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\r\n\t#if DEPTH_PACKING == 3200\r\n\r\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\r\n\r\n\t#elif DEPTH_PACKING == 3201\r\n\r\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\r\n\r\n\t#endif\r\n\r\n}\r\n";
  10301. var depth_vert = "#include <common>\r\n#include <uv_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\r\n\t#include <skinbase_vertex>\r\n\r\n\t#include <begin_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n}\r\n";
  10302. var distanceRGBA_frag = "uniform vec3 lightPos;\r\nvarying vec4 vWorldPosition;\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main () {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\r\n\r\n}\r\n";
  10303. var distanceRGBA_vert = "varying vec4 vWorldPosition;\r\n\r\n#include <common>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <skinbase_vertex>\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <project_vertex>\r\n\t#include <worldpos_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n\tvWorldPosition = worldPosition;\r\n\r\n}\r\n";
  10304. var equirect_frag = "uniform sampler2D tEquirect;\r\nuniform float tFlip;\r\n\r\nvarying vec3 vWorldPosition;\r\n\r\n#include <common>\r\n\r\nvoid main() {\r\n\r\n\t// \tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\r\n\tvec3 direction = normalize( vWorldPosition );\r\n\tvec2 sampleUV;\r\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\r\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\r\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\r\n\r\n}\r\n";
  10305. var equirect_vert = "varying vec3 vWorldPosition;\r\n\r\n#include <common>\r\n\r\nvoid main() {\r\n\r\n\tvWorldPosition = transformDirection( position, modelMatrix );\r\n\r\n\t#include <begin_vertex>\r\n\t#include <project_vertex>\r\n\r\n}\r\n";
  10306. var linedashed_frag = "uniform vec3 diffuse;\r\nuniform float opacity;\r\n\r\nuniform float dashSize;\r\nuniform float totalSize;\r\n\r\nvarying float vLineDistance;\r\n\r\n#include <common>\r\n#include <color_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\r\n\r\n\t\tdiscard;\r\n\r\n\t}\r\n\r\n\tvec3 outgoingLight = vec3( 0.0 );\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <color_fragment>\r\n\r\n\toutgoingLight = diffuseColor.rgb; // simple shader\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  10307. var linedashed_vert = "uniform float scale;\r\nattribute float lineDistance;\r\n\r\nvarying float vLineDistance;\r\n\r\n#include <common>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <color_vertex>\r\n\r\n\tvLineDistance = scale * lineDistance;\r\n\r\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\r\n\tgl_Position = projectionMatrix * mvPosition;\r\n\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  10308. var meshbasic_frag = "uniform vec3 diffuse;\r\nuniform float opacity;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <color_pars_fragment>\r\n#include <uv_pars_fragment>\r\n#include <uv2_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <aomap_pars_fragment>\r\n#include <lightmap_pars_fragment>\r\n#include <envmap_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <specularmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <specularmap_fragment>\r\n\r\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\r\n\r\n\t// accumulation (baked indirect lighting only)\r\n\t#ifdef USE_LIGHTMAP\r\n\r\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\r\n\r\n\t#else\r\n\r\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\r\n\r\n\t#endif\r\n\r\n\t// modulation\r\n\t#include <aomap_fragment>\r\n\r\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\r\n\r\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\r\n\r\n\t#include <normal_flip>\r\n\t#include <envmap_fragment>\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  10309. var meshbasic_vert = "#include <common>\r\n#include <uv_pars_vertex>\r\n#include <uv2_pars_vertex>\r\n#include <envmap_pars_vertex>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\t#include <uv2_vertex>\r\n\t#include <color_vertex>\r\n\t#include <skinbase_vertex>\r\n\r\n\t#ifdef USE_ENVMAP\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n\t#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\r\n\t#include <worldpos_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\t#include <envmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  10310. var meshlambert_frag = "uniform vec3 diffuse;\r\nuniform vec3 emissive;\r\nuniform float opacity;\r\n\r\nvarying vec3 vLightFront;\r\n\r\n#ifdef DOUBLE_SIDED\r\n\r\n\tvarying vec3 vLightBack;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <color_pars_fragment>\r\n#include <uv_pars_fragment>\r\n#include <uv2_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <aomap_pars_fragment>\r\n#include <lightmap_pars_fragment>\r\n#include <emissivemap_pars_fragment>\r\n#include <envmap_pars_fragment>\r\n#include <bsdfs>\r\n#include <lights_pars>\r\n#include <fog_pars_fragment>\r\n#include <shadowmap_pars_fragment>\r\n#include <shadowmask_pars_fragment>\r\n#include <specularmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\r\n\tvec3 totalEmissiveRadiance = emissive;\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <specularmap_fragment>\r\n\t#include <emissivemap_fragment>\r\n\r\n\t// accumulation\r\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\r\n\r\n\t#include <lightmap_fragment>\r\n\r\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\r\n\r\n\t#ifdef DOUBLE_SIDED\r\n\r\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\r\n\r\n\t#else\r\n\r\n\t\treflectedLight.directDiffuse = vLightFront;\r\n\r\n\t#endif\r\n\r\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\r\n\r\n\t// modulation\r\n\t#include <aomap_fragment>\r\n\r\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\r\n\r\n\t#include <normal_flip>\r\n\t#include <envmap_fragment>\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  10311. var meshlambert_vert = "#define LAMBERT\r\n\r\nvarying vec3 vLightFront;\r\n\r\n#ifdef DOUBLE_SIDED\r\n\r\n\tvarying vec3 vLightBack;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <uv2_pars_vertex>\r\n#include <envmap_pars_vertex>\r\n#include <bsdfs>\r\n#include <lights_pars>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\t#include <uv2_vertex>\r\n\t#include <color_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n\t#include <worldpos_vertex>\r\n\t#include <envmap_vertex>\r\n\t#include <lights_lambert_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  10312. var meshphong_frag = "#define PHONG\r\n\r\nuniform vec3 diffuse;\r\nuniform vec3 emissive;\r\nuniform vec3 specular;\r\nuniform float shininess;\r\nuniform float opacity;\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <color_pars_fragment>\r\n#include <uv_pars_fragment>\r\n#include <uv2_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <aomap_pars_fragment>\r\n#include <lightmap_pars_fragment>\r\n#include <emissivemap_pars_fragment>\r\n#include <envmap_pars_fragment>\r\n#include <gradientmap_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <bsdfs>\r\n#include <lights_pars>\r\n#include <lights_phong_pars_fragment>\r\n#include <shadowmap_pars_fragment>\r\n#include <bumpmap_pars_fragment>\r\n#include <normalmap_pars_fragment>\r\n#include <specularmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\r\n\tvec3 totalEmissiveRadiance = emissive;\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <specularmap_fragment>\r\n\t#include <normal_flip>\r\n\t#include <normal_fragment>\r\n\t#include <emissivemap_fragment>\r\n\r\n\t// accumulation\r\n\t#include <lights_phong_fragment>\r\n\t#include <lights_template>\r\n\r\n\t// modulation\r\n\t#include <aomap_fragment>\r\n\r\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\r\n\r\n\t#include <envmap_fragment>\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  10313. var meshphong_vert = "#define PHONG\r\n\r\nvarying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <uv2_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <envmap_pars_vertex>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\t#include <uv2_vertex>\r\n\t#include <color_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\r\n\r\n\tvNormal = normalize( transformedNormal );\r\n\r\n#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n\tvViewPosition = - mvPosition.xyz;\r\n\r\n\t#include <worldpos_vertex>\r\n\t#include <envmap_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  10314. var meshphysical_frag = "#define PHYSICAL\r\n\r\nuniform vec3 diffuse;\r\nuniform vec3 emissive;\r\nuniform float roughness;\r\nuniform float metalness;\r\nuniform float opacity;\r\n\r\n#ifndef STANDARD\r\n\tuniform float clearCoat;\r\n\tuniform float clearCoatRoughness;\r\n#endif\r\n\r\nvarying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <color_pars_fragment>\r\n#include <uv_pars_fragment>\r\n#include <uv2_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <aomap_pars_fragment>\r\n#include <lightmap_pars_fragment>\r\n#include <emissivemap_pars_fragment>\r\n#include <envmap_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <bsdfs>\r\n#include <cube_uv_reflection_fragment>\r\n#include <lights_pars>\r\n#include <lights_physical_pars_fragment>\r\n#include <shadowmap_pars_fragment>\r\n#include <bumpmap_pars_fragment>\r\n#include <normalmap_pars_fragment>\r\n#include <roughnessmap_pars_fragment>\r\n#include <metalnessmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\r\n\tvec3 totalEmissiveRadiance = emissive;\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <specularmap_fragment>\r\n\t#include <roughnessmap_fragment>\r\n\t#include <metalnessmap_fragment>\r\n\t#include <normal_flip>\r\n\t#include <normal_fragment>\r\n\t#include <emissivemap_fragment>\r\n\r\n\t// accumulation\r\n\t#include <lights_physical_fragment>\r\n\t#include <lights_template>\r\n\r\n\t// modulation\r\n\t#include <aomap_fragment>\r\n\r\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  10315. var meshphysical_vert = "#define PHYSICAL\r\n\r\nvarying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <uv2_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n#include <specularmap_pars_fragment>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\t#include <uv2_vertex>\r\n\t#include <color_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\r\n\r\n\tvNormal = normalize( transformedNormal );\r\n\r\n#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n\tvViewPosition = - mvPosition.xyz;\r\n\r\n\t#include <worldpos_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  10316. var normal_frag = "#define NORMAL\r\n\r\nuniform float opacity;\r\n\r\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\r\n\r\n\tvarying vec3 vViewPosition;\r\n\r\n#endif\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <packing>\r\n#include <uv_pars_fragment>\r\n#include <bumpmap_pars_fragment>\r\n#include <normalmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <normal_flip>\r\n\t#include <normal_fragment>\r\n\r\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\r\n\r\n}\r\n";
  10317. var normal_vert = "#define NORMAL\r\n\r\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\r\n\r\n\tvarying vec3 vViewPosition;\r\n\r\n#endif\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <uv_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\r\n\r\n\tvNormal = normalize( transformedNormal );\r\n\r\n#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\r\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\r\n\r\n\tvViewPosition = - mvPosition.xyz;\r\n\r\n#endif\r\n\r\n}\r\n";
  10318. var points_frag = "uniform vec3 diffuse;\r\nuniform float opacity;\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <color_pars_fragment>\r\n#include <map_particle_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <shadowmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec3 outgoingLight = vec3( 0.0 );\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_particle_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphatest_fragment>\r\n\r\n\toutgoingLight = diffuseColor.rgb;\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  10319. var points_vert = "uniform float size;\r\nuniform float scale;\r\n\r\n#include <common>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <color_vertex>\r\n\t#include <begin_vertex>\r\n\t#include <project_vertex>\r\n\r\n\t#ifdef USE_SIZEATTENUATION\r\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\r\n\t#else\r\n\t\tgl_PointSize = size;\r\n\t#endif\r\n\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\t#include <worldpos_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  10320. var shadow_frag = "uniform float opacity;\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <bsdfs>\r\n#include <lights_pars>\r\n#include <shadowmap_pars_fragment>\r\n#include <shadowmask_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\r\n\r\n}\r\n";
  10321. var shadow_vert = "#include <shadowmap_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <begin_vertex>\r\n\t#include <project_vertex>\r\n\t#include <worldpos_vertex>\r\n\t#include <shadowmap_vertex>\r\n\r\n}\r\n";
  10322. var ShaderChunk = {
  10323. alphamap_fragment: alphamap_fragment,
  10324. alphamap_pars_fragment: alphamap_pars_fragment,
  10325. alphatest_fragment: alphatest_fragment,
  10326. aomap_fragment: aomap_fragment,
  10327. aomap_pars_fragment: aomap_pars_fragment,
  10328. begin_vertex: begin_vertex,
  10329. beginnormal_vertex: beginnormal_vertex,
  10330. bsdfs: bsdfs,
  10331. bumpmap_pars_fragment: bumpmap_pars_fragment,
  10332. clipping_planes_fragment: clipping_planes_fragment,
  10333. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  10334. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  10335. clipping_planes_vertex: clipping_planes_vertex,
  10336. color_fragment: color_fragment,
  10337. color_pars_fragment: color_pars_fragment,
  10338. color_pars_vertex: color_pars_vertex,
  10339. color_vertex: color_vertex,
  10340. common: common,
  10341. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  10342. defaultnormal_vertex: defaultnormal_vertex,
  10343. displacementmap_pars_vertex: displacementmap_pars_vertex,
  10344. displacementmap_vertex: displacementmap_vertex,
  10345. emissivemap_fragment: emissivemap_fragment,
  10346. emissivemap_pars_fragment: emissivemap_pars_fragment,
  10347. encodings_fragment: encodings_fragment,
  10348. encodings_pars_fragment: encodings_pars_fragment,
  10349. envmap_fragment: envmap_fragment,
  10350. envmap_pars_fragment: envmap_pars_fragment,
  10351. envmap_pars_vertex: envmap_pars_vertex,
  10352. envmap_vertex: envmap_vertex,
  10353. fog_vertex: fog_vertex,
  10354. fog_pars_vertex: fog_pars_vertex,
  10355. fog_fragment: fog_fragment,
  10356. fog_pars_fragment: fog_pars_fragment,
  10357. gradientmap_pars_fragment: gradientmap_pars_fragment,
  10358. lightmap_fragment: lightmap_fragment,
  10359. lightmap_pars_fragment: lightmap_pars_fragment,
  10360. lights_lambert_vertex: lights_lambert_vertex,
  10361. lights_pars: lights_pars,
  10362. lights_phong_fragment: lights_phong_fragment,
  10363. lights_phong_pars_fragment: lights_phong_pars_fragment,
  10364. lights_physical_fragment: lights_physical_fragment,
  10365. lights_physical_pars_fragment: lights_physical_pars_fragment,
  10366. lights_template: lights_template,
  10367. logdepthbuf_fragment: logdepthbuf_fragment,
  10368. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  10369. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  10370. logdepthbuf_vertex: logdepthbuf_vertex,
  10371. map_fragment: map_fragment,
  10372. map_pars_fragment: map_pars_fragment,
  10373. map_particle_fragment: map_particle_fragment,
  10374. map_particle_pars_fragment: map_particle_pars_fragment,
  10375. metalnessmap_fragment: metalnessmap_fragment,
  10376. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  10377. morphnormal_vertex: morphnormal_vertex,
  10378. morphtarget_pars_vertex: morphtarget_pars_vertex,
  10379. morphtarget_vertex: morphtarget_vertex,
  10380. normal_flip: normal_flip,
  10381. normal_fragment: normal_fragment,
  10382. normalmap_pars_fragment: normalmap_pars_fragment,
  10383. packing: packing,
  10384. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  10385. project_vertex: project_vertex,
  10386. roughnessmap_fragment: roughnessmap_fragment,
  10387. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  10388. shadowmap_pars_fragment: shadowmap_pars_fragment,
  10389. shadowmap_pars_vertex: shadowmap_pars_vertex,
  10390. shadowmap_vertex: shadowmap_vertex,
  10391. shadowmask_pars_fragment: shadowmask_pars_fragment,
  10392. skinbase_vertex: skinbase_vertex,
  10393. skinning_pars_vertex: skinning_pars_vertex,
  10394. skinning_vertex: skinning_vertex,
  10395. skinnormal_vertex: skinnormal_vertex,
  10396. specularmap_fragment: specularmap_fragment,
  10397. specularmap_pars_fragment: specularmap_pars_fragment,
  10398. tonemapping_fragment: tonemapping_fragment,
  10399. tonemapping_pars_fragment: tonemapping_pars_fragment,
  10400. uv_pars_fragment: uv_pars_fragment,
  10401. uv_pars_vertex: uv_pars_vertex,
  10402. uv_vertex: uv_vertex,
  10403. uv2_pars_fragment: uv2_pars_fragment,
  10404. uv2_pars_vertex: uv2_pars_vertex,
  10405. uv2_vertex: uv2_vertex,
  10406. worldpos_vertex: worldpos_vertex,
  10407. cube_frag: cube_frag,
  10408. cube_vert: cube_vert,
  10409. depth_frag: depth_frag,
  10410. depth_vert: depth_vert,
  10411. distanceRGBA_frag: distanceRGBA_frag,
  10412. distanceRGBA_vert: distanceRGBA_vert,
  10413. equirect_frag: equirect_frag,
  10414. equirect_vert: equirect_vert,
  10415. linedashed_frag: linedashed_frag,
  10416. linedashed_vert: linedashed_vert,
  10417. meshbasic_frag: meshbasic_frag,
  10418. meshbasic_vert: meshbasic_vert,
  10419. meshlambert_frag: meshlambert_frag,
  10420. meshlambert_vert: meshlambert_vert,
  10421. meshphong_frag: meshphong_frag,
  10422. meshphong_vert: meshphong_vert,
  10423. meshphysical_frag: meshphysical_frag,
  10424. meshphysical_vert: meshphysical_vert,
  10425. normal_frag: normal_frag,
  10426. normal_vert: normal_vert,
  10427. points_frag: points_frag,
  10428. points_vert: points_vert,
  10429. shadow_frag: shadow_frag,
  10430. shadow_vert: shadow_vert
  10431. };
  10432. /**
  10433. * Uniforms library for shared webgl shaders
  10434. */
  10435. var UniformsLib = {
  10436. common: {
  10437. diffuse: { value: new Color( 0xeeeeee ) },
  10438. opacity: { value: 1.0 },
  10439. map: { value: null },
  10440. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  10441. specularMap: { value: null },
  10442. alphaMap: { value: null },
  10443. envMap: { value: null },
  10444. flipEnvMap: { value: - 1 },
  10445. reflectivity: { value: 1.0 },
  10446. refractionRatio: { value: 0.98 }
  10447. },
  10448. aomap: {
  10449. aoMap: { value: null },
  10450. aoMapIntensity: { value: 1 }
  10451. },
  10452. lightmap: {
  10453. lightMap: { value: null },
  10454. lightMapIntensity: { value: 1 }
  10455. },
  10456. emissivemap: {
  10457. emissiveMap: { value: null }
  10458. },
  10459. bumpmap: {
  10460. bumpMap: { value: null },
  10461. bumpScale: { value: 1 }
  10462. },
  10463. normalmap: {
  10464. normalMap: { value: null },
  10465. normalScale: { value: new Vector2( 1, 1 ) }
  10466. },
  10467. displacementmap: {
  10468. displacementMap: { value: null },
  10469. displacementScale: { value: 1 },
  10470. displacementBias: { value: 0 }
  10471. },
  10472. roughnessmap: {
  10473. roughnessMap: { value: null }
  10474. },
  10475. metalnessmap: {
  10476. metalnessMap: { value: null }
  10477. },
  10478. gradientmap: {
  10479. gradientMap: { value: null }
  10480. },
  10481. fog: {
  10482. fogDensity: { value: 0.00025 },
  10483. fogNear: { value: 1 },
  10484. fogFar: { value: 2000 },
  10485. fogColor: { value: new Color( 0xffffff ) }
  10486. },
  10487. lights: {
  10488. ambientLightColor: { value: [] },
  10489. directionalLights: { value: [], properties: {
  10490. direction: {},
  10491. color: {},
  10492. shadow: {},
  10493. shadowBias: {},
  10494. shadowRadius: {},
  10495. shadowMapSize: {}
  10496. } },
  10497. directionalShadowMap: { value: [] },
  10498. directionalShadowMatrix: { value: [] },
  10499. spotLights: { value: [], properties: {
  10500. color: {},
  10501. position: {},
  10502. direction: {},
  10503. distance: {},
  10504. coneCos: {},
  10505. penumbraCos: {},
  10506. decay: {},
  10507. shadow: {},
  10508. shadowBias: {},
  10509. shadowRadius: {},
  10510. shadowMapSize: {}
  10511. } },
  10512. spotShadowMap: { value: [] },
  10513. spotShadowMatrix: { value: [] },
  10514. pointLights: { value: [], properties: {
  10515. color: {},
  10516. position: {},
  10517. decay: {},
  10518. distance: {},
  10519. shadow: {},
  10520. shadowBias: {},
  10521. shadowRadius: {},
  10522. shadowMapSize: {}
  10523. } },
  10524. pointShadowMap: { value: [] },
  10525. pointShadowMatrix: { value: [] },
  10526. hemisphereLights: { value: [], properties: {
  10527. direction: {},
  10528. skyColor: {},
  10529. groundColor: {}
  10530. } },
  10531. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  10532. rectAreaLights: { value: [], properties: {
  10533. color: {},
  10534. position: {},
  10535. width: {},
  10536. height: {}
  10537. } }
  10538. },
  10539. points: {
  10540. diffuse: { value: new Color( 0xeeeeee ) },
  10541. opacity: { value: 1.0 },
  10542. size: { value: 1.0 },
  10543. scale: { value: 1.0 },
  10544. map: { value: null },
  10545. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  10546. }
  10547. };
  10548. /**
  10549. * @author alteredq / http://alteredqualia.com/
  10550. * @author mrdoob / http://mrdoob.com/
  10551. * @author mikael emtinger / http://gomo.se/
  10552. */
  10553. var ShaderLib = {
  10554. basic: {
  10555. uniforms: UniformsUtils.merge( [
  10556. UniformsLib.common,
  10557. UniformsLib.aomap,
  10558. UniformsLib.lightmap,
  10559. UniformsLib.fog
  10560. ] ),
  10561. vertexShader: ShaderChunk.meshbasic_vert,
  10562. fragmentShader: ShaderChunk.meshbasic_frag
  10563. },
  10564. lambert: {
  10565. uniforms: UniformsUtils.merge( [
  10566. UniformsLib.common,
  10567. UniformsLib.aomap,
  10568. UniformsLib.lightmap,
  10569. UniformsLib.emissivemap,
  10570. UniformsLib.fog,
  10571. UniformsLib.lights,
  10572. {
  10573. emissive: { value: new Color( 0x000000 ) }
  10574. }
  10575. ] ),
  10576. vertexShader: ShaderChunk.meshlambert_vert,
  10577. fragmentShader: ShaderChunk.meshlambert_frag
  10578. },
  10579. phong: {
  10580. uniforms: UniformsUtils.merge( [
  10581. UniformsLib.common,
  10582. UniformsLib.aomap,
  10583. UniformsLib.lightmap,
  10584. UniformsLib.emissivemap,
  10585. UniformsLib.bumpmap,
  10586. UniformsLib.normalmap,
  10587. UniformsLib.displacementmap,
  10588. UniformsLib.gradientmap,
  10589. UniformsLib.fog,
  10590. UniformsLib.lights,
  10591. {
  10592. emissive: { value: new Color( 0x000000 ) },
  10593. specular: { value: new Color( 0x111111 ) },
  10594. shininess: { value: 30 }
  10595. }
  10596. ] ),
  10597. vertexShader: ShaderChunk.meshphong_vert,
  10598. fragmentShader: ShaderChunk.meshphong_frag
  10599. },
  10600. standard: {
  10601. uniforms: UniformsUtils.merge( [
  10602. UniformsLib.common,
  10603. UniformsLib.aomap,
  10604. UniformsLib.lightmap,
  10605. UniformsLib.emissivemap,
  10606. UniformsLib.bumpmap,
  10607. UniformsLib.normalmap,
  10608. UniformsLib.displacementmap,
  10609. UniformsLib.roughnessmap,
  10610. UniformsLib.metalnessmap,
  10611. UniformsLib.fog,
  10612. UniformsLib.lights,
  10613. {
  10614. emissive: { value: new Color( 0x000000 ) },
  10615. roughness: { value: 0.5 },
  10616. metalness: { value: 0 },
  10617. envMapIntensity: { value: 1 } // temporary
  10618. }
  10619. ] ),
  10620. vertexShader: ShaderChunk.meshphysical_vert,
  10621. fragmentShader: ShaderChunk.meshphysical_frag
  10622. },
  10623. points: {
  10624. uniforms: UniformsUtils.merge( [
  10625. UniformsLib.points,
  10626. UniformsLib.fog
  10627. ] ),
  10628. vertexShader: ShaderChunk.points_vert,
  10629. fragmentShader: ShaderChunk.points_frag
  10630. },
  10631. dashed: {
  10632. uniforms: UniformsUtils.merge( [
  10633. UniformsLib.common,
  10634. UniformsLib.fog,
  10635. {
  10636. scale: { value: 1 },
  10637. dashSize: { value: 1 },
  10638. totalSize: { value: 2 }
  10639. }
  10640. ] ),
  10641. vertexShader: ShaderChunk.linedashed_vert,
  10642. fragmentShader: ShaderChunk.linedashed_frag
  10643. },
  10644. depth: {
  10645. uniforms: UniformsUtils.merge( [
  10646. UniformsLib.common,
  10647. UniformsLib.displacementmap
  10648. ] ),
  10649. vertexShader: ShaderChunk.depth_vert,
  10650. fragmentShader: ShaderChunk.depth_frag
  10651. },
  10652. normal: {
  10653. uniforms: UniformsUtils.merge( [
  10654. UniformsLib.common,
  10655. UniformsLib.bumpmap,
  10656. UniformsLib.normalmap,
  10657. UniformsLib.displacementmap,
  10658. {
  10659. opacity: { value: 1.0 }
  10660. }
  10661. ] ),
  10662. vertexShader: ShaderChunk.normal_vert,
  10663. fragmentShader: ShaderChunk.normal_frag
  10664. },
  10665. /* -------------------------------------------------------------------------
  10666. // Cube map shader
  10667. ------------------------------------------------------------------------- */
  10668. cube: {
  10669. uniforms: {
  10670. tCube: { value: null },
  10671. tFlip: { value: - 1 },
  10672. opacity: { value: 1.0 }
  10673. },
  10674. vertexShader: ShaderChunk.cube_vert,
  10675. fragmentShader: ShaderChunk.cube_frag
  10676. },
  10677. /* -------------------------------------------------------------------------
  10678. // Cube map shader
  10679. ------------------------------------------------------------------------- */
  10680. equirect: {
  10681. uniforms: {
  10682. tEquirect: { value: null },
  10683. tFlip: { value: - 1 }
  10684. },
  10685. vertexShader: ShaderChunk.equirect_vert,
  10686. fragmentShader: ShaderChunk.equirect_frag
  10687. },
  10688. distanceRGBA: {
  10689. uniforms: {
  10690. lightPos: { value: new Vector3() }
  10691. },
  10692. vertexShader: ShaderChunk.distanceRGBA_vert,
  10693. fragmentShader: ShaderChunk.distanceRGBA_frag
  10694. }
  10695. };
  10696. ShaderLib.physical = {
  10697. uniforms: UniformsUtils.merge( [
  10698. ShaderLib.standard.uniforms,
  10699. {
  10700. clearCoat: { value: 0 },
  10701. clearCoatRoughness: { value: 0 }
  10702. }
  10703. ] ),
  10704. vertexShader: ShaderChunk.meshphysical_vert,
  10705. fragmentShader: ShaderChunk.meshphysical_frag
  10706. };
  10707. /**
  10708. * @author mikael emtinger / http://gomo.se/
  10709. * @author alteredq / http://alteredqualia.com/
  10710. */
  10711. function LensFlarePlugin( renderer, flares ) {
  10712. var gl = renderer.context;
  10713. var state = renderer.state;
  10714. var vertexBuffer, elementBuffer;
  10715. var shader, program, attributes, uniforms;
  10716. var tempTexture, occlusionTexture;
  10717. function init() {
  10718. var vertices = new Float32Array( [
  10719. - 1, - 1, 0, 0,
  10720. 1, - 1, 1, 0,
  10721. 1, 1, 1, 1,
  10722. - 1, 1, 0, 1
  10723. ] );
  10724. var faces = new Uint16Array( [
  10725. 0, 1, 2,
  10726. 0, 2, 3
  10727. ] );
  10728. // buffers
  10729. vertexBuffer = gl.createBuffer();
  10730. elementBuffer = gl.createBuffer();
  10731. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  10732. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  10733. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  10734. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  10735. // textures
  10736. tempTexture = gl.createTexture();
  10737. occlusionTexture = gl.createTexture();
  10738. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  10739. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  10740. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  10741. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  10742. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  10743. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  10744. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  10745. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  10746. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  10747. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  10748. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  10749. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  10750. shader = {
  10751. vertexShader: [
  10752. "uniform lowp int renderType;",
  10753. "uniform vec3 screenPosition;",
  10754. "uniform vec2 scale;",
  10755. "uniform float rotation;",
  10756. "uniform sampler2D occlusionMap;",
  10757. "attribute vec2 position;",
  10758. "attribute vec2 uv;",
  10759. "varying vec2 vUV;",
  10760. "varying float vVisibility;",
  10761. "void main() {",
  10762. "vUV = uv;",
  10763. "vec2 pos = position;",
  10764. "if ( renderType == 2 ) {",
  10765. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  10766. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  10767. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  10768. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  10769. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  10770. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  10771. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  10772. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  10773. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  10774. "vVisibility = visibility.r / 9.0;",
  10775. "vVisibility *= 1.0 - visibility.g / 9.0;",
  10776. "vVisibility *= visibility.b / 9.0;",
  10777. "vVisibility *= 1.0 - visibility.a / 9.0;",
  10778. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  10779. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  10780. "}",
  10781. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  10782. "}"
  10783. ].join( "\n" ),
  10784. fragmentShader: [
  10785. "uniform lowp int renderType;",
  10786. "uniform sampler2D map;",
  10787. "uniform float opacity;",
  10788. "uniform vec3 color;",
  10789. "varying vec2 vUV;",
  10790. "varying float vVisibility;",
  10791. "void main() {",
  10792. // pink square
  10793. "if ( renderType == 0 ) {",
  10794. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  10795. // restore
  10796. "} else if ( renderType == 1 ) {",
  10797. "gl_FragColor = texture2D( map, vUV );",
  10798. // flare
  10799. "} else {",
  10800. "vec4 texture = texture2D( map, vUV );",
  10801. "texture.a *= opacity * vVisibility;",
  10802. "gl_FragColor = texture;",
  10803. "gl_FragColor.rgb *= color;",
  10804. "}",
  10805. "}"
  10806. ].join( "\n" )
  10807. };
  10808. program = createProgram( shader );
  10809. attributes = {
  10810. vertex: gl.getAttribLocation ( program, "position" ),
  10811. uv: gl.getAttribLocation ( program, "uv" )
  10812. };
  10813. uniforms = {
  10814. renderType: gl.getUniformLocation( program, "renderType" ),
  10815. map: gl.getUniformLocation( program, "map" ),
  10816. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  10817. opacity: gl.getUniformLocation( program, "opacity" ),
  10818. color: gl.getUniformLocation( program, "color" ),
  10819. scale: gl.getUniformLocation( program, "scale" ),
  10820. rotation: gl.getUniformLocation( program, "rotation" ),
  10821. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  10822. };
  10823. }
  10824. /*
  10825. * Render lens flares
  10826. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  10827. * reads these back and calculates occlusion.
  10828. */
  10829. this.render = function ( scene, camera, viewport ) {
  10830. if ( flares.length === 0 ) return;
  10831. var tempPosition = new Vector3();
  10832. var invAspect = viewport.w / viewport.z,
  10833. halfViewportWidth = viewport.z * 0.5,
  10834. halfViewportHeight = viewport.w * 0.5;
  10835. var size = 16 / viewport.w,
  10836. scale = new Vector2( size * invAspect, size );
  10837. var screenPosition = new Vector3( 1, 1, 0 ),
  10838. screenPositionPixels = new Vector2( 1, 1 );
  10839. var validArea = new Box2();
  10840. validArea.min.set( viewport.x, viewport.y );
  10841. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  10842. if ( program === undefined ) {
  10843. init();
  10844. }
  10845. gl.useProgram( program );
  10846. state.initAttributes();
  10847. state.enableAttribute( attributes.vertex );
  10848. state.enableAttribute( attributes.uv );
  10849. state.disableUnusedAttributes();
  10850. // loop through all lens flares to update their occlusion and positions
  10851. // setup gl and common used attribs/uniforms
  10852. gl.uniform1i( uniforms.occlusionMap, 0 );
  10853. gl.uniform1i( uniforms.map, 1 );
  10854. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  10855. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  10856. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  10857. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  10858. state.disable( gl.CULL_FACE );
  10859. state.setDepthWrite( false );
  10860. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  10861. size = 16 / viewport.w;
  10862. scale.set( size * invAspect, size );
  10863. // calc object screen position
  10864. var flare = flares[ i ];
  10865. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  10866. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  10867. tempPosition.applyMatrix4( camera.projectionMatrix );
  10868. // setup arrays for gl programs
  10869. screenPosition.copy( tempPosition );
  10870. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  10871. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  10872. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  10873. // screen cull
  10874. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  10875. // save current RGB to temp texture
  10876. state.activeTexture( gl.TEXTURE0 );
  10877. state.bindTexture( gl.TEXTURE_2D, null );
  10878. state.activeTexture( gl.TEXTURE1 );
  10879. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  10880. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  10881. // render pink quad
  10882. gl.uniform1i( uniforms.renderType, 0 );
  10883. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  10884. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  10885. state.disable( gl.BLEND );
  10886. state.enable( gl.DEPTH_TEST );
  10887. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  10888. // copy result to occlusionMap
  10889. state.activeTexture( gl.TEXTURE0 );
  10890. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  10891. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  10892. // restore graphics
  10893. gl.uniform1i( uniforms.renderType, 1 );
  10894. state.disable( gl.DEPTH_TEST );
  10895. state.activeTexture( gl.TEXTURE1 );
  10896. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  10897. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  10898. // update object positions
  10899. flare.positionScreen.copy( screenPosition );
  10900. if ( flare.customUpdateCallback ) {
  10901. flare.customUpdateCallback( flare );
  10902. } else {
  10903. flare.updateLensFlares();
  10904. }
  10905. // render flares
  10906. gl.uniform1i( uniforms.renderType, 2 );
  10907. state.enable( gl.BLEND );
  10908. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  10909. var sprite = flare.lensFlares[ j ];
  10910. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  10911. screenPosition.x = sprite.x;
  10912. screenPosition.y = sprite.y;
  10913. screenPosition.z = sprite.z;
  10914. size = sprite.size * sprite.scale / viewport.w;
  10915. scale.x = size * invAspect;
  10916. scale.y = size;
  10917. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  10918. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  10919. gl.uniform1f( uniforms.rotation, sprite.rotation );
  10920. gl.uniform1f( uniforms.opacity, sprite.opacity );
  10921. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  10922. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  10923. renderer.setTexture2D( sprite.texture, 1 );
  10924. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  10925. }
  10926. }
  10927. }
  10928. }
  10929. // restore gl
  10930. state.enable( gl.CULL_FACE );
  10931. state.enable( gl.DEPTH_TEST );
  10932. state.setDepthWrite( true );
  10933. renderer.resetGLState();
  10934. };
  10935. function createProgram( shader ) {
  10936. var program = gl.createProgram();
  10937. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  10938. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  10939. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  10940. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  10941. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  10942. gl.compileShader( fragmentShader );
  10943. gl.compileShader( vertexShader );
  10944. gl.attachShader( program, fragmentShader );
  10945. gl.attachShader( program, vertexShader );
  10946. gl.linkProgram( program );
  10947. return program;
  10948. }
  10949. }
  10950. /**
  10951. * @author mikael emtinger / http://gomo.se/
  10952. * @author alteredq / http://alteredqualia.com/
  10953. */
  10954. function SpritePlugin( renderer, sprites ) {
  10955. var gl = renderer.context;
  10956. var state = renderer.state;
  10957. var vertexBuffer, elementBuffer;
  10958. var program, attributes, uniforms;
  10959. var texture;
  10960. // decompose matrixWorld
  10961. var spritePosition = new Vector3();
  10962. var spriteRotation = new Quaternion();
  10963. var spriteScale = new Vector3();
  10964. function init() {
  10965. var vertices = new Float32Array( [
  10966. - 0.5, - 0.5, 0, 0,
  10967. 0.5, - 0.5, 1, 0,
  10968. 0.5, 0.5, 1, 1,
  10969. - 0.5, 0.5, 0, 1
  10970. ] );
  10971. var faces = new Uint16Array( [
  10972. 0, 1, 2,
  10973. 0, 2, 3
  10974. ] );
  10975. vertexBuffer = gl.createBuffer();
  10976. elementBuffer = gl.createBuffer();
  10977. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  10978. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  10979. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  10980. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  10981. program = createProgram();
  10982. attributes = {
  10983. position: gl.getAttribLocation ( program, 'position' ),
  10984. uv: gl.getAttribLocation ( program, 'uv' )
  10985. };
  10986. uniforms = {
  10987. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  10988. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  10989. rotation: gl.getUniformLocation( program, 'rotation' ),
  10990. scale: gl.getUniformLocation( program, 'scale' ),
  10991. color: gl.getUniformLocation( program, 'color' ),
  10992. map: gl.getUniformLocation( program, 'map' ),
  10993. opacity: gl.getUniformLocation( program, 'opacity' ),
  10994. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  10995. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  10996. fogType: gl.getUniformLocation( program, 'fogType' ),
  10997. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  10998. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  10999. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  11000. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  11001. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  11002. };
  11003. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  11004. canvas.width = 8;
  11005. canvas.height = 8;
  11006. var context = canvas.getContext( '2d' );
  11007. context.fillStyle = 'white';
  11008. context.fillRect( 0, 0, 8, 8 );
  11009. texture = new Texture( canvas );
  11010. texture.needsUpdate = true;
  11011. }
  11012. this.render = function ( scene, camera ) {
  11013. if ( sprites.length === 0 ) return;
  11014. // setup gl
  11015. if ( program === undefined ) {
  11016. init();
  11017. }
  11018. gl.useProgram( program );
  11019. state.initAttributes();
  11020. state.enableAttribute( attributes.position );
  11021. state.enableAttribute( attributes.uv );
  11022. state.disableUnusedAttributes();
  11023. state.disable( gl.CULL_FACE );
  11024. state.enable( gl.BLEND );
  11025. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  11026. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  11027. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  11028. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  11029. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  11030. state.activeTexture( gl.TEXTURE0 );
  11031. gl.uniform1i( uniforms.map, 0 );
  11032. var oldFogType = 0;
  11033. var sceneFogType = 0;
  11034. var fog = scene.fog;
  11035. if ( fog ) {
  11036. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  11037. if ( fog.isFog ) {
  11038. gl.uniform1f( uniforms.fogNear, fog.near );
  11039. gl.uniform1f( uniforms.fogFar, fog.far );
  11040. gl.uniform1i( uniforms.fogType, 1 );
  11041. oldFogType = 1;
  11042. sceneFogType = 1;
  11043. } else if ( fog.isFogExp2 ) {
  11044. gl.uniform1f( uniforms.fogDensity, fog.density );
  11045. gl.uniform1i( uniforms.fogType, 2 );
  11046. oldFogType = 2;
  11047. sceneFogType = 2;
  11048. }
  11049. } else {
  11050. gl.uniform1i( uniforms.fogType, 0 );
  11051. oldFogType = 0;
  11052. sceneFogType = 0;
  11053. }
  11054. // update positions and sort
  11055. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  11056. var sprite = sprites[ i ];
  11057. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  11058. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  11059. }
  11060. sprites.sort( painterSortStable );
  11061. // render all sprites
  11062. var scale = [];
  11063. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  11064. var sprite = sprites[ i ];
  11065. var material = sprite.material;
  11066. if ( material.visible === false ) continue;
  11067. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  11068. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  11069. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  11070. scale[ 0 ] = spriteScale.x;
  11071. scale[ 1 ] = spriteScale.y;
  11072. var fogType = 0;
  11073. if ( scene.fog && material.fog ) {
  11074. fogType = sceneFogType;
  11075. }
  11076. if ( oldFogType !== fogType ) {
  11077. gl.uniform1i( uniforms.fogType, fogType );
  11078. oldFogType = fogType;
  11079. }
  11080. if ( material.map !== null ) {
  11081. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  11082. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  11083. } else {
  11084. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  11085. gl.uniform2f( uniforms.uvScale, 1, 1 );
  11086. }
  11087. gl.uniform1f( uniforms.opacity, material.opacity );
  11088. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  11089. gl.uniform1f( uniforms.rotation, material.rotation );
  11090. gl.uniform2fv( uniforms.scale, scale );
  11091. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11092. state.setDepthTest( material.depthTest );
  11093. state.setDepthWrite( material.depthWrite );
  11094. if ( material.map ) {
  11095. renderer.setTexture2D( material.map, 0 );
  11096. } else {
  11097. renderer.setTexture2D( texture, 0 );
  11098. }
  11099. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  11100. }
  11101. // restore gl
  11102. state.enable( gl.CULL_FACE );
  11103. renderer.resetGLState();
  11104. };
  11105. function createProgram() {
  11106. var program = gl.createProgram();
  11107. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  11108. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  11109. gl.shaderSource( vertexShader, [
  11110. 'precision ' + renderer.getPrecision() + ' float;',
  11111. 'uniform mat4 modelViewMatrix;',
  11112. 'uniform mat4 projectionMatrix;',
  11113. 'uniform float rotation;',
  11114. 'uniform vec2 scale;',
  11115. 'uniform vec2 uvOffset;',
  11116. 'uniform vec2 uvScale;',
  11117. 'attribute vec2 position;',
  11118. 'attribute vec2 uv;',
  11119. 'varying vec2 vUV;',
  11120. 'void main() {',
  11121. 'vUV = uvOffset + uv * uvScale;',
  11122. 'vec2 alignedPosition = position * scale;',
  11123. 'vec2 rotatedPosition;',
  11124. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  11125. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  11126. 'vec4 finalPosition;',
  11127. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  11128. 'finalPosition.xy += rotatedPosition;',
  11129. 'finalPosition = projectionMatrix * finalPosition;',
  11130. 'gl_Position = finalPosition;',
  11131. '}'
  11132. ].join( '\n' ) );
  11133. gl.shaderSource( fragmentShader, [
  11134. 'precision ' + renderer.getPrecision() + ' float;',
  11135. 'uniform vec3 color;',
  11136. 'uniform sampler2D map;',
  11137. 'uniform float opacity;',
  11138. 'uniform int fogType;',
  11139. 'uniform vec3 fogColor;',
  11140. 'uniform float fogDensity;',
  11141. 'uniform float fogNear;',
  11142. 'uniform float fogFar;',
  11143. 'uniform float alphaTest;',
  11144. 'varying vec2 vUV;',
  11145. 'void main() {',
  11146. 'vec4 texture = texture2D( map, vUV );',
  11147. 'if ( texture.a < alphaTest ) discard;',
  11148. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  11149. 'if ( fogType > 0 ) {',
  11150. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  11151. 'float fogFactor = 0.0;',
  11152. 'if ( fogType == 1 ) {',
  11153. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  11154. '} else {',
  11155. 'const float LOG2 = 1.442695;',
  11156. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  11157. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  11158. '}',
  11159. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  11160. '}',
  11161. '}'
  11162. ].join( '\n' ) );
  11163. gl.compileShader( vertexShader );
  11164. gl.compileShader( fragmentShader );
  11165. gl.attachShader( program, vertexShader );
  11166. gl.attachShader( program, fragmentShader );
  11167. gl.linkProgram( program );
  11168. return program;
  11169. }
  11170. function painterSortStable( a, b ) {
  11171. if ( a.renderOrder !== b.renderOrder ) {
  11172. return a.renderOrder - b.renderOrder;
  11173. } else if ( a.z !== b.z ) {
  11174. return b.z - a.z;
  11175. } else {
  11176. return b.id - a.id;
  11177. }
  11178. }
  11179. }
  11180. /**
  11181. * @author szimek / https://github.com/szimek/
  11182. * @author alteredq / http://alteredqualia.com/
  11183. * @author Marius Kintel / https://github.com/kintel
  11184. */
  11185. /*
  11186. In options, we can specify:
  11187. * Texture parameters for an auto-generated target texture
  11188. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  11189. */
  11190. function WebGLRenderTarget( width, height, options ) {
  11191. this.uuid = _Math.generateUUID();
  11192. this.width = width;
  11193. this.height = height;
  11194. this.scissor = new Vector4( 0, 0, width, height );
  11195. this.scissorTest = false;
  11196. this.viewport = new Vector4( 0, 0, width, height );
  11197. options = options || {};
  11198. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  11199. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  11200. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  11201. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  11202. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  11203. }
  11204. WebGLRenderTarget.prototype = {
  11205. constructor: WebGLRenderTarget,
  11206. isWebGLRenderTarget: true,
  11207. setSize: function ( width, height ) {
  11208. if ( this.width !== width || this.height !== height ) {
  11209. this.width = width;
  11210. this.height = height;
  11211. this.dispose();
  11212. }
  11213. this.viewport.set( 0, 0, width, height );
  11214. this.scissor.set( 0, 0, width, height );
  11215. },
  11216. clone: function () {
  11217. return new this.constructor().copy( this );
  11218. },
  11219. copy: function ( source ) {
  11220. this.width = source.width;
  11221. this.height = source.height;
  11222. this.viewport.copy( source.viewport );
  11223. this.texture = source.texture.clone();
  11224. this.depthBuffer = source.depthBuffer;
  11225. this.stencilBuffer = source.stencilBuffer;
  11226. this.depthTexture = source.depthTexture;
  11227. return this;
  11228. },
  11229. dispose: function () {
  11230. this.dispatchEvent( { type: 'dispose' } );
  11231. }
  11232. };
  11233. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype );
  11234. /**
  11235. * @author mrdoob / http://mrdoob.com/
  11236. * @author alteredq / http://alteredqualia.com/
  11237. * @author bhouston / https://clara.io
  11238. * @author WestLangley / http://github.com/WestLangley
  11239. *
  11240. * parameters = {
  11241. *
  11242. * opacity: <float>,
  11243. *
  11244. * map: new THREE.Texture( <Image> ),
  11245. *
  11246. * alphaMap: new THREE.Texture( <Image> ),
  11247. *
  11248. * displacementMap: new THREE.Texture( <Image> ),
  11249. * displacementScale: <float>,
  11250. * displacementBias: <float>,
  11251. *
  11252. * wireframe: <boolean>,
  11253. * wireframeLinewidth: <float>
  11254. * }
  11255. */
  11256. function MeshDepthMaterial( parameters ) {
  11257. Material.call( this );
  11258. this.type = 'MeshDepthMaterial';
  11259. this.depthPacking = BasicDepthPacking;
  11260. this.skinning = false;
  11261. this.morphTargets = false;
  11262. this.map = null;
  11263. this.alphaMap = null;
  11264. this.displacementMap = null;
  11265. this.displacementScale = 1;
  11266. this.displacementBias = 0;
  11267. this.wireframe = false;
  11268. this.wireframeLinewidth = 1;
  11269. this.fog = false;
  11270. this.lights = false;
  11271. this.setValues( parameters );
  11272. }
  11273. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  11274. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  11275. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  11276. MeshDepthMaterial.prototype.copy = function ( source ) {
  11277. Material.prototype.copy.call( this, source );
  11278. this.depthPacking = source.depthPacking;
  11279. this.skinning = source.skinning;
  11280. this.morphTargets = source.morphTargets;
  11281. this.map = source.map;
  11282. this.alphaMap = source.alphaMap;
  11283. this.displacementMap = source.displacementMap;
  11284. this.displacementScale = source.displacementScale;
  11285. this.displacementBias = source.displacementBias;
  11286. this.wireframe = source.wireframe;
  11287. this.wireframeLinewidth = source.wireframeLinewidth;
  11288. return this;
  11289. };
  11290. /**
  11291. * @author mrdoob / http://mrdoob.com/
  11292. * @author alteredq / http://alteredqualia.com/
  11293. * @author bhouston / http://clara.io
  11294. */
  11295. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  11296. this.planes = [
  11297. ( p0 !== undefined ) ? p0 : new Plane(),
  11298. ( p1 !== undefined ) ? p1 : new Plane(),
  11299. ( p2 !== undefined ) ? p2 : new Plane(),
  11300. ( p3 !== undefined ) ? p3 : new Plane(),
  11301. ( p4 !== undefined ) ? p4 : new Plane(),
  11302. ( p5 !== undefined ) ? p5 : new Plane()
  11303. ];
  11304. }
  11305. Frustum.prototype = {
  11306. constructor: Frustum,
  11307. set: function ( p0, p1, p2, p3, p4, p5 ) {
  11308. var planes = this.planes;
  11309. planes[ 0 ].copy( p0 );
  11310. planes[ 1 ].copy( p1 );
  11311. planes[ 2 ].copy( p2 );
  11312. planes[ 3 ].copy( p3 );
  11313. planes[ 4 ].copy( p4 );
  11314. planes[ 5 ].copy( p5 );
  11315. return this;
  11316. },
  11317. clone: function () {
  11318. return new this.constructor().copy( this );
  11319. },
  11320. copy: function ( frustum ) {
  11321. var planes = this.planes;
  11322. for ( var i = 0; i < 6; i ++ ) {
  11323. planes[ i ].copy( frustum.planes[ i ] );
  11324. }
  11325. return this;
  11326. },
  11327. setFromMatrix: function ( m ) {
  11328. var planes = this.planes;
  11329. var me = m.elements;
  11330. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  11331. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  11332. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  11333. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  11334. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  11335. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  11336. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  11337. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  11338. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  11339. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  11340. return this;
  11341. },
  11342. intersectsObject: function () {
  11343. var sphere = new Sphere();
  11344. return function intersectsObject( object ) {
  11345. var geometry = object.geometry;
  11346. if ( geometry.boundingSphere === null )
  11347. geometry.computeBoundingSphere();
  11348. sphere.copy( geometry.boundingSphere )
  11349. .applyMatrix4( object.matrixWorld );
  11350. return this.intersectsSphere( sphere );
  11351. };
  11352. }(),
  11353. intersectsSprite: function () {
  11354. var sphere = new Sphere();
  11355. return function intersectsSprite( sprite ) {
  11356. sphere.center.set( 0, 0, 0 );
  11357. sphere.radius = 0.7071067811865476;
  11358. sphere.applyMatrix4( sprite.matrixWorld );
  11359. return this.intersectsSphere( sphere );
  11360. };
  11361. }(),
  11362. intersectsSphere: function ( sphere ) {
  11363. var planes = this.planes;
  11364. var center = sphere.center;
  11365. var negRadius = - sphere.radius;
  11366. for ( var i = 0; i < 6; i ++ ) {
  11367. var distance = planes[ i ].distanceToPoint( center );
  11368. if ( distance < negRadius ) {
  11369. return false;
  11370. }
  11371. }
  11372. return true;
  11373. },
  11374. intersectsBox: function () {
  11375. var p1 = new Vector3(),
  11376. p2 = new Vector3();
  11377. return function intersectsBox( box ) {
  11378. var planes = this.planes;
  11379. for ( var i = 0; i < 6 ; i ++ ) {
  11380. var plane = planes[ i ];
  11381. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  11382. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  11383. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  11384. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  11385. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  11386. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  11387. var d1 = plane.distanceToPoint( p1 );
  11388. var d2 = plane.distanceToPoint( p2 );
  11389. // if both outside plane, no intersection
  11390. if ( d1 < 0 && d2 < 0 ) {
  11391. return false;
  11392. }
  11393. }
  11394. return true;
  11395. };
  11396. }(),
  11397. containsPoint: function ( point ) {
  11398. var planes = this.planes;
  11399. for ( var i = 0; i < 6; i ++ ) {
  11400. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  11401. return false;
  11402. }
  11403. }
  11404. return true;
  11405. }
  11406. };
  11407. /**
  11408. * @author alteredq / http://alteredqualia.com/
  11409. * @author mrdoob / http://mrdoob.com/
  11410. */
  11411. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  11412. var _gl = _renderer.context,
  11413. _state = _renderer.state,
  11414. _frustum = new Frustum(),
  11415. _projScreenMatrix = new Matrix4(),
  11416. _lightShadows = _lights.shadows,
  11417. _shadowMapSize = new Vector2(),
  11418. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  11419. _lookTarget = new Vector3(),
  11420. _lightPositionWorld = new Vector3(),
  11421. _renderList = [],
  11422. _MorphingFlag = 1,
  11423. _SkinningFlag = 2,
  11424. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  11425. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  11426. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  11427. _materialCache = {};
  11428. var cubeDirections = [
  11429. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  11430. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  11431. ];
  11432. var cubeUps = [
  11433. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  11434. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  11435. ];
  11436. var cube2DViewPorts = [
  11437. new Vector4(), new Vector4(), new Vector4(),
  11438. new Vector4(), new Vector4(), new Vector4()
  11439. ];
  11440. // init
  11441. var depthMaterialTemplate = new MeshDepthMaterial();
  11442. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  11443. depthMaterialTemplate.clipping = true;
  11444. var distanceShader = ShaderLib[ "distanceRGBA" ];
  11445. var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms );
  11446. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  11447. var useMorphing = ( i & _MorphingFlag ) !== 0;
  11448. var useSkinning = ( i & _SkinningFlag ) !== 0;
  11449. var depthMaterial = depthMaterialTemplate.clone();
  11450. depthMaterial.morphTargets = useMorphing;
  11451. depthMaterial.skinning = useSkinning;
  11452. _depthMaterials[ i ] = depthMaterial;
  11453. var distanceMaterial = new ShaderMaterial( {
  11454. defines: {
  11455. 'USE_SHADOWMAP': ''
  11456. },
  11457. uniforms: distanceUniforms,
  11458. vertexShader: distanceShader.vertexShader,
  11459. fragmentShader: distanceShader.fragmentShader,
  11460. morphTargets: useMorphing,
  11461. skinning: useSkinning,
  11462. clipping: true
  11463. } );
  11464. _distanceMaterials[ i ] = distanceMaterial;
  11465. }
  11466. //
  11467. var scope = this;
  11468. this.enabled = false;
  11469. this.autoUpdate = true;
  11470. this.needsUpdate = false;
  11471. this.type = PCFShadowMap;
  11472. this.renderReverseSided = true;
  11473. this.renderSingleSided = true;
  11474. this.render = function ( scene, camera ) {
  11475. if ( scope.enabled === false ) return;
  11476. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  11477. if ( _lightShadows.length === 0 ) return;
  11478. // Set GL state for depth map.
  11479. _state.buffers.color.setClear( 1, 1, 1, 1 );
  11480. _state.disable( _gl.BLEND );
  11481. _state.setDepthTest( true );
  11482. _state.setScissorTest( false );
  11483. // render depth map
  11484. var faceCount, isPointLight;
  11485. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  11486. var light = _lightShadows[ i ];
  11487. var shadow = light.shadow;
  11488. if ( shadow === undefined ) {
  11489. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  11490. continue;
  11491. }
  11492. var shadowCamera = shadow.camera;
  11493. _shadowMapSize.copy( shadow.mapSize );
  11494. _shadowMapSize.min( _maxShadowMapSize );
  11495. if ( light && light.isPointLight ) {
  11496. faceCount = 6;
  11497. isPointLight = true;
  11498. var vpWidth = _shadowMapSize.x;
  11499. var vpHeight = _shadowMapSize.y;
  11500. // These viewports map a cube-map onto a 2D texture with the
  11501. // following orientation:
  11502. //
  11503. // xzXZ
  11504. // y Y
  11505. //
  11506. // X - Positive x direction
  11507. // x - Negative x direction
  11508. // Y - Positive y direction
  11509. // y - Negative y direction
  11510. // Z - Positive z direction
  11511. // z - Negative z direction
  11512. // positive X
  11513. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  11514. // negative X
  11515. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  11516. // positive Z
  11517. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  11518. // negative Z
  11519. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  11520. // positive Y
  11521. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  11522. // negative Y
  11523. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  11524. _shadowMapSize.x *= 4.0;
  11525. _shadowMapSize.y *= 2.0;
  11526. } else {
  11527. faceCount = 1;
  11528. isPointLight = false;
  11529. }
  11530. if ( shadow.map === null ) {
  11531. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  11532. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11533. shadowCamera.updateProjectionMatrix();
  11534. }
  11535. if ( shadow.isSpotLightShadow ) {
  11536. shadow.update( light );
  11537. }
  11538. // TODO (abelnation / sam-g-steel): is this needed?
  11539. if (shadow && shadow.isRectAreaLightShadow ) {
  11540. shadow.update( light );
  11541. }
  11542. var shadowMap = shadow.map;
  11543. var shadowMatrix = shadow.matrix;
  11544. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  11545. shadowCamera.position.copy( _lightPositionWorld );
  11546. _renderer.setRenderTarget( shadowMap );
  11547. _renderer.clear();
  11548. // render shadow map for each cube face (if omni-directional) or
  11549. // run a single pass if not
  11550. for ( var face = 0; face < faceCount; face ++ ) {
  11551. if ( isPointLight ) {
  11552. _lookTarget.copy( shadowCamera.position );
  11553. _lookTarget.add( cubeDirections[ face ] );
  11554. shadowCamera.up.copy( cubeUps[ face ] );
  11555. shadowCamera.lookAt( _lookTarget );
  11556. var vpDimensions = cube2DViewPorts[ face ];
  11557. _state.viewport( vpDimensions );
  11558. } else {
  11559. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  11560. shadowCamera.lookAt( _lookTarget );
  11561. }
  11562. shadowCamera.updateMatrixWorld();
  11563. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  11564. // compute shadow matrix
  11565. shadowMatrix.set(
  11566. 0.5, 0.0, 0.0, 0.5,
  11567. 0.0, 0.5, 0.0, 0.5,
  11568. 0.0, 0.0, 0.5, 0.5,
  11569. 0.0, 0.0, 0.0, 1.0
  11570. );
  11571. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  11572. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  11573. // update camera matrices and frustum
  11574. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  11575. _frustum.setFromMatrix( _projScreenMatrix );
  11576. // set object matrices & frustum culling
  11577. _renderList.length = 0;
  11578. projectObject( scene, camera, shadowCamera );
  11579. // render shadow map
  11580. // render regular objects
  11581. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  11582. var object = _renderList[ j ];
  11583. var geometry = _objects.update( object );
  11584. var material = object.material;
  11585. if ( material && material.isMultiMaterial ) {
  11586. var groups = geometry.groups;
  11587. var materials = material.materials;
  11588. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  11589. var group = groups[ k ];
  11590. var groupMaterial = materials[ group.materialIndex ];
  11591. if ( groupMaterial.visible === true ) {
  11592. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  11593. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  11594. }
  11595. }
  11596. } else {
  11597. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  11598. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  11599. }
  11600. }
  11601. }
  11602. }
  11603. // Restore GL state.
  11604. var clearColor = _renderer.getClearColor(),
  11605. clearAlpha = _renderer.getClearAlpha();
  11606. _renderer.setClearColor( clearColor, clearAlpha );
  11607. scope.needsUpdate = false;
  11608. };
  11609. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  11610. var geometry = object.geometry;
  11611. var result = null;
  11612. var materialVariants = _depthMaterials;
  11613. var customMaterial = object.customDepthMaterial;
  11614. if ( isPointLight ) {
  11615. materialVariants = _distanceMaterials;
  11616. customMaterial = object.customDistanceMaterial;
  11617. }
  11618. if ( ! customMaterial ) {
  11619. var useMorphing = false;
  11620. if ( material.morphTargets ) {
  11621. if ( geometry && geometry.isBufferGeometry ) {
  11622. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  11623. } else if ( geometry && geometry.isGeometry ) {
  11624. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  11625. }
  11626. }
  11627. var useSkinning = object.isSkinnedMesh && material.skinning;
  11628. var variantIndex = 0;
  11629. if ( useMorphing ) variantIndex |= _MorphingFlag;
  11630. if ( useSkinning ) variantIndex |= _SkinningFlag;
  11631. result = materialVariants[ variantIndex ];
  11632. } else {
  11633. result = customMaterial;
  11634. }
  11635. if ( _renderer.localClippingEnabled &&
  11636. material.clipShadows === true &&
  11637. material.clippingPlanes.length !== 0 ) {
  11638. // in this case we need a unique material instance reflecting the
  11639. // appropriate state
  11640. var keyA = result.uuid, keyB = material.uuid;
  11641. var materialsForVariant = _materialCache[ keyA ];
  11642. if ( materialsForVariant === undefined ) {
  11643. materialsForVariant = {};
  11644. _materialCache[ keyA ] = materialsForVariant;
  11645. }
  11646. var cachedMaterial = materialsForVariant[ keyB ];
  11647. if ( cachedMaterial === undefined ) {
  11648. cachedMaterial = result.clone();
  11649. materialsForVariant[ keyB ] = cachedMaterial;
  11650. }
  11651. result = cachedMaterial;
  11652. }
  11653. result.visible = material.visible;
  11654. result.wireframe = material.wireframe;
  11655. var side = material.side;
  11656. if ( scope.renderSingleSided && side == DoubleSide ) {
  11657. side = FrontSide;
  11658. }
  11659. if ( scope.renderReverseSided ) {
  11660. if ( side === FrontSide ) side = BackSide;
  11661. else if ( side === BackSide ) side = FrontSide;
  11662. }
  11663. result.side = side;
  11664. result.clipShadows = material.clipShadows;
  11665. result.clippingPlanes = material.clippingPlanes;
  11666. result.wireframeLinewidth = material.wireframeLinewidth;
  11667. result.linewidth = material.linewidth;
  11668. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  11669. result.uniforms.lightPos.value.copy( lightPositionWorld );
  11670. }
  11671. return result;
  11672. }
  11673. function projectObject( object, camera, shadowCamera ) {
  11674. if ( object.visible === false ) return;
  11675. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  11676. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  11677. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  11678. var material = object.material;
  11679. if ( material.visible === true ) {
  11680. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  11681. _renderList.push( object );
  11682. }
  11683. }
  11684. }
  11685. var children = object.children;
  11686. for ( var i = 0, l = children.length; i < l; i ++ ) {
  11687. projectObject( children[ i ], camera, shadowCamera );
  11688. }
  11689. }
  11690. }
  11691. /**
  11692. * @author bhouston / http://clara.io
  11693. * @author mrdoob / http://mrdoob.com/
  11694. */
  11695. function Triangle( a, b, c ) {
  11696. this.a = ( a !== undefined ) ? a : new Vector3();
  11697. this.b = ( b !== undefined ) ? b : new Vector3();
  11698. this.c = ( c !== undefined ) ? c : new Vector3();
  11699. }
  11700. Triangle.normal = function () {
  11701. var v0 = new Vector3();
  11702. return function normal( a, b, c, optionalTarget ) {
  11703. var result = optionalTarget || new Vector3();
  11704. result.subVectors( c, b );
  11705. v0.subVectors( a, b );
  11706. result.cross( v0 );
  11707. var resultLengthSq = result.lengthSq();
  11708. if ( resultLengthSq > 0 ) {
  11709. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  11710. }
  11711. return result.set( 0, 0, 0 );
  11712. };
  11713. }();
  11714. // static/instance method to calculate barycentric coordinates
  11715. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11716. Triangle.barycoordFromPoint = function () {
  11717. var v0 = new Vector3();
  11718. var v1 = new Vector3();
  11719. var v2 = new Vector3();
  11720. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  11721. v0.subVectors( c, a );
  11722. v1.subVectors( b, a );
  11723. v2.subVectors( point, a );
  11724. var dot00 = v0.dot( v0 );
  11725. var dot01 = v0.dot( v1 );
  11726. var dot02 = v0.dot( v2 );
  11727. var dot11 = v1.dot( v1 );
  11728. var dot12 = v1.dot( v2 );
  11729. var denom = ( dot00 * dot11 - dot01 * dot01 );
  11730. var result = optionalTarget || new Vector3();
  11731. // collinear or singular triangle
  11732. if ( denom === 0 ) {
  11733. // arbitrary location outside of triangle?
  11734. // not sure if this is the best idea, maybe should be returning undefined
  11735. return result.set( - 2, - 1, - 1 );
  11736. }
  11737. var invDenom = 1 / denom;
  11738. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11739. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11740. // barycentric coordinates must always sum to 1
  11741. return result.set( 1 - u - v, v, u );
  11742. };
  11743. }();
  11744. Triangle.containsPoint = function () {
  11745. var v1 = new Vector3();
  11746. return function containsPoint( point, a, b, c ) {
  11747. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  11748. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  11749. };
  11750. }();
  11751. Triangle.prototype = {
  11752. constructor: Triangle,
  11753. set: function ( a, b, c ) {
  11754. this.a.copy( a );
  11755. this.b.copy( b );
  11756. this.c.copy( c );
  11757. return this;
  11758. },
  11759. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  11760. this.a.copy( points[ i0 ] );
  11761. this.b.copy( points[ i1 ] );
  11762. this.c.copy( points[ i2 ] );
  11763. return this;
  11764. },
  11765. clone: function () {
  11766. return new this.constructor().copy( this );
  11767. },
  11768. copy: function ( triangle ) {
  11769. this.a.copy( triangle.a );
  11770. this.b.copy( triangle.b );
  11771. this.c.copy( triangle.c );
  11772. return this;
  11773. },
  11774. area: function () {
  11775. var v0 = new Vector3();
  11776. var v1 = new Vector3();
  11777. return function area() {
  11778. v0.subVectors( this.c, this.b );
  11779. v1.subVectors( this.a, this.b );
  11780. return v0.cross( v1 ).length() * 0.5;
  11781. };
  11782. }(),
  11783. midpoint: function ( optionalTarget ) {
  11784. var result = optionalTarget || new Vector3();
  11785. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11786. },
  11787. normal: function ( optionalTarget ) {
  11788. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  11789. },
  11790. plane: function ( optionalTarget ) {
  11791. var result = optionalTarget || new Plane();
  11792. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  11793. },
  11794. barycoordFromPoint: function ( point, optionalTarget ) {
  11795. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  11796. },
  11797. containsPoint: function ( point ) {
  11798. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11799. },
  11800. closestPointToPoint: function () {
  11801. var plane, edgeList, projectedPoint, closestPoint;
  11802. return function closestPointToPoint( point, optionalTarget ) {
  11803. if ( plane === undefined ) {
  11804. plane = new Plane();
  11805. edgeList = [ new Line3(), new Line3(), new Line3() ];
  11806. projectedPoint = new Vector3();
  11807. closestPoint = new Vector3();
  11808. }
  11809. var result = optionalTarget || new Vector3();
  11810. var minDistance = Infinity;
  11811. // project the point onto the plane of the triangle
  11812. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  11813. plane.projectPoint( point, projectedPoint );
  11814. // check if the projection lies within the triangle
  11815. if( this.containsPoint( projectedPoint ) === true ) {
  11816. // if so, this is the closest point
  11817. result.copy( projectedPoint );
  11818. } else {
  11819. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  11820. edgeList[ 0 ].set( this.a, this.b );
  11821. edgeList[ 1 ].set( this.b, this.c );
  11822. edgeList[ 2 ].set( this.c, this.a );
  11823. for( var i = 0; i < edgeList.length; i ++ ) {
  11824. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  11825. var distance = projectedPoint.distanceToSquared( closestPoint );
  11826. if( distance < minDistance ) {
  11827. minDistance = distance;
  11828. result.copy( closestPoint );
  11829. }
  11830. }
  11831. }
  11832. return result;
  11833. };
  11834. }(),
  11835. equals: function ( triangle ) {
  11836. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11837. }
  11838. };
  11839. /**
  11840. * @author mrdoob / http://mrdoob.com/
  11841. * @author alteredq / http://alteredqualia.com/
  11842. *
  11843. * parameters = {
  11844. * color: <hex>,
  11845. * opacity: <float>,
  11846. * map: new THREE.Texture( <Image> ),
  11847. *
  11848. * lightMap: new THREE.Texture( <Image> ),
  11849. * lightMapIntensity: <float>
  11850. *
  11851. * aoMap: new THREE.Texture( <Image> ),
  11852. * aoMapIntensity: <float>
  11853. *
  11854. * specularMap: new THREE.Texture( <Image> ),
  11855. *
  11856. * alphaMap: new THREE.Texture( <Image> ),
  11857. *
  11858. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11859. * combine: THREE.Multiply,
  11860. * reflectivity: <float>,
  11861. * refractionRatio: <float>,
  11862. *
  11863. * shading: THREE.SmoothShading,
  11864. * depthTest: <bool>,
  11865. * depthWrite: <bool>,
  11866. *
  11867. * wireframe: <boolean>,
  11868. * wireframeLinewidth: <float>,
  11869. *
  11870. * skinning: <bool>,
  11871. * morphTargets: <bool>
  11872. * }
  11873. */
  11874. function MeshBasicMaterial( parameters ) {
  11875. Material.call( this );
  11876. this.type = 'MeshBasicMaterial';
  11877. this.color = new Color( 0xffffff ); // emissive
  11878. this.map = null;
  11879. this.lightMap = null;
  11880. this.lightMapIntensity = 1.0;
  11881. this.aoMap = null;
  11882. this.aoMapIntensity = 1.0;
  11883. this.specularMap = null;
  11884. this.alphaMap = null;
  11885. this.envMap = null;
  11886. this.combine = MultiplyOperation;
  11887. this.reflectivity = 1;
  11888. this.refractionRatio = 0.98;
  11889. this.wireframe = false;
  11890. this.wireframeLinewidth = 1;
  11891. this.wireframeLinecap = 'round';
  11892. this.wireframeLinejoin = 'round';
  11893. this.skinning = false;
  11894. this.morphTargets = false;
  11895. this.lights = false;
  11896. this.setValues( parameters );
  11897. }
  11898. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  11899. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  11900. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  11901. MeshBasicMaterial.prototype.copy = function ( source ) {
  11902. Material.prototype.copy.call( this, source );
  11903. this.color.copy( source.color );
  11904. this.map = source.map;
  11905. this.lightMap = source.lightMap;
  11906. this.lightMapIntensity = source.lightMapIntensity;
  11907. this.aoMap = source.aoMap;
  11908. this.aoMapIntensity = source.aoMapIntensity;
  11909. this.specularMap = source.specularMap;
  11910. this.alphaMap = source.alphaMap;
  11911. this.envMap = source.envMap;
  11912. this.combine = source.combine;
  11913. this.reflectivity = source.reflectivity;
  11914. this.refractionRatio = source.refractionRatio;
  11915. this.wireframe = source.wireframe;
  11916. this.wireframeLinewidth = source.wireframeLinewidth;
  11917. this.wireframeLinecap = source.wireframeLinecap;
  11918. this.wireframeLinejoin = source.wireframeLinejoin;
  11919. this.skinning = source.skinning;
  11920. this.morphTargets = source.morphTargets;
  11921. return this;
  11922. };
  11923. /**
  11924. * @author mrdoob / http://mrdoob.com/
  11925. * @author alteredq / http://alteredqualia.com/
  11926. * @author mikael emtinger / http://gomo.se/
  11927. * @author jonobr1 / http://jonobr1.com/
  11928. */
  11929. function Mesh( geometry, material ) {
  11930. Object3D.call( this );
  11931. this.type = 'Mesh';
  11932. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  11933. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  11934. this.drawMode = TrianglesDrawMode;
  11935. this.updateMorphTargets();
  11936. }
  11937. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  11938. constructor: Mesh,
  11939. isMesh: true,
  11940. setDrawMode: function ( value ) {
  11941. this.drawMode = value;
  11942. },
  11943. copy: function ( source ) {
  11944. Object3D.prototype.copy.call( this, source );
  11945. this.drawMode = source.drawMode;
  11946. return this;
  11947. },
  11948. updateMorphTargets: function () {
  11949. var morphTargets = this.geometry.morphTargets;
  11950. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  11951. this.morphTargetInfluences = [];
  11952. this.morphTargetDictionary = {};
  11953. for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  11954. this.morphTargetInfluences.push( 0 );
  11955. this.morphTargetDictionary[ morphTargets[ m ].name ] = m;
  11956. }
  11957. }
  11958. },
  11959. raycast: ( function () {
  11960. var inverseMatrix = new Matrix4();
  11961. var ray = new Ray();
  11962. var sphere = new Sphere();
  11963. var vA = new Vector3();
  11964. var vB = new Vector3();
  11965. var vC = new Vector3();
  11966. var tempA = new Vector3();
  11967. var tempB = new Vector3();
  11968. var tempC = new Vector3();
  11969. var uvA = new Vector2();
  11970. var uvB = new Vector2();
  11971. var uvC = new Vector2();
  11972. var barycoord = new Vector3();
  11973. var intersectionPoint = new Vector3();
  11974. var intersectionPointWorld = new Vector3();
  11975. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  11976. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  11977. uv1.multiplyScalar( barycoord.x );
  11978. uv2.multiplyScalar( barycoord.y );
  11979. uv3.multiplyScalar( barycoord.z );
  11980. uv1.add( uv2 ).add( uv3 );
  11981. return uv1.clone();
  11982. }
  11983. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  11984. var intersect;
  11985. var material = object.material;
  11986. if ( material.side === BackSide ) {
  11987. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  11988. } else {
  11989. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  11990. }
  11991. if ( intersect === null ) return null;
  11992. intersectionPointWorld.copy( point );
  11993. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  11994. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  11995. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  11996. return {
  11997. distance: distance,
  11998. point: intersectionPointWorld.clone(),
  11999. object: object
  12000. };
  12001. }
  12002. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  12003. vA.fromBufferAttribute( position, a );
  12004. vB.fromBufferAttribute( position, b );
  12005. vC.fromBufferAttribute( position, c );
  12006. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  12007. if ( intersection ) {
  12008. if ( uv ) {
  12009. uvA.fromBufferAttribute( uv, a );
  12010. uvB.fromBufferAttribute( uv, b );
  12011. uvC.fromBufferAttribute( uv, c );
  12012. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  12013. }
  12014. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  12015. intersection.faceIndex = a;
  12016. }
  12017. return intersection;
  12018. }
  12019. return function raycast( raycaster, intersects ) {
  12020. var geometry = this.geometry;
  12021. var material = this.material;
  12022. var matrixWorld = this.matrixWorld;
  12023. if ( material === undefined ) return;
  12024. // Checking boundingSphere distance to ray
  12025. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12026. sphere.copy( geometry.boundingSphere );
  12027. sphere.applyMatrix4( matrixWorld );
  12028. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  12029. //
  12030. inverseMatrix.getInverse( matrixWorld );
  12031. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  12032. // Check boundingBox before continuing
  12033. if ( geometry.boundingBox !== null ) {
  12034. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  12035. }
  12036. var intersection;
  12037. if ( geometry.isBufferGeometry ) {
  12038. var a, b, c;
  12039. var index = geometry.index;
  12040. var position = geometry.attributes.position;
  12041. var uv = geometry.attributes.uv;
  12042. var i, l;
  12043. if ( index !== null ) {
  12044. // indexed buffer geometry
  12045. for ( i = 0, l = index.count; i < l; i += 3 ) {
  12046. a = index.getX( i );
  12047. b = index.getX( i + 1 );
  12048. c = index.getX( i + 2 );
  12049. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  12050. if ( intersection ) {
  12051. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  12052. intersects.push( intersection );
  12053. }
  12054. }
  12055. } else {
  12056. // non-indexed buffer geometry
  12057. for ( i = 0, l = position.count; i < l; i += 3 ) {
  12058. a = i;
  12059. b = i + 1;
  12060. c = i + 2;
  12061. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  12062. if ( intersection ) {
  12063. intersection.index = a; // triangle number in positions buffer semantics
  12064. intersects.push( intersection );
  12065. }
  12066. }
  12067. }
  12068. } else if ( geometry.isGeometry ) {
  12069. var fvA, fvB, fvC;
  12070. var isFaceMaterial = ( material && material.isMultiMaterial );
  12071. var materials = isFaceMaterial === true ? material.materials : null;
  12072. var vertices = geometry.vertices;
  12073. var faces = geometry.faces;
  12074. var uvs;
  12075. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  12076. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  12077. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  12078. var face = faces[ f ];
  12079. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  12080. if ( faceMaterial === undefined ) continue;
  12081. fvA = vertices[ face.a ];
  12082. fvB = vertices[ face.b ];
  12083. fvC = vertices[ face.c ];
  12084. if ( faceMaterial.morphTargets === true ) {
  12085. var morphTargets = geometry.morphTargets;
  12086. var morphInfluences = this.morphTargetInfluences;
  12087. vA.set( 0, 0, 0 );
  12088. vB.set( 0, 0, 0 );
  12089. vC.set( 0, 0, 0 );
  12090. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  12091. var influence = morphInfluences[ t ];
  12092. if ( influence === 0 ) continue;
  12093. var targets = morphTargets[ t ].vertices;
  12094. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  12095. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  12096. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  12097. }
  12098. vA.add( fvA );
  12099. vB.add( fvB );
  12100. vC.add( fvC );
  12101. fvA = vA;
  12102. fvB = vB;
  12103. fvC = vC;
  12104. }
  12105. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  12106. if ( intersection ) {
  12107. if ( uvs ) {
  12108. var uvs_f = uvs[ f ];
  12109. uvA.copy( uvs_f[ 0 ] );
  12110. uvB.copy( uvs_f[ 1 ] );
  12111. uvC.copy( uvs_f[ 2 ] );
  12112. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  12113. }
  12114. intersection.face = face;
  12115. intersection.faceIndex = f;
  12116. intersects.push( intersection );
  12117. }
  12118. }
  12119. }
  12120. };
  12121. }() ),
  12122. clone: function () {
  12123. return new this.constructor( this.geometry, this.material ).copy( this );
  12124. }
  12125. } );
  12126. /**
  12127. * @author mrdoob / http://mrdoob.com/
  12128. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  12129. */
  12130. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  12131. Geometry.call( this );
  12132. this.type = 'PlaneGeometry';
  12133. this.parameters = {
  12134. width: width,
  12135. height: height,
  12136. widthSegments: widthSegments,
  12137. heightSegments: heightSegments
  12138. };
  12139. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  12140. }
  12141. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  12142. PlaneGeometry.prototype.constructor = PlaneGeometry;
  12143. /**
  12144. * @author mrdoob / http://mrdoob.com/
  12145. * @author Mugen87 / https://github.com/Mugen87
  12146. *
  12147. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  12148. */
  12149. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  12150. BufferGeometry.call( this );
  12151. this.type = 'PlaneBufferGeometry';
  12152. this.parameters = {
  12153. width: width,
  12154. height: height,
  12155. widthSegments: widthSegments,
  12156. heightSegments: heightSegments
  12157. };
  12158. var width_half = width / 2;
  12159. var height_half = height / 2;
  12160. var gridX = Math.floor( widthSegments ) || 1;
  12161. var gridY = Math.floor( heightSegments ) || 1;
  12162. var gridX1 = gridX + 1;
  12163. var gridY1 = gridY + 1;
  12164. var segment_width = width / gridX;
  12165. var segment_height = height / gridY;
  12166. var ix, iy;
  12167. // buffers
  12168. var indices = [];
  12169. var vertices = [];
  12170. var normals = [];
  12171. var uvs = [];
  12172. // generate vertices, normals and uvs
  12173. for ( iy = 0; iy < gridY1; iy ++ ) {
  12174. var y = iy * segment_height - height_half;
  12175. for ( ix = 0; ix < gridX1; ix ++ ) {
  12176. var x = ix * segment_width - width_half;
  12177. vertices.push( x, - y, 0 );
  12178. normals.push( 0, 0, 1 );
  12179. uvs.push( ix / gridX );
  12180. uvs.push( 1 - ( iy / gridY ) );
  12181. }
  12182. }
  12183. // indices
  12184. for ( iy = 0; iy < gridY; iy ++ ) {
  12185. for ( ix = 0; ix < gridX; ix ++ ) {
  12186. var a = ix + gridX1 * iy;
  12187. var b = ix + gridX1 * ( iy + 1 );
  12188. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  12189. var d = ( ix + 1 ) + gridX1 * iy;
  12190. // faces
  12191. indices.push( a, b, d );
  12192. indices.push( b, c, d );
  12193. }
  12194. }
  12195. // build geometry
  12196. this.setIndex( indices );
  12197. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12198. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  12199. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  12200. }
  12201. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  12202. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  12203. /**
  12204. * @author alteredq / http://alteredqualia.com/
  12205. * @author arose / http://github.com/arose
  12206. */
  12207. function OrthographicCamera( left, right, top, bottom, near, far ) {
  12208. Camera.call( this );
  12209. this.type = 'OrthographicCamera';
  12210. this.zoom = 1;
  12211. this.view = null;
  12212. this.left = left;
  12213. this.right = right;
  12214. this.top = top;
  12215. this.bottom = bottom;
  12216. this.near = ( near !== undefined ) ? near : 0.1;
  12217. this.far = ( far !== undefined ) ? far : 2000;
  12218. this.updateProjectionMatrix();
  12219. }
  12220. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  12221. constructor: OrthographicCamera,
  12222. isOrthographicCamera: true,
  12223. copy: function ( source ) {
  12224. Camera.prototype.copy.call( this, source );
  12225. this.left = source.left;
  12226. this.right = source.right;
  12227. this.top = source.top;
  12228. this.bottom = source.bottom;
  12229. this.near = source.near;
  12230. this.far = source.far;
  12231. this.zoom = source.zoom;
  12232. this.view = source.view === null ? null : Object.assign( {}, source.view );
  12233. return this;
  12234. },
  12235. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  12236. this.view = {
  12237. fullWidth: fullWidth,
  12238. fullHeight: fullHeight,
  12239. offsetX: x,
  12240. offsetY: y,
  12241. width: width,
  12242. height: height
  12243. };
  12244. this.updateProjectionMatrix();
  12245. },
  12246. clearViewOffset: function() {
  12247. this.view = null;
  12248. this.updateProjectionMatrix();
  12249. },
  12250. updateProjectionMatrix: function () {
  12251. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  12252. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  12253. var cx = ( this.right + this.left ) / 2;
  12254. var cy = ( this.top + this.bottom ) / 2;
  12255. var left = cx - dx;
  12256. var right = cx + dx;
  12257. var top = cy + dy;
  12258. var bottom = cy - dy;
  12259. if ( this.view !== null ) {
  12260. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  12261. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  12262. var scaleW = ( this.right - this.left ) / this.view.width;
  12263. var scaleH = ( this.top - this.bottom ) / this.view.height;
  12264. left += scaleW * ( this.view.offsetX / zoomW );
  12265. right = left + scaleW * ( this.view.width / zoomW );
  12266. top -= scaleH * ( this.view.offsetY / zoomH );
  12267. bottom = top - scaleH * ( this.view.height / zoomH );
  12268. }
  12269. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  12270. },
  12271. toJSON: function ( meta ) {
  12272. var data = Object3D.prototype.toJSON.call( this, meta );
  12273. data.object.zoom = this.zoom;
  12274. data.object.left = this.left;
  12275. data.object.right = this.right;
  12276. data.object.top = this.top;
  12277. data.object.bottom = this.bottom;
  12278. data.object.near = this.near;
  12279. data.object.far = this.far;
  12280. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  12281. return data;
  12282. }
  12283. } );
  12284. /**
  12285. * @author mrdoob / http://mrdoob.com/
  12286. */
  12287. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  12288. var mode;
  12289. function setMode( value ) {
  12290. mode = value;
  12291. }
  12292. var type, size;
  12293. function setIndex( index ) {
  12294. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  12295. type = gl.UNSIGNED_INT;
  12296. size = 4;
  12297. } else if ( index.array instanceof Uint16Array ) {
  12298. type = gl.UNSIGNED_SHORT;
  12299. size = 2;
  12300. } else {
  12301. type = gl.UNSIGNED_BYTE;
  12302. size = 1;
  12303. }
  12304. }
  12305. function render( start, count ) {
  12306. gl.drawElements( mode, count, type, start * size );
  12307. infoRender.calls ++;
  12308. infoRender.vertices += count;
  12309. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  12310. }
  12311. function renderInstances( geometry, start, count ) {
  12312. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  12313. if ( extension === null ) {
  12314. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12315. return;
  12316. }
  12317. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  12318. infoRender.calls ++;
  12319. infoRender.vertices += count * geometry.maxInstancedCount;
  12320. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  12321. }
  12322. return {
  12323. setMode: setMode,
  12324. setIndex: setIndex,
  12325. render: render,
  12326. renderInstances: renderInstances
  12327. };
  12328. }
  12329. /**
  12330. * @author mrdoob / http://mrdoob.com/
  12331. */
  12332. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  12333. var mode;
  12334. function setMode( value ) {
  12335. mode = value;
  12336. }
  12337. function render( start, count ) {
  12338. gl.drawArrays( mode, start, count );
  12339. infoRender.calls ++;
  12340. infoRender.vertices += count;
  12341. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  12342. }
  12343. function renderInstances( geometry ) {
  12344. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  12345. if ( extension === null ) {
  12346. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12347. return;
  12348. }
  12349. var position = geometry.attributes.position;
  12350. var count = 0;
  12351. if ( position.isInterleavedBufferAttribute ) {
  12352. count = position.data.count;
  12353. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  12354. } else {
  12355. count = position.count;
  12356. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  12357. }
  12358. infoRender.calls ++;
  12359. infoRender.vertices += count * geometry.maxInstancedCount;
  12360. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  12361. }
  12362. return {
  12363. setMode: setMode,
  12364. render: render,
  12365. renderInstances: renderInstances
  12366. };
  12367. }
  12368. /**
  12369. * @author mrdoob / http://mrdoob.com/
  12370. */
  12371. function WebGLLights() {
  12372. var lights = {};
  12373. return {
  12374. get: function ( light ) {
  12375. if ( lights[ light.id ] !== undefined ) {
  12376. return lights[ light.id ];
  12377. }
  12378. var uniforms;
  12379. switch ( light.type ) {
  12380. case 'DirectionalLight':
  12381. uniforms = {
  12382. direction: new Vector3(),
  12383. color: new Color(),
  12384. shadow: false,
  12385. shadowBias: 0,
  12386. shadowRadius: 1,
  12387. shadowMapSize: new Vector2()
  12388. };
  12389. break;
  12390. case 'SpotLight':
  12391. uniforms = {
  12392. position: new Vector3(),
  12393. direction: new Vector3(),
  12394. color: new Color(),
  12395. distance: 0,
  12396. coneCos: 0,
  12397. penumbraCos: 0,
  12398. decay: 0,
  12399. shadow: false,
  12400. shadowBias: 0,
  12401. shadowRadius: 1,
  12402. shadowMapSize: new Vector2()
  12403. };
  12404. break;
  12405. case 'PointLight':
  12406. uniforms = {
  12407. position: new Vector3(),
  12408. color: new Color(),
  12409. distance: 0,
  12410. decay: 0,
  12411. shadow: false,
  12412. shadowBias: 0,
  12413. shadowRadius: 1,
  12414. shadowMapSize: new Vector2()
  12415. };
  12416. break;
  12417. case 'HemisphereLight':
  12418. uniforms = {
  12419. direction: new Vector3(),
  12420. skyColor: new Color(),
  12421. groundColor: new Color()
  12422. };
  12423. break;
  12424. case 'RectAreaLight':
  12425. uniforms = {
  12426. color: new Color(),
  12427. position: new Vector3(),
  12428. halfWidth: new Vector3(),
  12429. halfHeight: new Vector3()
  12430. // TODO (abelnation): set RectAreaLight shadow uniforms
  12431. };
  12432. break;
  12433. }
  12434. lights[ light.id ] = uniforms;
  12435. return uniforms;
  12436. }
  12437. };
  12438. }
  12439. /**
  12440. * @author mrdoob / http://mrdoob.com/
  12441. */
  12442. function addLineNumbers( string ) {
  12443. var lines = string.split( '\n' );
  12444. for ( var i = 0; i < lines.length; i ++ ) {
  12445. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  12446. }
  12447. return lines.join( '\n' );
  12448. }
  12449. function WebGLShader( gl, type, string ) {
  12450. var shader = gl.createShader( type );
  12451. gl.shaderSource( shader, string );
  12452. gl.compileShader( shader );
  12453. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  12454. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  12455. }
  12456. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  12457. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  12458. }
  12459. // --enable-privileged-webgl-extension
  12460. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  12461. return shader;
  12462. }
  12463. /**
  12464. * @author mrdoob / http://mrdoob.com/
  12465. */
  12466. var programIdCount = 0;
  12467. function getEncodingComponents( encoding ) {
  12468. switch ( encoding ) {
  12469. case LinearEncoding:
  12470. return [ 'Linear','( value )' ];
  12471. case sRGBEncoding:
  12472. return [ 'sRGB','( value )' ];
  12473. case RGBEEncoding:
  12474. return [ 'RGBE','( value )' ];
  12475. case RGBM7Encoding:
  12476. return [ 'RGBM','( value, 7.0 )' ];
  12477. case RGBM16Encoding:
  12478. return [ 'RGBM','( value, 16.0 )' ];
  12479. case RGBDEncoding:
  12480. return [ 'RGBD','( value, 256.0 )' ];
  12481. case GammaEncoding:
  12482. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  12483. default:
  12484. throw new Error( 'unsupported encoding: ' + encoding );
  12485. }
  12486. }
  12487. function getTexelDecodingFunction( functionName, encoding ) {
  12488. var components = getEncodingComponents( encoding );
  12489. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  12490. }
  12491. function getTexelEncodingFunction( functionName, encoding ) {
  12492. var components = getEncodingComponents( encoding );
  12493. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  12494. }
  12495. function getToneMappingFunction( functionName, toneMapping ) {
  12496. var toneMappingName;
  12497. switch ( toneMapping ) {
  12498. case LinearToneMapping:
  12499. toneMappingName = "Linear";
  12500. break;
  12501. case ReinhardToneMapping:
  12502. toneMappingName = "Reinhard";
  12503. break;
  12504. case Uncharted2ToneMapping:
  12505. toneMappingName = "Uncharted2";
  12506. break;
  12507. case CineonToneMapping:
  12508. toneMappingName = "OptimizedCineon";
  12509. break;
  12510. default:
  12511. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  12512. }
  12513. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  12514. }
  12515. function generateExtensions( extensions, parameters, rendererExtensions ) {
  12516. extensions = extensions || {};
  12517. var chunks = [
  12518. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  12519. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  12520. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  12521. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  12522. ];
  12523. return chunks.filter( filterEmptyLine ).join( '\n' );
  12524. }
  12525. function generateDefines( defines ) {
  12526. var chunks = [];
  12527. for ( var name in defines ) {
  12528. var value = defines[ name ];
  12529. if ( value === false ) continue;
  12530. chunks.push( '#define ' + name + ' ' + value );
  12531. }
  12532. return chunks.join( '\n' );
  12533. }
  12534. function fetchAttributeLocations( gl, program, identifiers ) {
  12535. var attributes = {};
  12536. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  12537. for ( var i = 0; i < n; i ++ ) {
  12538. var info = gl.getActiveAttrib( program, i );
  12539. var name = info.name;
  12540. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  12541. attributes[ name ] = gl.getAttribLocation( program, name );
  12542. }
  12543. return attributes;
  12544. }
  12545. function filterEmptyLine( string ) {
  12546. return string !== '';
  12547. }
  12548. function replaceLightNums( string, parameters ) {
  12549. return string
  12550. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  12551. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  12552. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  12553. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  12554. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  12555. }
  12556. function parseIncludes( string ) {
  12557. var pattern = /#include +<([\w\d.]+)>/g;
  12558. function replace( match, include ) {
  12559. var replace = ShaderChunk[ include ];
  12560. if ( replace === undefined ) {
  12561. throw new Error( 'Can not resolve #include <' + include + '>' );
  12562. }
  12563. return parseIncludes( replace );
  12564. }
  12565. return string.replace( pattern, replace );
  12566. }
  12567. function unrollLoops( string ) {
  12568. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  12569. function replace( match, start, end, snippet ) {
  12570. var unroll = '';
  12571. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  12572. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  12573. }
  12574. return unroll;
  12575. }
  12576. return string.replace( pattern, replace );
  12577. }
  12578. function WebGLProgram( renderer, code, material, parameters ) {
  12579. var gl = renderer.context;
  12580. var extensions = material.extensions;
  12581. var defines = material.defines;
  12582. var vertexShader = material.__webglShader.vertexShader;
  12583. var fragmentShader = material.__webglShader.fragmentShader;
  12584. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  12585. if ( parameters.shadowMapType === PCFShadowMap ) {
  12586. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  12587. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  12588. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  12589. }
  12590. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12591. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  12592. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12593. if ( parameters.envMap ) {
  12594. switch ( material.envMap.mapping ) {
  12595. case CubeReflectionMapping:
  12596. case CubeRefractionMapping:
  12597. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  12598. break;
  12599. case CubeUVReflectionMapping:
  12600. case CubeUVRefractionMapping:
  12601. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  12602. break;
  12603. case EquirectangularReflectionMapping:
  12604. case EquirectangularRefractionMapping:
  12605. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  12606. break;
  12607. case SphericalReflectionMapping:
  12608. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  12609. break;
  12610. }
  12611. switch ( material.envMap.mapping ) {
  12612. case CubeRefractionMapping:
  12613. case EquirectangularRefractionMapping:
  12614. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  12615. break;
  12616. }
  12617. switch ( material.combine ) {
  12618. case MultiplyOperation:
  12619. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  12620. break;
  12621. case MixOperation:
  12622. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  12623. break;
  12624. case AddOperation:
  12625. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  12626. break;
  12627. }
  12628. }
  12629. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  12630. // console.log( 'building new program ' );
  12631. //
  12632. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  12633. var customDefines = generateDefines( defines );
  12634. //
  12635. var program = gl.createProgram();
  12636. var prefixVertex, prefixFragment;
  12637. if ( material.isRawShaderMaterial ) {
  12638. prefixVertex = [
  12639. customDefines,
  12640. '\n'
  12641. ].filter( filterEmptyLine ).join( '\n' );
  12642. prefixFragment = [
  12643. customExtensions,
  12644. customDefines,
  12645. '\n'
  12646. ].filter( filterEmptyLine ).join( '\n' );
  12647. } else {
  12648. prefixVertex = [
  12649. 'precision ' + parameters.precision + ' float;',
  12650. 'precision ' + parameters.precision + ' int;',
  12651. '#define SHADER_NAME ' + material.__webglShader.name,
  12652. customDefines,
  12653. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  12654. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  12655. '#define MAX_BONES ' + parameters.maxBones,
  12656. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  12657. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  12658. parameters.map ? '#define USE_MAP' : '',
  12659. parameters.envMap ? '#define USE_ENVMAP' : '',
  12660. parameters.envMap ? '#define ' + envMapModeDefine : '',
  12661. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  12662. parameters.aoMap ? '#define USE_AOMAP' : '',
  12663. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  12664. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  12665. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  12666. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  12667. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  12668. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  12669. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  12670. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  12671. parameters.vertexColors ? '#define USE_COLOR' : '',
  12672. parameters.flatShading ? '#define FLAT_SHADED' : '',
  12673. parameters.skinning ? '#define USE_SKINNING' : '',
  12674. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  12675. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  12676. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  12677. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  12678. parameters.flipSided ? '#define FLIP_SIDED' : '',
  12679. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  12680. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  12681. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  12682. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  12683. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  12684. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  12685. 'uniform mat4 modelMatrix;',
  12686. 'uniform mat4 modelViewMatrix;',
  12687. 'uniform mat4 projectionMatrix;',
  12688. 'uniform mat4 viewMatrix;',
  12689. 'uniform mat3 normalMatrix;',
  12690. 'uniform vec3 cameraPosition;',
  12691. 'attribute vec3 position;',
  12692. 'attribute vec3 normal;',
  12693. 'attribute vec2 uv;',
  12694. '#ifdef USE_COLOR',
  12695. ' attribute vec3 color;',
  12696. '#endif',
  12697. '#ifdef USE_MORPHTARGETS',
  12698. ' attribute vec3 morphTarget0;',
  12699. ' attribute vec3 morphTarget1;',
  12700. ' attribute vec3 morphTarget2;',
  12701. ' attribute vec3 morphTarget3;',
  12702. ' #ifdef USE_MORPHNORMALS',
  12703. ' attribute vec3 morphNormal0;',
  12704. ' attribute vec3 morphNormal1;',
  12705. ' attribute vec3 morphNormal2;',
  12706. ' attribute vec3 morphNormal3;',
  12707. ' #else',
  12708. ' attribute vec3 morphTarget4;',
  12709. ' attribute vec3 morphTarget5;',
  12710. ' attribute vec3 morphTarget6;',
  12711. ' attribute vec3 morphTarget7;',
  12712. ' #endif',
  12713. '#endif',
  12714. '#ifdef USE_SKINNING',
  12715. ' attribute vec4 skinIndex;',
  12716. ' attribute vec4 skinWeight;',
  12717. '#endif',
  12718. '\n'
  12719. ].filter( filterEmptyLine ).join( '\n' );
  12720. prefixFragment = [
  12721. customExtensions,
  12722. 'precision ' + parameters.precision + ' float;',
  12723. 'precision ' + parameters.precision + ' int;',
  12724. '#define SHADER_NAME ' + material.__webglShader.name,
  12725. customDefines,
  12726. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  12727. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  12728. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  12729. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  12730. parameters.map ? '#define USE_MAP' : '',
  12731. parameters.envMap ? '#define USE_ENVMAP' : '',
  12732. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  12733. parameters.envMap ? '#define ' + envMapModeDefine : '',
  12734. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  12735. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  12736. parameters.aoMap ? '#define USE_AOMAP' : '',
  12737. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  12738. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  12739. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  12740. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  12741. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  12742. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  12743. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  12744. parameters.vertexColors ? '#define USE_COLOR' : '',
  12745. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  12746. parameters.flatShading ? '#define FLAT_SHADED' : '',
  12747. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  12748. parameters.flipSided ? '#define FLIP_SIDED' : '',
  12749. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  12750. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  12751. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  12752. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  12753. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  12754. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  12755. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  12756. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  12757. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  12758. 'uniform mat4 viewMatrix;',
  12759. 'uniform vec3 cameraPosition;',
  12760. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  12761. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  12762. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  12763. ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  12764. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  12765. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  12766. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  12767. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  12768. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  12769. '\n'
  12770. ].filter( filterEmptyLine ).join( '\n' );
  12771. }
  12772. vertexShader = parseIncludes( vertexShader, parameters );
  12773. vertexShader = replaceLightNums( vertexShader, parameters );
  12774. fragmentShader = parseIncludes( fragmentShader, parameters );
  12775. fragmentShader = replaceLightNums( fragmentShader, parameters );
  12776. if ( ! material.isShaderMaterial ) {
  12777. vertexShader = unrollLoops( vertexShader );
  12778. fragmentShader = unrollLoops( fragmentShader );
  12779. }
  12780. var vertexGlsl = prefixVertex + vertexShader;
  12781. var fragmentGlsl = prefixFragment + fragmentShader;
  12782. // console.log( '*VERTEX*', vertexGlsl );
  12783. // console.log( '*FRAGMENT*', fragmentGlsl );
  12784. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  12785. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  12786. gl.attachShader( program, glVertexShader );
  12787. gl.attachShader( program, glFragmentShader );
  12788. // Force a particular attribute to index 0.
  12789. if ( material.index0AttributeName !== undefined ) {
  12790. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  12791. } else if ( parameters.morphTargets === true ) {
  12792. // programs with morphTargets displace position out of attribute 0
  12793. gl.bindAttribLocation( program, 0, 'position' );
  12794. }
  12795. gl.linkProgram( program );
  12796. var programLog = gl.getProgramInfoLog( program );
  12797. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  12798. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  12799. var runnable = true;
  12800. var haveDiagnostics = true;
  12801. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  12802. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  12803. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  12804. runnable = false;
  12805. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  12806. } else if ( programLog !== '' ) {
  12807. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  12808. } else if ( vertexLog === '' || fragmentLog === '' ) {
  12809. haveDiagnostics = false;
  12810. }
  12811. if ( haveDiagnostics ) {
  12812. this.diagnostics = {
  12813. runnable: runnable,
  12814. material: material,
  12815. programLog: programLog,
  12816. vertexShader: {
  12817. log: vertexLog,
  12818. prefix: prefixVertex
  12819. },
  12820. fragmentShader: {
  12821. log: fragmentLog,
  12822. prefix: prefixFragment
  12823. }
  12824. };
  12825. }
  12826. // clean up
  12827. gl.deleteShader( glVertexShader );
  12828. gl.deleteShader( glFragmentShader );
  12829. // set up caching for uniform locations
  12830. var cachedUniforms;
  12831. this.getUniforms = function() {
  12832. if ( cachedUniforms === undefined ) {
  12833. cachedUniforms =
  12834. new WebGLUniforms( gl, program, renderer );
  12835. }
  12836. return cachedUniforms;
  12837. };
  12838. // set up caching for attribute locations
  12839. var cachedAttributes;
  12840. this.getAttributes = function() {
  12841. if ( cachedAttributes === undefined ) {
  12842. cachedAttributes = fetchAttributeLocations( gl, program );
  12843. }
  12844. return cachedAttributes;
  12845. };
  12846. // free resource
  12847. this.destroy = function() {
  12848. gl.deleteProgram( program );
  12849. this.program = undefined;
  12850. };
  12851. // DEPRECATED
  12852. Object.defineProperties( this, {
  12853. uniforms: {
  12854. get: function() {
  12855. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  12856. return this.getUniforms();
  12857. }
  12858. },
  12859. attributes: {
  12860. get: function() {
  12861. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  12862. return this.getAttributes();
  12863. }
  12864. }
  12865. } );
  12866. //
  12867. this.id = programIdCount ++;
  12868. this.code = code;
  12869. this.usedTimes = 1;
  12870. this.program = program;
  12871. this.vertexShader = glVertexShader;
  12872. this.fragmentShader = glFragmentShader;
  12873. return this;
  12874. }
  12875. /**
  12876. * @author mrdoob / http://mrdoob.com/
  12877. */
  12878. function WebGLPrograms( renderer, capabilities ) {
  12879. var programs = [];
  12880. var shaderIDs = {
  12881. MeshDepthMaterial: 'depth',
  12882. MeshNormalMaterial: 'normal',
  12883. MeshBasicMaterial: 'basic',
  12884. MeshLambertMaterial: 'lambert',
  12885. MeshPhongMaterial: 'phong',
  12886. MeshToonMaterial: 'phong',
  12887. MeshStandardMaterial: 'physical',
  12888. MeshPhysicalMaterial: 'physical',
  12889. LineBasicMaterial: 'basic',
  12890. LineDashedMaterial: 'dashed',
  12891. PointsMaterial: 'points'
  12892. };
  12893. var parameterNames = [
  12894. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  12895. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  12896. "roughnessMap", "metalnessMap", "gradientMap",
  12897. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  12898. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  12899. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  12900. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  12901. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  12902. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  12903. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking"
  12904. ];
  12905. function allocateBones( object ) {
  12906. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  12907. return 1024;
  12908. } else {
  12909. // default for when object is not specified
  12910. // ( for example when prebuilding shader to be used with multiple objects )
  12911. //
  12912. // - leave some extra space for other uniforms
  12913. // - limit here is ANGLE's 254 max uniform vectors
  12914. // (up to 54 should be safe)
  12915. var nVertexUniforms = capabilities.maxVertexUniforms;
  12916. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  12917. var maxBones = nVertexMatrices;
  12918. if ( object !== undefined && (object && object.isSkinnedMesh) ) {
  12919. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  12920. if ( maxBones < object.skeleton.bones.length ) {
  12921. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  12922. }
  12923. }
  12924. return maxBones;
  12925. }
  12926. }
  12927. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  12928. var encoding;
  12929. if ( ! map ) {
  12930. encoding = LinearEncoding;
  12931. } else if ( map.isTexture ) {
  12932. encoding = map.encoding;
  12933. } else if ( map.isWebGLRenderTarget ) {
  12934. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  12935. encoding = map.texture.encoding;
  12936. }
  12937. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  12938. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  12939. encoding = GammaEncoding;
  12940. }
  12941. return encoding;
  12942. }
  12943. this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) {
  12944. var shaderID = shaderIDs[ material.type ];
  12945. // heuristics to create shader parameters according to lights in the scene
  12946. // (not to blow over maxLights budget)
  12947. var maxBones = allocateBones( object );
  12948. var precision = renderer.getPrecision();
  12949. if ( material.precision !== null ) {
  12950. precision = capabilities.getMaxPrecision( material.precision );
  12951. if ( precision !== material.precision ) {
  12952. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12953. }
  12954. }
  12955. var currentRenderTarget = renderer.getCurrentRenderTarget();
  12956. var parameters = {
  12957. shaderID: shaderID,
  12958. precision: precision,
  12959. supportsVertexTextures: capabilities.vertexTextures,
  12960. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  12961. map: !! material.map,
  12962. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  12963. envMap: !! material.envMap,
  12964. envMapMode: material.envMap && material.envMap.mapping,
  12965. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  12966. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  12967. lightMap: !! material.lightMap,
  12968. aoMap: !! material.aoMap,
  12969. emissiveMap: !! material.emissiveMap,
  12970. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  12971. bumpMap: !! material.bumpMap,
  12972. normalMap: !! material.normalMap,
  12973. displacementMap: !! material.displacementMap,
  12974. roughnessMap: !! material.roughnessMap,
  12975. metalnessMap: !! material.metalnessMap,
  12976. specularMap: !! material.specularMap,
  12977. alphaMap: !! material.alphaMap,
  12978. gradientMap: !! material.gradientMap,
  12979. combine: material.combine,
  12980. vertexColors: material.vertexColors,
  12981. fog: !! fog,
  12982. useFog: material.fog,
  12983. fogExp: (fog && fog.isFogExp2),
  12984. flatShading: material.shading === FlatShading,
  12985. sizeAttenuation: material.sizeAttenuation,
  12986. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  12987. skinning: material.skinning,
  12988. maxBones: maxBones,
  12989. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  12990. morphTargets: material.morphTargets,
  12991. morphNormals: material.morphNormals,
  12992. maxMorphTargets: renderer.maxMorphTargets,
  12993. maxMorphNormals: renderer.maxMorphNormals,
  12994. numDirLights: lights.directional.length,
  12995. numPointLights: lights.point.length,
  12996. numSpotLights: lights.spot.length,
  12997. numRectAreaLights: lights.rectArea.length,
  12998. numHemiLights: lights.hemi.length,
  12999. numClippingPlanes: nClipPlanes,
  13000. numClipIntersection: nClipIntersection,
  13001. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  13002. shadowMapType: renderer.shadowMap.type,
  13003. toneMapping: renderer.toneMapping,
  13004. physicallyCorrectLights: renderer.physicallyCorrectLights,
  13005. premultipliedAlpha: material.premultipliedAlpha,
  13006. alphaTest: material.alphaTest,
  13007. doubleSided: material.side === DoubleSide,
  13008. flipSided: material.side === BackSide,
  13009. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  13010. };
  13011. return parameters;
  13012. };
  13013. this.getProgramCode = function ( material, parameters ) {
  13014. var array = [];
  13015. if ( parameters.shaderID ) {
  13016. array.push( parameters.shaderID );
  13017. } else {
  13018. array.push( material.fragmentShader );
  13019. array.push( material.vertexShader );
  13020. }
  13021. if ( material.defines !== undefined ) {
  13022. for ( var name in material.defines ) {
  13023. array.push( name );
  13024. array.push( material.defines[ name ] );
  13025. }
  13026. }
  13027. for ( var i = 0; i < parameterNames.length; i ++ ) {
  13028. array.push( parameters[ parameterNames[ i ] ] );
  13029. }
  13030. return array.join();
  13031. };
  13032. this.acquireProgram = function ( material, parameters, code ) {
  13033. var program;
  13034. // Check if code has been already compiled
  13035. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  13036. var programInfo = programs[ p ];
  13037. if ( programInfo.code === code ) {
  13038. program = programInfo;
  13039. ++ program.usedTimes;
  13040. break;
  13041. }
  13042. }
  13043. if ( program === undefined ) {
  13044. program = new WebGLProgram( renderer, code, material, parameters );
  13045. programs.push( program );
  13046. }
  13047. return program;
  13048. };
  13049. this.releaseProgram = function( program ) {
  13050. if ( -- program.usedTimes === 0 ) {
  13051. // Remove from unordered set
  13052. var i = programs.indexOf( program );
  13053. programs[ i ] = programs[ programs.length - 1 ];
  13054. programs.pop();
  13055. // Free WebGL resources
  13056. program.destroy();
  13057. }
  13058. };
  13059. // Exposed for resource monitoring & error feedback via renderer.info:
  13060. this.programs = programs;
  13061. }
  13062. /**
  13063. * @author mrdoob / http://mrdoob.com/
  13064. */
  13065. function WebGLGeometries( gl, properties, info ) {
  13066. var geometries = {};
  13067. function onGeometryDispose( event ) {
  13068. var geometry = event.target;
  13069. var buffergeometry = geometries[ geometry.id ];
  13070. if ( buffergeometry.index !== null ) {
  13071. deleteAttribute( buffergeometry.index );
  13072. }
  13073. deleteAttributes( buffergeometry.attributes );
  13074. geometry.removeEventListener( 'dispose', onGeometryDispose );
  13075. delete geometries[ geometry.id ];
  13076. // TODO
  13077. var property = properties.get( geometry );
  13078. if ( property.wireframe ) {
  13079. deleteAttribute( property.wireframe );
  13080. }
  13081. properties.delete( geometry );
  13082. var bufferproperty = properties.get( buffergeometry );
  13083. if ( bufferproperty.wireframe ) {
  13084. deleteAttribute( bufferproperty.wireframe );
  13085. }
  13086. properties.delete( buffergeometry );
  13087. //
  13088. info.memory.geometries --;
  13089. }
  13090. function getAttributeBuffer( attribute ) {
  13091. if ( attribute.isInterleavedBufferAttribute ) {
  13092. return properties.get( attribute.data ).__webglBuffer;
  13093. }
  13094. return properties.get( attribute ).__webglBuffer;
  13095. }
  13096. function deleteAttribute( attribute ) {
  13097. var buffer = getAttributeBuffer( attribute );
  13098. if ( buffer !== undefined ) {
  13099. gl.deleteBuffer( buffer );
  13100. removeAttributeBuffer( attribute );
  13101. }
  13102. }
  13103. function deleteAttributes( attributes ) {
  13104. for ( var name in attributes ) {
  13105. deleteAttribute( attributes[ name ] );
  13106. }
  13107. }
  13108. function removeAttributeBuffer( attribute ) {
  13109. if ( attribute.isInterleavedBufferAttribute ) {
  13110. properties.delete( attribute.data );
  13111. } else {
  13112. properties.delete( attribute );
  13113. }
  13114. }
  13115. return {
  13116. get: function ( object ) {
  13117. var geometry = object.geometry;
  13118. if ( geometries[ geometry.id ] !== undefined ) {
  13119. return geometries[ geometry.id ];
  13120. }
  13121. geometry.addEventListener( 'dispose', onGeometryDispose );
  13122. var buffergeometry;
  13123. if ( geometry.isBufferGeometry ) {
  13124. buffergeometry = geometry;
  13125. } else if ( geometry.isGeometry ) {
  13126. if ( geometry._bufferGeometry === undefined ) {
  13127. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  13128. }
  13129. buffergeometry = geometry._bufferGeometry;
  13130. }
  13131. geometries[ geometry.id ] = buffergeometry;
  13132. info.memory.geometries ++;
  13133. return buffergeometry;
  13134. }
  13135. };
  13136. }
  13137. /**
  13138. * @author mrdoob / http://mrdoob.com/
  13139. */
  13140. function WebGLObjects( gl, properties, info ) {
  13141. var geometries = new WebGLGeometries( gl, properties, info );
  13142. //
  13143. function update( object ) {
  13144. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  13145. var geometry = geometries.get( object );
  13146. if ( object.geometry.isGeometry ) {
  13147. geometry.updateFromObject( object );
  13148. }
  13149. var index = geometry.index;
  13150. var attributes = geometry.attributes;
  13151. if ( index !== null ) {
  13152. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  13153. }
  13154. for ( var name in attributes ) {
  13155. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  13156. }
  13157. // morph targets
  13158. var morphAttributes = geometry.morphAttributes;
  13159. for ( var name in morphAttributes ) {
  13160. var array = morphAttributes[ name ];
  13161. for ( var i = 0, l = array.length; i < l; i ++ ) {
  13162. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  13163. }
  13164. }
  13165. return geometry;
  13166. }
  13167. function updateAttribute( attribute, bufferType ) {
  13168. var data = ( attribute.isInterleavedBufferAttribute ) ? attribute.data : attribute;
  13169. var attributeProperties = properties.get( data );
  13170. if ( attributeProperties.__webglBuffer === undefined ) {
  13171. createBuffer( attributeProperties, data, bufferType );
  13172. } else if ( attributeProperties.version !== data.version ) {
  13173. updateBuffer( attributeProperties, data, bufferType );
  13174. }
  13175. }
  13176. function createBuffer( attributeProperties, data, bufferType ) {
  13177. attributeProperties.__webglBuffer = gl.createBuffer();
  13178. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  13179. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  13180. gl.bufferData( bufferType, data.array, usage );
  13181. var type = gl.FLOAT;
  13182. var array = data.array;
  13183. if ( array instanceof Float32Array ) {
  13184. type = gl.FLOAT;
  13185. } else if ( array instanceof Float64Array ) {
  13186. console.warn( "Unsupported data buffer format: Float64Array" );
  13187. } else if ( array instanceof Uint16Array ) {
  13188. type = gl.UNSIGNED_SHORT;
  13189. } else if ( array instanceof Int16Array ) {
  13190. type = gl.SHORT;
  13191. } else if ( array instanceof Uint32Array ) {
  13192. type = gl.UNSIGNED_INT;
  13193. } else if ( array instanceof Int32Array ) {
  13194. type = gl.INT;
  13195. } else if ( array instanceof Int8Array ) {
  13196. type = gl.BYTE;
  13197. } else if ( array instanceof Uint8Array ) {
  13198. type = gl.UNSIGNED_BYTE;
  13199. }
  13200. attributeProperties.bytesPerElement = array.BYTES_PER_ELEMENT;
  13201. attributeProperties.type = type;
  13202. attributeProperties.version = data.version;
  13203. data.onUploadCallback();
  13204. }
  13205. function updateBuffer( attributeProperties, data, bufferType ) {
  13206. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  13207. if ( data.dynamic === false ) {
  13208. gl.bufferData( bufferType, data.array, gl.STATIC_DRAW );
  13209. } else if ( data.updateRange.count === - 1 ) {
  13210. // Not using update ranges
  13211. gl.bufferSubData( bufferType, 0, data.array );
  13212. } else if ( data.updateRange.count === 0 ) {
  13213. console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' );
  13214. } else {
  13215. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  13216. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  13217. data.updateRange.count = 0; // reset range
  13218. }
  13219. attributeProperties.version = data.version;
  13220. }
  13221. function getAttributeBuffer( attribute ) {
  13222. if ( attribute.isInterleavedBufferAttribute ) {
  13223. return properties.get( attribute.data ).__webglBuffer;
  13224. }
  13225. return properties.get( attribute ).__webglBuffer;
  13226. }
  13227. function getAttributeProperties( attribute ) {
  13228. if ( attribute.isInterleavedBufferAttribute ) {
  13229. return properties.get( attribute.data );
  13230. }
  13231. return properties.get( attribute );
  13232. }
  13233. function getWireframeAttribute( geometry ) {
  13234. var property = properties.get( geometry );
  13235. if ( property.wireframe !== undefined ) {
  13236. return property.wireframe;
  13237. }
  13238. var indices = [];
  13239. var index = geometry.index;
  13240. var attributes = geometry.attributes;
  13241. // console.time( 'wireframe' );
  13242. if ( index !== null ) {
  13243. var array = index.array;
  13244. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  13245. var a = array[ i + 0 ];
  13246. var b = array[ i + 1 ];
  13247. var c = array[ i + 2 ];
  13248. indices.push( a, b, b, c, c, a );
  13249. }
  13250. } else {
  13251. var array = attributes.position.array;
  13252. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  13253. var a = i + 0;
  13254. var b = i + 1;
  13255. var c = i + 2;
  13256. indices.push( a, b, b, c, c, a );
  13257. }
  13258. }
  13259. // console.timeEnd( 'wireframe' );
  13260. var attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  13261. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  13262. property.wireframe = attribute;
  13263. return attribute;
  13264. }
  13265. return {
  13266. getAttributeBuffer: getAttributeBuffer,
  13267. getAttributeProperties: getAttributeProperties,
  13268. getWireframeAttribute: getWireframeAttribute,
  13269. update: update
  13270. };
  13271. }
  13272. /**
  13273. * @author mrdoob / http://mrdoob.com/
  13274. */
  13275. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) {
  13276. var _infoMemory = info.memory;
  13277. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  13278. //
  13279. function clampToMaxSize( image, maxSize ) {
  13280. if ( image.width > maxSize || image.height > maxSize ) {
  13281. // Warning: Scaling through the canvas will only work with images that use
  13282. // premultiplied alpha.
  13283. var scale = maxSize / Math.max( image.width, image.height );
  13284. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  13285. canvas.width = Math.floor( image.width * scale );
  13286. canvas.height = Math.floor( image.height * scale );
  13287. var context = canvas.getContext( '2d' );
  13288. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  13289. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  13290. return canvas;
  13291. }
  13292. return image;
  13293. }
  13294. function isPowerOfTwo( image ) {
  13295. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  13296. }
  13297. function makePowerOfTwo( image ) {
  13298. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  13299. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  13300. canvas.width = _Math.nearestPowerOfTwo( image.width );
  13301. canvas.height = _Math.nearestPowerOfTwo( image.height );
  13302. var context = canvas.getContext( '2d' );
  13303. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  13304. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  13305. return canvas;
  13306. }
  13307. return image;
  13308. }
  13309. function textureNeedsPowerOfTwo( texture ) {
  13310. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13311. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13312. }
  13313. // Fallback filters for non-power-of-2 textures
  13314. function filterFallback( f ) {
  13315. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  13316. return _gl.NEAREST;
  13317. }
  13318. return _gl.LINEAR;
  13319. }
  13320. //
  13321. function onTextureDispose( event ) {
  13322. var texture = event.target;
  13323. texture.removeEventListener( 'dispose', onTextureDispose );
  13324. deallocateTexture( texture );
  13325. _infoMemory.textures --;
  13326. }
  13327. function onRenderTargetDispose( event ) {
  13328. var renderTarget = event.target;
  13329. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13330. deallocateRenderTarget( renderTarget );
  13331. _infoMemory.textures --;
  13332. }
  13333. //
  13334. function deallocateTexture( texture ) {
  13335. var textureProperties = properties.get( texture );
  13336. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  13337. // cube texture
  13338. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  13339. } else {
  13340. // 2D texture
  13341. if ( textureProperties.__webglInit === undefined ) return;
  13342. _gl.deleteTexture( textureProperties.__webglTexture );
  13343. }
  13344. // remove all webgl properties
  13345. properties.delete( texture );
  13346. }
  13347. function deallocateRenderTarget( renderTarget ) {
  13348. var renderTargetProperties = properties.get( renderTarget );
  13349. var textureProperties = properties.get( renderTarget.texture );
  13350. if ( ! renderTarget ) return;
  13351. if ( textureProperties.__webglTexture !== undefined ) {
  13352. _gl.deleteTexture( textureProperties.__webglTexture );
  13353. }
  13354. if ( renderTarget.depthTexture ) {
  13355. renderTarget.depthTexture.dispose();
  13356. }
  13357. if ( renderTarget.isWebGLRenderTargetCube ) {
  13358. for ( var i = 0; i < 6; i ++ ) {
  13359. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13360. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13361. }
  13362. } else {
  13363. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13364. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13365. }
  13366. properties.delete( renderTarget.texture );
  13367. properties.delete( renderTarget );
  13368. }
  13369. //
  13370. function setTexture2D( texture, slot ) {
  13371. var textureProperties = properties.get( texture );
  13372. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13373. var image = texture.image;
  13374. if ( image === undefined ) {
  13375. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  13376. } else if ( image.complete === false ) {
  13377. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  13378. } else {
  13379. uploadTexture( textureProperties, texture, slot );
  13380. return;
  13381. }
  13382. }
  13383. state.activeTexture( _gl.TEXTURE0 + slot );
  13384. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  13385. }
  13386. function setTextureCube( texture, slot ) {
  13387. var textureProperties = properties.get( texture );
  13388. if ( texture.image.length === 6 ) {
  13389. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13390. if ( ! textureProperties.__image__webglTextureCube ) {
  13391. texture.addEventListener( 'dispose', onTextureDispose );
  13392. textureProperties.__image__webglTextureCube = _gl.createTexture();
  13393. _infoMemory.textures ++;
  13394. }
  13395. state.activeTexture( _gl.TEXTURE0 + slot );
  13396. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  13397. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13398. var isCompressed = ( texture && texture.isCompressedTexture );
  13399. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  13400. var cubeImage = [];
  13401. for ( var i = 0; i < 6; i ++ ) {
  13402. if ( ! isCompressed && ! isDataTexture ) {
  13403. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  13404. } else {
  13405. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13406. }
  13407. }
  13408. var image = cubeImage[ 0 ],
  13409. isPowerOfTwoImage = isPowerOfTwo( image ),
  13410. glFormat = paramThreeToGL( texture.format ),
  13411. glType = paramThreeToGL( texture.type );
  13412. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  13413. for ( var i = 0; i < 6; i ++ ) {
  13414. if ( ! isCompressed ) {
  13415. if ( isDataTexture ) {
  13416. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13417. } else {
  13418. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13419. }
  13420. } else {
  13421. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13422. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13423. mipmap = mipmaps[ j ];
  13424. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13425. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  13426. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13427. } else {
  13428. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  13429. }
  13430. } else {
  13431. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13432. }
  13433. }
  13434. }
  13435. }
  13436. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  13437. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13438. }
  13439. textureProperties.__version = texture.version;
  13440. if ( texture.onUpdate ) texture.onUpdate( texture );
  13441. } else {
  13442. state.activeTexture( _gl.TEXTURE0 + slot );
  13443. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  13444. }
  13445. }
  13446. }
  13447. function setTextureCubeDynamic( texture, slot ) {
  13448. state.activeTexture( _gl.TEXTURE0 + slot );
  13449. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  13450. }
  13451. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  13452. var extension;
  13453. if ( isPowerOfTwoImage ) {
  13454. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13455. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13456. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13457. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13458. } else {
  13459. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13460. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13461. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13462. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  13463. }
  13464. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13465. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13466. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13467. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  13468. }
  13469. }
  13470. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13471. if ( extension ) {
  13472. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  13473. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  13474. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13475. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13476. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13477. }
  13478. }
  13479. }
  13480. function uploadTexture( textureProperties, texture, slot ) {
  13481. if ( textureProperties.__webglInit === undefined ) {
  13482. textureProperties.__webglInit = true;
  13483. texture.addEventListener( 'dispose', onTextureDispose );
  13484. textureProperties.__webglTexture = _gl.createTexture();
  13485. _infoMemory.textures ++;
  13486. }
  13487. state.activeTexture( _gl.TEXTURE0 + slot );
  13488. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  13489. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13490. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13491. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13492. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  13493. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  13494. image = makePowerOfTwo( image );
  13495. }
  13496. var isPowerOfTwoImage = isPowerOfTwo( image ),
  13497. glFormat = paramThreeToGL( texture.format ),
  13498. glType = paramThreeToGL( texture.type );
  13499. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  13500. var mipmap, mipmaps = texture.mipmaps;
  13501. if ( texture.isDepthTexture ) {
  13502. // populate depth texture with dummy data
  13503. var internalFormat = _gl.DEPTH_COMPONENT;
  13504. if ( texture.type === FloatType ) {
  13505. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  13506. internalFormat = _gl.DEPTH_COMPONENT32F;
  13507. } else if ( _isWebGL2 ) {
  13508. // WebGL 2.0 requires signed internalformat for glTexImage2D
  13509. internalFormat = _gl.DEPTH_COMPONENT16;
  13510. }
  13511. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  13512. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13513. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13514. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13515. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13516. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13517. texture.type = UnsignedShortType;
  13518. glType = paramThreeToGL( texture.type );
  13519. }
  13520. }
  13521. // Depth stencil textures need the DEPTH_STENCIL internal format
  13522. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13523. if ( texture.format === DepthStencilFormat ) {
  13524. internalFormat = _gl.DEPTH_STENCIL;
  13525. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13526. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13527. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13528. if ( texture.type !== UnsignedInt248Type ) {
  13529. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13530. texture.type = UnsignedInt248Type;
  13531. glType = paramThreeToGL( texture.type );
  13532. }
  13533. }
  13534. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  13535. } else if ( texture.isDataTexture ) {
  13536. // use manually created mipmaps if available
  13537. // if there are no manual mipmaps
  13538. // set 0 level mipmap and then use GL to generate other mipmap levels
  13539. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  13540. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13541. mipmap = mipmaps[ i ];
  13542. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13543. }
  13544. texture.generateMipmaps = false;
  13545. } else {
  13546. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13547. }
  13548. } else if ( texture.isCompressedTexture ) {
  13549. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13550. mipmap = mipmaps[ i ];
  13551. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13552. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  13553. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13554. } else {
  13555. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  13556. }
  13557. } else {
  13558. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13559. }
  13560. }
  13561. } else {
  13562. // regular Texture (image, video, canvas)
  13563. // use manually created mipmaps if available
  13564. // if there are no manual mipmaps
  13565. // set 0 level mipmap and then use GL to generate other mipmap levels
  13566. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  13567. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13568. mipmap = mipmaps[ i ];
  13569. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  13570. }
  13571. texture.generateMipmaps = false;
  13572. } else {
  13573. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  13574. }
  13575. }
  13576. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13577. textureProperties.__version = texture.version;
  13578. if ( texture.onUpdate ) texture.onUpdate( texture );
  13579. }
  13580. // Render targets
  13581. // Setup storage for target texture and bind it to correct framebuffer
  13582. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  13583. var glFormat = paramThreeToGL( renderTarget.texture.format );
  13584. var glType = paramThreeToGL( renderTarget.texture.type );
  13585. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13586. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13587. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  13588. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  13589. }
  13590. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13591. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  13592. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13593. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13594. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13595. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13596. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13597. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13598. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13599. } else {
  13600. // FIXME: We don't support !depth !stencil
  13601. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13602. }
  13603. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13604. }
  13605. // Setup resources for a Depth Texture for a FBO (needs an extension)
  13606. function setupDepthTexture( framebuffer, renderTarget ) {
  13607. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  13608. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  13609. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13610. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  13611. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13612. }
  13613. // upload an empty depth texture with framebuffer size
  13614. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  13615. renderTarget.depthTexture.image.width !== renderTarget.width ||
  13616. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  13617. renderTarget.depthTexture.image.width = renderTarget.width;
  13618. renderTarget.depthTexture.image.height = renderTarget.height;
  13619. renderTarget.depthTexture.needsUpdate = true;
  13620. }
  13621. setTexture2D( renderTarget.depthTexture, 0 );
  13622. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  13623. if ( renderTarget.depthTexture.format === DepthFormat ) {
  13624. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  13625. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  13626. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  13627. } else {
  13628. throw new Error('Unknown depthTexture format')
  13629. }
  13630. }
  13631. // Setup GL resources for a non-texture depth buffer
  13632. function setupDepthRenderbuffer( renderTarget ) {
  13633. var renderTargetProperties = properties.get( renderTarget );
  13634. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  13635. if ( renderTarget.depthTexture ) {
  13636. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  13637. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  13638. } else {
  13639. if ( isCube ) {
  13640. renderTargetProperties.__webglDepthbuffer = [];
  13641. for ( var i = 0; i < 6; i ++ ) {
  13642. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  13643. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  13644. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  13645. }
  13646. } else {
  13647. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  13648. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13649. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  13650. }
  13651. }
  13652. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  13653. }
  13654. // Set up GL resources for the render target
  13655. function setupRenderTarget( renderTarget ) {
  13656. var renderTargetProperties = properties.get( renderTarget );
  13657. var textureProperties = properties.get( renderTarget.texture );
  13658. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13659. textureProperties.__webglTexture = _gl.createTexture();
  13660. _infoMemory.textures ++;
  13661. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  13662. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  13663. // Setup framebuffer
  13664. if ( isCube ) {
  13665. renderTargetProperties.__webglFramebuffer = [];
  13666. for ( var i = 0; i < 6; i ++ ) {
  13667. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13668. }
  13669. } else {
  13670. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13671. }
  13672. // Setup color buffer
  13673. if ( isCube ) {
  13674. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  13675. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  13676. for ( var i = 0; i < 6; i ++ ) {
  13677. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13678. }
  13679. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13680. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13681. } else {
  13682. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  13683. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  13684. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  13685. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13686. state.bindTexture( _gl.TEXTURE_2D, null );
  13687. }
  13688. // Setup depth and stencil buffers
  13689. if ( renderTarget.depthBuffer ) {
  13690. setupDepthRenderbuffer( renderTarget );
  13691. }
  13692. }
  13693. function updateRenderTargetMipmap( renderTarget ) {
  13694. var texture = renderTarget.texture;
  13695. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  13696. texture.minFilter !== NearestFilter &&
  13697. texture.minFilter !== LinearFilter ) {
  13698. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  13699. var webglTexture = properties.get( texture ).__webglTexture;
  13700. state.bindTexture( target, webglTexture );
  13701. _gl.generateMipmap( target );
  13702. state.bindTexture( target, null );
  13703. }
  13704. }
  13705. this.setTexture2D = setTexture2D;
  13706. this.setTextureCube = setTextureCube;
  13707. this.setTextureCubeDynamic = setTextureCubeDynamic;
  13708. this.setupRenderTarget = setupRenderTarget;
  13709. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13710. }
  13711. /**
  13712. * @author fordacious / fordacious.github.io
  13713. */
  13714. function WebGLProperties() {
  13715. var properties = {};
  13716. return {
  13717. get: function ( object ) {
  13718. var uuid = object.uuid;
  13719. var map = properties[ uuid ];
  13720. if ( map === undefined ) {
  13721. map = {};
  13722. properties[ uuid ] = map;
  13723. }
  13724. return map;
  13725. },
  13726. delete: function ( object ) {
  13727. delete properties[ object.uuid ];
  13728. },
  13729. clear: function () {
  13730. properties = {};
  13731. }
  13732. };
  13733. }
  13734. /**
  13735. * @author mrdoob / http://mrdoob.com/
  13736. */
  13737. function WebGLState( gl, extensions, paramThreeToGL ) {
  13738. function ColorBuffer() {
  13739. var locked = false;
  13740. var color = new Vector4();
  13741. var currentColorMask = null;
  13742. var currentColorClear = new Vector4();
  13743. return {
  13744. setMask: function ( colorMask ) {
  13745. if ( currentColorMask !== colorMask && ! locked ) {
  13746. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13747. currentColorMask = colorMask;
  13748. }
  13749. },
  13750. setLocked: function ( lock ) {
  13751. locked = lock;
  13752. },
  13753. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13754. if ( premultipliedAlpha === true ) {
  13755. r *= a; g *= a; b *= a;
  13756. }
  13757. color.set( r, g, b, a );
  13758. if ( currentColorClear.equals( color ) === false ) {
  13759. gl.clearColor( r, g, b, a );
  13760. currentColorClear.copy( color );
  13761. }
  13762. },
  13763. reset: function () {
  13764. locked = false;
  13765. currentColorMask = null;
  13766. currentColorClear.set( 0, 0, 0, 1 );
  13767. }
  13768. };
  13769. }
  13770. function DepthBuffer() {
  13771. var locked = false;
  13772. var currentDepthMask = null;
  13773. var currentDepthFunc = null;
  13774. var currentDepthClear = null;
  13775. return {
  13776. setTest: function ( depthTest ) {
  13777. if ( depthTest ) {
  13778. enable( gl.DEPTH_TEST );
  13779. } else {
  13780. disable( gl.DEPTH_TEST );
  13781. }
  13782. },
  13783. setMask: function ( depthMask ) {
  13784. if ( currentDepthMask !== depthMask && ! locked ) {
  13785. gl.depthMask( depthMask );
  13786. currentDepthMask = depthMask;
  13787. }
  13788. },
  13789. setFunc: function ( depthFunc ) {
  13790. if ( currentDepthFunc !== depthFunc ) {
  13791. if ( depthFunc ) {
  13792. switch ( depthFunc ) {
  13793. case NeverDepth:
  13794. gl.depthFunc( gl.NEVER );
  13795. break;
  13796. case AlwaysDepth:
  13797. gl.depthFunc( gl.ALWAYS );
  13798. break;
  13799. case LessDepth:
  13800. gl.depthFunc( gl.LESS );
  13801. break;
  13802. case LessEqualDepth:
  13803. gl.depthFunc( gl.LEQUAL );
  13804. break;
  13805. case EqualDepth:
  13806. gl.depthFunc( gl.EQUAL );
  13807. break;
  13808. case GreaterEqualDepth:
  13809. gl.depthFunc( gl.GEQUAL );
  13810. break;
  13811. case GreaterDepth:
  13812. gl.depthFunc( gl.GREATER );
  13813. break;
  13814. case NotEqualDepth:
  13815. gl.depthFunc( gl.NOTEQUAL );
  13816. break;
  13817. default:
  13818. gl.depthFunc( gl.LEQUAL );
  13819. }
  13820. } else {
  13821. gl.depthFunc( gl.LEQUAL );
  13822. }
  13823. currentDepthFunc = depthFunc;
  13824. }
  13825. },
  13826. setLocked: function ( lock ) {
  13827. locked = lock;
  13828. },
  13829. setClear: function ( depth ) {
  13830. if ( currentDepthClear !== depth ) {
  13831. gl.clearDepth( depth );
  13832. currentDepthClear = depth;
  13833. }
  13834. },
  13835. reset: function () {
  13836. locked = false;
  13837. currentDepthMask = null;
  13838. currentDepthFunc = null;
  13839. currentDepthClear = null;
  13840. }
  13841. };
  13842. }
  13843. function StencilBuffer() {
  13844. var locked = false;
  13845. var currentStencilMask = null;
  13846. var currentStencilFunc = null;
  13847. var currentStencilRef = null;
  13848. var currentStencilFuncMask = null;
  13849. var currentStencilFail = null;
  13850. var currentStencilZFail = null;
  13851. var currentStencilZPass = null;
  13852. var currentStencilClear = null;
  13853. return {
  13854. setTest: function ( stencilTest ) {
  13855. if ( stencilTest ) {
  13856. enable( gl.STENCIL_TEST );
  13857. } else {
  13858. disable( gl.STENCIL_TEST );
  13859. }
  13860. },
  13861. setMask: function ( stencilMask ) {
  13862. if ( currentStencilMask !== stencilMask && ! locked ) {
  13863. gl.stencilMask( stencilMask );
  13864. currentStencilMask = stencilMask;
  13865. }
  13866. },
  13867. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13868. if ( currentStencilFunc !== stencilFunc ||
  13869. currentStencilRef !== stencilRef ||
  13870. currentStencilFuncMask !== stencilMask ) {
  13871. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13872. currentStencilFunc = stencilFunc;
  13873. currentStencilRef = stencilRef;
  13874. currentStencilFuncMask = stencilMask;
  13875. }
  13876. },
  13877. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13878. if ( currentStencilFail !== stencilFail ||
  13879. currentStencilZFail !== stencilZFail ||
  13880. currentStencilZPass !== stencilZPass ) {
  13881. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13882. currentStencilFail = stencilFail;
  13883. currentStencilZFail = stencilZFail;
  13884. currentStencilZPass = stencilZPass;
  13885. }
  13886. },
  13887. setLocked: function ( lock ) {
  13888. locked = lock;
  13889. },
  13890. setClear: function ( stencil ) {
  13891. if ( currentStencilClear !== stencil ) {
  13892. gl.clearStencil( stencil );
  13893. currentStencilClear = stencil;
  13894. }
  13895. },
  13896. reset: function () {
  13897. locked = false;
  13898. currentStencilMask = null;
  13899. currentStencilFunc = null;
  13900. currentStencilRef = null;
  13901. currentStencilFuncMask = null;
  13902. currentStencilFail = null;
  13903. currentStencilZFail = null;
  13904. currentStencilZPass = null;
  13905. currentStencilClear = null;
  13906. }
  13907. };
  13908. }
  13909. //
  13910. var colorBuffer = new ColorBuffer();
  13911. var depthBuffer = new DepthBuffer();
  13912. var stencilBuffer = new StencilBuffer();
  13913. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  13914. var newAttributes = new Uint8Array( maxVertexAttributes );
  13915. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  13916. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  13917. var capabilities = {};
  13918. var compressedTextureFormats = null;
  13919. var currentBlending = null;
  13920. var currentBlendEquation = null;
  13921. var currentBlendSrc = null;
  13922. var currentBlendDst = null;
  13923. var currentBlendEquationAlpha = null;
  13924. var currentBlendSrcAlpha = null;
  13925. var currentBlendDstAlpha = null;
  13926. var currentPremultipledAlpha = false;
  13927. var currentFlipSided = null;
  13928. var currentCullFace = null;
  13929. var currentLineWidth = null;
  13930. var currentPolygonOffsetFactor = null;
  13931. var currentPolygonOffsetUnits = null;
  13932. var currentScissorTest = null;
  13933. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  13934. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  13935. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  13936. var currentTextureSlot = null;
  13937. var currentBoundTextures = {};
  13938. var currentScissor = new Vector4();
  13939. var currentViewport = new Vector4();
  13940. function createTexture( type, target, count ) {
  13941. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13942. var texture = gl.createTexture();
  13943. gl.bindTexture( type, texture );
  13944. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13945. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13946. for ( var i = 0; i < count; i ++ ) {
  13947. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13948. }
  13949. return texture;
  13950. }
  13951. var emptyTextures = {};
  13952. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13953. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13954. //
  13955. function init() {
  13956. colorBuffer.setClear( 0, 0, 0, 1 );
  13957. depthBuffer.setClear( 1 );
  13958. stencilBuffer.setClear( 0 );
  13959. enable( gl.DEPTH_TEST );
  13960. setDepthFunc( LessEqualDepth );
  13961. setFlipSided( false );
  13962. setCullFace( CullFaceBack );
  13963. enable( gl.CULL_FACE );
  13964. enable( gl.BLEND );
  13965. setBlending( NormalBlending );
  13966. }
  13967. function initAttributes() {
  13968. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  13969. newAttributes[ i ] = 0;
  13970. }
  13971. }
  13972. function enableAttribute( attribute ) {
  13973. newAttributes[ attribute ] = 1;
  13974. if ( enabledAttributes[ attribute ] === 0 ) {
  13975. gl.enableVertexAttribArray( attribute );
  13976. enabledAttributes[ attribute ] = 1;
  13977. }
  13978. if ( attributeDivisors[ attribute ] !== 0 ) {
  13979. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  13980. extension.vertexAttribDivisorANGLE( attribute, 0 );
  13981. attributeDivisors[ attribute ] = 0;
  13982. }
  13983. }
  13984. function enableAttributeAndDivisor( attribute, meshPerAttribute, extension ) {
  13985. newAttributes[ attribute ] = 1;
  13986. if ( enabledAttributes[ attribute ] === 0 ) {
  13987. gl.enableVertexAttribArray( attribute );
  13988. enabledAttributes[ attribute ] = 1;
  13989. }
  13990. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  13991. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  13992. attributeDivisors[ attribute ] = meshPerAttribute;
  13993. }
  13994. }
  13995. function disableUnusedAttributes() {
  13996. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  13997. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  13998. gl.disableVertexAttribArray( i );
  13999. enabledAttributes[ i ] = 0;
  14000. }
  14001. }
  14002. }
  14003. function enable( id ) {
  14004. if ( capabilities[ id ] !== true ) {
  14005. gl.enable( id );
  14006. capabilities[ id ] = true;
  14007. }
  14008. }
  14009. function disable( id ) {
  14010. if ( capabilities[ id ] !== false ) {
  14011. gl.disable( id );
  14012. capabilities[ id ] = false;
  14013. }
  14014. }
  14015. function getCompressedTextureFormats() {
  14016. if ( compressedTextureFormats === null ) {
  14017. compressedTextureFormats = [];
  14018. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  14019. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  14020. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  14021. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  14022. for ( var i = 0; i < formats.length; i ++ ) {
  14023. compressedTextureFormats.push( formats[ i ] );
  14024. }
  14025. }
  14026. }
  14027. return compressedTextureFormats;
  14028. }
  14029. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  14030. if ( blending !== NoBlending ) {
  14031. enable( gl.BLEND );
  14032. } else {
  14033. disable( gl.BLEND );
  14034. }
  14035. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  14036. if ( blending === AdditiveBlending ) {
  14037. if ( premultipliedAlpha ) {
  14038. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  14039. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  14040. } else {
  14041. gl.blendEquation( gl.FUNC_ADD );
  14042. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  14043. }
  14044. } else if ( blending === SubtractiveBlending ) {
  14045. if ( premultipliedAlpha ) {
  14046. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  14047. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  14048. } else {
  14049. gl.blendEquation( gl.FUNC_ADD );
  14050. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  14051. }
  14052. } else if ( blending === MultiplyBlending ) {
  14053. if ( premultipliedAlpha ) {
  14054. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  14055. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  14056. } else {
  14057. gl.blendEquation( gl.FUNC_ADD );
  14058. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  14059. }
  14060. } else {
  14061. if ( premultipliedAlpha ) {
  14062. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  14063. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14064. } else {
  14065. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  14066. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14067. }
  14068. }
  14069. currentBlending = blending;
  14070. currentPremultipledAlpha = premultipliedAlpha;
  14071. }
  14072. if ( blending === CustomBlending ) {
  14073. blendEquationAlpha = blendEquationAlpha || blendEquation;
  14074. blendSrcAlpha = blendSrcAlpha || blendSrc;
  14075. blendDstAlpha = blendDstAlpha || blendDst;
  14076. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  14077. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  14078. currentBlendEquation = blendEquation;
  14079. currentBlendEquationAlpha = blendEquationAlpha;
  14080. }
  14081. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  14082. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  14083. currentBlendSrc = blendSrc;
  14084. currentBlendDst = blendDst;
  14085. currentBlendSrcAlpha = blendSrcAlpha;
  14086. currentBlendDstAlpha = blendDstAlpha;
  14087. }
  14088. } else {
  14089. currentBlendEquation = null;
  14090. currentBlendSrc = null;
  14091. currentBlendDst = null;
  14092. currentBlendEquationAlpha = null;
  14093. currentBlendSrcAlpha = null;
  14094. currentBlendDstAlpha = null;
  14095. }
  14096. }
  14097. // TODO Deprecate
  14098. function setColorWrite( colorWrite ) {
  14099. colorBuffer.setMask( colorWrite );
  14100. }
  14101. function setDepthTest( depthTest ) {
  14102. depthBuffer.setTest( depthTest );
  14103. }
  14104. function setDepthWrite( depthWrite ) {
  14105. depthBuffer.setMask( depthWrite );
  14106. }
  14107. function setDepthFunc( depthFunc ) {
  14108. depthBuffer.setFunc( depthFunc );
  14109. }
  14110. function setStencilTest( stencilTest ) {
  14111. stencilBuffer.setTest( stencilTest );
  14112. }
  14113. function setStencilWrite( stencilWrite ) {
  14114. stencilBuffer.setMask( stencilWrite );
  14115. }
  14116. function setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  14117. stencilBuffer.setFunc( stencilFunc, stencilRef, stencilMask );
  14118. }
  14119. function setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  14120. stencilBuffer.setOp( stencilFail, stencilZFail, stencilZPass );
  14121. }
  14122. //
  14123. function setFlipSided( flipSided ) {
  14124. if ( currentFlipSided !== flipSided ) {
  14125. if ( flipSided ) {
  14126. gl.frontFace( gl.CW );
  14127. } else {
  14128. gl.frontFace( gl.CCW );
  14129. }
  14130. currentFlipSided = flipSided;
  14131. }
  14132. }
  14133. function setCullFace( cullFace ) {
  14134. if ( cullFace !== CullFaceNone ) {
  14135. enable( gl.CULL_FACE );
  14136. if ( cullFace !== currentCullFace ) {
  14137. if ( cullFace === CullFaceBack ) {
  14138. gl.cullFace( gl.BACK );
  14139. } else if ( cullFace === CullFaceFront ) {
  14140. gl.cullFace( gl.FRONT );
  14141. } else {
  14142. gl.cullFace( gl.FRONT_AND_BACK );
  14143. }
  14144. }
  14145. } else {
  14146. disable( gl.CULL_FACE );
  14147. }
  14148. currentCullFace = cullFace;
  14149. }
  14150. function setLineWidth( width ) {
  14151. if ( width !== currentLineWidth ) {
  14152. if ( lineWidthAvailable ) gl.lineWidth( width );
  14153. currentLineWidth = width;
  14154. }
  14155. }
  14156. function setPolygonOffset( polygonOffset, factor, units ) {
  14157. if ( polygonOffset ) {
  14158. enable( gl.POLYGON_OFFSET_FILL );
  14159. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  14160. gl.polygonOffset( factor, units );
  14161. currentPolygonOffsetFactor = factor;
  14162. currentPolygonOffsetUnits = units;
  14163. }
  14164. } else {
  14165. disable( gl.POLYGON_OFFSET_FILL );
  14166. }
  14167. }
  14168. function getScissorTest() {
  14169. return currentScissorTest;
  14170. }
  14171. function setScissorTest( scissorTest ) {
  14172. currentScissorTest = scissorTest;
  14173. if ( scissorTest ) {
  14174. enable( gl.SCISSOR_TEST );
  14175. } else {
  14176. disable( gl.SCISSOR_TEST );
  14177. }
  14178. }
  14179. // texture
  14180. function activeTexture( webglSlot ) {
  14181. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14182. if ( currentTextureSlot !== webglSlot ) {
  14183. gl.activeTexture( webglSlot );
  14184. currentTextureSlot = webglSlot;
  14185. }
  14186. }
  14187. function bindTexture( webglType, webglTexture ) {
  14188. if ( currentTextureSlot === null ) {
  14189. activeTexture();
  14190. }
  14191. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  14192. if ( boundTexture === undefined ) {
  14193. boundTexture = { type: undefined, texture: undefined };
  14194. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  14195. }
  14196. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  14197. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  14198. boundTexture.type = webglType;
  14199. boundTexture.texture = webglTexture;
  14200. }
  14201. }
  14202. function compressedTexImage2D() {
  14203. try {
  14204. gl.compressedTexImage2D.apply( gl, arguments );
  14205. } catch ( error ) {
  14206. console.error( error );
  14207. }
  14208. }
  14209. function texImage2D() {
  14210. try {
  14211. gl.texImage2D.apply( gl, arguments );
  14212. } catch ( error ) {
  14213. console.error( error );
  14214. }
  14215. }
  14216. //
  14217. function scissor( scissor ) {
  14218. if ( currentScissor.equals( scissor ) === false ) {
  14219. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  14220. currentScissor.copy( scissor );
  14221. }
  14222. }
  14223. function viewport( viewport ) {
  14224. if ( currentViewport.equals( viewport ) === false ) {
  14225. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  14226. currentViewport.copy( viewport );
  14227. }
  14228. }
  14229. //
  14230. function reset() {
  14231. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  14232. if ( enabledAttributes[ i ] === 1 ) {
  14233. gl.disableVertexAttribArray( i );
  14234. enabledAttributes[ i ] = 0;
  14235. }
  14236. }
  14237. capabilities = {};
  14238. compressedTextureFormats = null;
  14239. currentTextureSlot = null;
  14240. currentBoundTextures = {};
  14241. currentBlending = null;
  14242. currentFlipSided = null;
  14243. currentCullFace = null;
  14244. colorBuffer.reset();
  14245. depthBuffer.reset();
  14246. stencilBuffer.reset();
  14247. }
  14248. return {
  14249. buffers: {
  14250. color: colorBuffer,
  14251. depth: depthBuffer,
  14252. stencil: stencilBuffer
  14253. },
  14254. init: init,
  14255. initAttributes: initAttributes,
  14256. enableAttribute: enableAttribute,
  14257. enableAttributeAndDivisor: enableAttributeAndDivisor,
  14258. disableUnusedAttributes: disableUnusedAttributes,
  14259. enable: enable,
  14260. disable: disable,
  14261. getCompressedTextureFormats: getCompressedTextureFormats,
  14262. setBlending: setBlending,
  14263. setColorWrite: setColorWrite,
  14264. setDepthTest: setDepthTest,
  14265. setDepthWrite: setDepthWrite,
  14266. setDepthFunc: setDepthFunc,
  14267. setStencilTest: setStencilTest,
  14268. setStencilWrite: setStencilWrite,
  14269. setStencilFunc: setStencilFunc,
  14270. setStencilOp: setStencilOp,
  14271. setFlipSided: setFlipSided,
  14272. setCullFace: setCullFace,
  14273. setLineWidth: setLineWidth,
  14274. setPolygonOffset: setPolygonOffset,
  14275. getScissorTest: getScissorTest,
  14276. setScissorTest: setScissorTest,
  14277. activeTexture: activeTexture,
  14278. bindTexture: bindTexture,
  14279. compressedTexImage2D: compressedTexImage2D,
  14280. texImage2D: texImage2D,
  14281. scissor: scissor,
  14282. viewport: viewport,
  14283. reset: reset
  14284. };
  14285. }
  14286. /**
  14287. * @author mrdoob / http://mrdoob.com/
  14288. */
  14289. function WebGLCapabilities( gl, extensions, parameters ) {
  14290. var maxAnisotropy;
  14291. function getMaxAnisotropy() {
  14292. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  14293. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14294. if ( extension !== null ) {
  14295. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  14296. } else {
  14297. maxAnisotropy = 0;
  14298. }
  14299. return maxAnisotropy;
  14300. }
  14301. function getMaxPrecision( precision ) {
  14302. if ( precision === 'highp' ) {
  14303. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  14304. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  14305. return 'highp';
  14306. }
  14307. precision = 'mediump';
  14308. }
  14309. if ( precision === 'mediump' ) {
  14310. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  14311. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  14312. return 'mediump';
  14313. }
  14314. }
  14315. return 'lowp';
  14316. }
  14317. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  14318. var maxPrecision = getMaxPrecision( precision );
  14319. if ( maxPrecision !== precision ) {
  14320. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  14321. precision = maxPrecision;
  14322. }
  14323. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  14324. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  14325. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  14326. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  14327. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  14328. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  14329. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  14330. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  14331. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  14332. var vertexTextures = maxVertexTextures > 0;
  14333. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  14334. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  14335. return {
  14336. getMaxAnisotropy: getMaxAnisotropy,
  14337. getMaxPrecision: getMaxPrecision,
  14338. precision: precision,
  14339. logarithmicDepthBuffer: logarithmicDepthBuffer,
  14340. maxTextures: maxTextures,
  14341. maxVertexTextures: maxVertexTextures,
  14342. maxTextureSize: maxTextureSize,
  14343. maxCubemapSize: maxCubemapSize,
  14344. maxAttributes: maxAttributes,
  14345. maxVertexUniforms: maxVertexUniforms,
  14346. maxVaryings: maxVaryings,
  14347. maxFragmentUniforms: maxFragmentUniforms,
  14348. vertexTextures: vertexTextures,
  14349. floatFragmentTextures: floatFragmentTextures,
  14350. floatVertexTextures: floatVertexTextures
  14351. };
  14352. }
  14353. /**
  14354. * @author mrdoob / http://mrdoob.com/
  14355. */
  14356. function WebGLExtensions( gl ) {
  14357. var extensions = {};
  14358. return {
  14359. get: function ( name ) {
  14360. if ( extensions[ name ] !== undefined ) {
  14361. return extensions[ name ];
  14362. }
  14363. var extension;
  14364. switch ( name ) {
  14365. case 'WEBGL_depth_texture':
  14366. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  14367. break;
  14368. case 'EXT_texture_filter_anisotropic':
  14369. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14370. break;
  14371. case 'WEBGL_compressed_texture_s3tc':
  14372. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14373. break;
  14374. case 'WEBGL_compressed_texture_pvrtc':
  14375. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  14376. break;
  14377. case 'WEBGL_compressed_texture_etc1':
  14378. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  14379. break;
  14380. default:
  14381. extension = gl.getExtension( name );
  14382. }
  14383. if ( extension === null ) {
  14384. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  14385. }
  14386. extensions[ name ] = extension;
  14387. return extension;
  14388. }
  14389. };
  14390. }
  14391. /**
  14392. * @author tschw
  14393. */
  14394. function WebGLClipping() {
  14395. var scope = this,
  14396. globalState = null,
  14397. numGlobalPlanes = 0,
  14398. localClippingEnabled = false,
  14399. renderingShadows = false,
  14400. plane = new Plane(),
  14401. viewNormalMatrix = new Matrix3(),
  14402. uniform = { value: null, needsUpdate: false };
  14403. this.uniform = uniform;
  14404. this.numPlanes = 0;
  14405. this.numIntersection = 0;
  14406. this.init = function( planes, enableLocalClipping, camera ) {
  14407. var enabled =
  14408. planes.length !== 0 ||
  14409. enableLocalClipping ||
  14410. // enable state of previous frame - the clipping code has to
  14411. // run another frame in order to reset the state:
  14412. numGlobalPlanes !== 0 ||
  14413. localClippingEnabled;
  14414. localClippingEnabled = enableLocalClipping;
  14415. globalState = projectPlanes( planes, camera, 0 );
  14416. numGlobalPlanes = planes.length;
  14417. return enabled;
  14418. };
  14419. this.beginShadows = function() {
  14420. renderingShadows = true;
  14421. projectPlanes( null );
  14422. };
  14423. this.endShadows = function() {
  14424. renderingShadows = false;
  14425. resetGlobalState();
  14426. };
  14427. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  14428. if ( ! localClippingEnabled ||
  14429. planes === null || planes.length === 0 ||
  14430. renderingShadows && ! clipShadows ) {
  14431. // there's no local clipping
  14432. if ( renderingShadows ) {
  14433. // there's no global clipping
  14434. projectPlanes( null );
  14435. } else {
  14436. resetGlobalState();
  14437. }
  14438. } else {
  14439. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  14440. lGlobal = nGlobal * 4,
  14441. dstArray = cache.clippingState || null;
  14442. uniform.value = dstArray; // ensure unique state
  14443. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  14444. for ( var i = 0; i !== lGlobal; ++ i ) {
  14445. dstArray[ i ] = globalState[ i ];
  14446. }
  14447. cache.clippingState = dstArray;
  14448. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  14449. this.numPlanes += nGlobal;
  14450. }
  14451. };
  14452. function resetGlobalState() {
  14453. if ( uniform.value !== globalState ) {
  14454. uniform.value = globalState;
  14455. uniform.needsUpdate = numGlobalPlanes > 0;
  14456. }
  14457. scope.numPlanes = numGlobalPlanes;
  14458. scope.numIntersection = 0;
  14459. }
  14460. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  14461. var nPlanes = planes !== null ? planes.length : 0,
  14462. dstArray = null;
  14463. if ( nPlanes !== 0 ) {
  14464. dstArray = uniform.value;
  14465. if ( skipTransform !== true || dstArray === null ) {
  14466. var flatSize = dstOffset + nPlanes * 4,
  14467. viewMatrix = camera.matrixWorldInverse;
  14468. viewNormalMatrix.getNormalMatrix( viewMatrix );
  14469. if ( dstArray === null || dstArray.length < flatSize ) {
  14470. dstArray = new Float32Array( flatSize );
  14471. }
  14472. for ( var i = 0, i4 = dstOffset;
  14473. i !== nPlanes; ++ i, i4 += 4 ) {
  14474. plane.copy( planes[ i ] ).
  14475. applyMatrix4( viewMatrix, viewNormalMatrix );
  14476. plane.normal.toArray( dstArray, i4 );
  14477. dstArray[ i4 + 3 ] = plane.constant;
  14478. }
  14479. }
  14480. uniform.value = dstArray;
  14481. uniform.needsUpdate = true;
  14482. }
  14483. scope.numPlanes = nPlanes;
  14484. return dstArray;
  14485. }
  14486. }
  14487. /**
  14488. * @author supereggbert / http://www.paulbrunt.co.uk/
  14489. * @author mrdoob / http://mrdoob.com/
  14490. * @author alteredq / http://alteredqualia.com/
  14491. * @author szimek / https://github.com/szimek/
  14492. * @author tschw
  14493. */
  14494. function WebGLRenderer( parameters ) {
  14495. console.log( 'THREE.WebGLRenderer', REVISION );
  14496. parameters = parameters || {};
  14497. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  14498. _context = parameters.context !== undefined ? parameters.context : null,
  14499. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14500. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14501. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14502. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14503. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14504. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  14505. var lights = [];
  14506. var opaqueObjects = [];
  14507. var opaqueObjectsLastIndex = - 1;
  14508. var transparentObjects = [];
  14509. var transparentObjectsLastIndex = - 1;
  14510. var morphInfluences = new Float32Array( 8 );
  14511. var sprites = [];
  14512. var lensFlares = [];
  14513. // public properties
  14514. this.domElement = _canvas;
  14515. this.context = null;
  14516. // clearing
  14517. this.autoClear = true;
  14518. this.autoClearColor = true;
  14519. this.autoClearDepth = true;
  14520. this.autoClearStencil = true;
  14521. // scene graph
  14522. this.sortObjects = true;
  14523. // user-defined clipping
  14524. this.clippingPlanes = [];
  14525. this.localClippingEnabled = false;
  14526. // physically based shading
  14527. this.gammaFactor = 2.0; // for backwards compatibility
  14528. this.gammaInput = false;
  14529. this.gammaOutput = false;
  14530. // physical lights
  14531. this.physicallyCorrectLights = false;
  14532. // tone mapping
  14533. this.toneMapping = LinearToneMapping;
  14534. this.toneMappingExposure = 1.0;
  14535. this.toneMappingWhitePoint = 1.0;
  14536. // morphs
  14537. this.maxMorphTargets = 8;
  14538. this.maxMorphNormals = 4;
  14539. // internal properties
  14540. var _this = this,
  14541. // internal state cache
  14542. _currentProgram = null,
  14543. _currentRenderTarget = null,
  14544. _currentFramebuffer = null,
  14545. _currentMaterialId = - 1,
  14546. _currentGeometryProgram = '',
  14547. _currentCamera = null,
  14548. _currentScissor = new Vector4(),
  14549. _currentScissorTest = null,
  14550. _currentViewport = new Vector4(),
  14551. //
  14552. _usedTextureUnits = 0,
  14553. //
  14554. _clearColor = new Color( 0x000000 ),
  14555. _clearAlpha = 0,
  14556. _width = _canvas.width,
  14557. _height = _canvas.height,
  14558. _pixelRatio = 1,
  14559. _scissor = new Vector4( 0, 0, _width, _height ),
  14560. _scissorTest = false,
  14561. _viewport = new Vector4( 0, 0, _width, _height ),
  14562. // frustum
  14563. _frustum = new Frustum(),
  14564. // clipping
  14565. _clipping = new WebGLClipping(),
  14566. _clippingEnabled = false,
  14567. _localClippingEnabled = false,
  14568. _sphere = new Sphere(),
  14569. // camera matrices cache
  14570. _projScreenMatrix = new Matrix4(),
  14571. _vector3 = new Vector3(),
  14572. _matrix4 = new Matrix4(),
  14573. _matrix42 = new Matrix4(),
  14574. // light arrays cache
  14575. _lights = {
  14576. hash: '',
  14577. ambient: [ 0, 0, 0 ],
  14578. directional: [],
  14579. directionalShadowMap: [],
  14580. directionalShadowMatrix: [],
  14581. spot: [],
  14582. spotShadowMap: [],
  14583. spotShadowMatrix: [],
  14584. rectArea: [],
  14585. point: [],
  14586. pointShadowMap: [],
  14587. pointShadowMatrix: [],
  14588. hemi: [],
  14589. shadows: []
  14590. },
  14591. // info
  14592. _infoRender = {
  14593. calls: 0,
  14594. vertices: 0,
  14595. faces: 0,
  14596. points: 0
  14597. };
  14598. this.info = {
  14599. render: _infoRender,
  14600. memory: {
  14601. geometries: 0,
  14602. textures: 0
  14603. },
  14604. programs: null
  14605. };
  14606. // initialize
  14607. var _gl;
  14608. try {
  14609. var attributes = {
  14610. alpha: _alpha,
  14611. depth: _depth,
  14612. stencil: _stencil,
  14613. antialias: _antialias,
  14614. premultipliedAlpha: _premultipliedAlpha,
  14615. preserveDrawingBuffer: _preserveDrawingBuffer
  14616. };
  14617. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  14618. if ( _gl === null ) {
  14619. if ( _canvas.getContext( 'webgl' ) !== null ) {
  14620. throw 'Error creating WebGL context with your selected attributes.';
  14621. } else {
  14622. throw 'Error creating WebGL context.';
  14623. }
  14624. }
  14625. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14626. if ( _gl.getShaderPrecisionFormat === undefined ) {
  14627. _gl.getShaderPrecisionFormat = function () {
  14628. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  14629. };
  14630. }
  14631. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14632. } catch ( error ) {
  14633. console.error( 'THREE.WebGLRenderer: ' + error );
  14634. }
  14635. var extensions = new WebGLExtensions( _gl );
  14636. extensions.get( 'WEBGL_depth_texture' );
  14637. extensions.get( 'OES_texture_float' );
  14638. extensions.get( 'OES_texture_float_linear' );
  14639. extensions.get( 'OES_texture_half_float' );
  14640. extensions.get( 'OES_texture_half_float_linear' );
  14641. extensions.get( 'OES_standard_derivatives' );
  14642. extensions.get( 'ANGLE_instanced_arrays' );
  14643. if ( extensions.get( 'OES_element_index_uint' ) ) {
  14644. BufferGeometry.MaxIndex = 4294967296;
  14645. }
  14646. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  14647. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  14648. var properties = new WebGLProperties();
  14649. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  14650. var objects = new WebGLObjects( _gl, properties, this.info );
  14651. var programCache = new WebGLPrograms( this, capabilities );
  14652. var lightCache = new WebGLLights();
  14653. this.info.programs = programCache.programs;
  14654. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  14655. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  14656. //
  14657. var backgroundPlaneCamera, backgroundPlaneMesh;
  14658. var backgroundBoxCamera, backgroundBoxMesh;
  14659. //
  14660. function getTargetPixelRatio() {
  14661. return _currentRenderTarget === null ? _pixelRatio : 1;
  14662. }
  14663. function setDefaultGLState() {
  14664. state.init();
  14665. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  14666. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  14667. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  14668. }
  14669. function resetGLState() {
  14670. _currentProgram = null;
  14671. _currentCamera = null;
  14672. _currentGeometryProgram = '';
  14673. _currentMaterialId = - 1;
  14674. state.reset();
  14675. }
  14676. setDefaultGLState();
  14677. this.context = _gl;
  14678. this.capabilities = capabilities;
  14679. this.extensions = extensions;
  14680. this.properties = properties;
  14681. this.state = state;
  14682. // shadow map
  14683. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  14684. this.shadowMap = shadowMap;
  14685. // Plugins
  14686. var spritePlugin = new SpritePlugin( this, sprites );
  14687. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  14688. // API
  14689. this.getContext = function () {
  14690. return _gl;
  14691. };
  14692. this.getContextAttributes = function () {
  14693. return _gl.getContextAttributes();
  14694. };
  14695. this.forceContextLoss = function () {
  14696. extensions.get( 'WEBGL_lose_context' ).loseContext();
  14697. };
  14698. this.getMaxAnisotropy = function () {
  14699. return capabilities.getMaxAnisotropy();
  14700. };
  14701. this.getPrecision = function () {
  14702. return capabilities.precision;
  14703. };
  14704. this.getPixelRatio = function () {
  14705. return _pixelRatio;
  14706. };
  14707. this.setPixelRatio = function ( value ) {
  14708. if ( value === undefined ) return;
  14709. _pixelRatio = value;
  14710. this.setSize( _viewport.z, _viewport.w, false );
  14711. };
  14712. this.getSize = function () {
  14713. return {
  14714. width: _width,
  14715. height: _height
  14716. };
  14717. };
  14718. this.setSize = function ( width, height, updateStyle ) {
  14719. _width = width;
  14720. _height = height;
  14721. _canvas.width = width * _pixelRatio;
  14722. _canvas.height = height * _pixelRatio;
  14723. if ( updateStyle !== false ) {
  14724. _canvas.style.width = width + 'px';
  14725. _canvas.style.height = height + 'px';
  14726. }
  14727. this.setViewport( 0, 0, width, height );
  14728. };
  14729. this.setViewport = function ( x, y, width, height ) {
  14730. state.viewport( _viewport.set( x, y, width, height ) );
  14731. };
  14732. this.setScissor = function ( x, y, width, height ) {
  14733. state.scissor( _scissor.set( x, y, width, height ) );
  14734. };
  14735. this.setScissorTest = function ( boolean ) {
  14736. state.setScissorTest( _scissorTest = boolean );
  14737. };
  14738. // Clearing
  14739. this.getClearColor = function () {
  14740. return _clearColor;
  14741. };
  14742. this.setClearColor = function ( color, alpha ) {
  14743. _clearColor.set( color );
  14744. _clearAlpha = alpha !== undefined ? alpha : 1;
  14745. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  14746. };
  14747. this.getClearAlpha = function () {
  14748. return _clearAlpha;
  14749. };
  14750. this.setClearAlpha = function ( alpha ) {
  14751. _clearAlpha = alpha;
  14752. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  14753. };
  14754. this.clear = function ( color, depth, stencil ) {
  14755. var bits = 0;
  14756. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  14757. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  14758. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  14759. _gl.clear( bits );
  14760. };
  14761. this.clearColor = function () {
  14762. this.clear( true, false, false );
  14763. };
  14764. this.clearDepth = function () {
  14765. this.clear( false, true, false );
  14766. };
  14767. this.clearStencil = function () {
  14768. this.clear( false, false, true );
  14769. };
  14770. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  14771. this.setRenderTarget( renderTarget );
  14772. this.clear( color, depth, stencil );
  14773. };
  14774. // Reset
  14775. this.resetGLState = resetGLState;
  14776. this.dispose = function() {
  14777. transparentObjects = [];
  14778. transparentObjectsLastIndex = -1;
  14779. opaqueObjects = [];
  14780. opaqueObjectsLastIndex = -1;
  14781. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14782. };
  14783. // Events
  14784. function onContextLost( event ) {
  14785. event.preventDefault();
  14786. resetGLState();
  14787. setDefaultGLState();
  14788. properties.clear();
  14789. }
  14790. function onMaterialDispose( event ) {
  14791. var material = event.target;
  14792. material.removeEventListener( 'dispose', onMaterialDispose );
  14793. deallocateMaterial( material );
  14794. }
  14795. // Buffer deallocation
  14796. function deallocateMaterial( material ) {
  14797. releaseMaterialProgramReference( material );
  14798. properties.delete( material );
  14799. }
  14800. function releaseMaterialProgramReference( material ) {
  14801. var programInfo = properties.get( material ).program;
  14802. material.program = undefined;
  14803. if ( programInfo !== undefined ) {
  14804. programCache.releaseProgram( programInfo );
  14805. }
  14806. }
  14807. // Buffer rendering
  14808. this.renderBufferImmediate = function ( object, program, material ) {
  14809. state.initAttributes();
  14810. var buffers = properties.get( object );
  14811. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  14812. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  14813. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  14814. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  14815. var attributes = program.getAttributes();
  14816. if ( object.hasPositions ) {
  14817. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  14818. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  14819. state.enableAttribute( attributes.position );
  14820. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14821. }
  14822. if ( object.hasNormals ) {
  14823. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  14824. if ( ! material.isMeshPhongMaterial &&
  14825. ! material.isMeshStandardMaterial &&
  14826. ! material.isMeshNormalMaterial &&
  14827. material.shading === FlatShading ) {
  14828. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  14829. var array = object.normalArray;
  14830. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  14831. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  14832. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  14833. array[ i + 0 ] = nx;
  14834. array[ i + 1 ] = ny;
  14835. array[ i + 2 ] = nz;
  14836. array[ i + 3 ] = nx;
  14837. array[ i + 4 ] = ny;
  14838. array[ i + 5 ] = nz;
  14839. array[ i + 6 ] = nx;
  14840. array[ i + 7 ] = ny;
  14841. array[ i + 8 ] = nz;
  14842. }
  14843. }
  14844. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  14845. state.enableAttribute( attributes.normal );
  14846. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  14847. }
  14848. if ( object.hasUvs && material.map ) {
  14849. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  14850. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  14851. state.enableAttribute( attributes.uv );
  14852. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  14853. }
  14854. if ( object.hasColors && material.vertexColors !== NoColors ) {
  14855. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  14856. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  14857. state.enableAttribute( attributes.color );
  14858. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  14859. }
  14860. state.disableUnusedAttributes();
  14861. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  14862. object.count = 0;
  14863. };
  14864. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  14865. setMaterial( material );
  14866. var program = setProgram( camera, fog, material, object );
  14867. var updateBuffers = false;
  14868. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  14869. if ( geometryProgram !== _currentGeometryProgram ) {
  14870. _currentGeometryProgram = geometryProgram;
  14871. updateBuffers = true;
  14872. }
  14873. // morph targets
  14874. var morphTargetInfluences = object.morphTargetInfluences;
  14875. if ( morphTargetInfluences !== undefined ) {
  14876. var activeInfluences = [];
  14877. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  14878. var influence = morphTargetInfluences[ i ];
  14879. activeInfluences.push( [ influence, i ] );
  14880. }
  14881. activeInfluences.sort( absNumericalSort );
  14882. if ( activeInfluences.length > 8 ) {
  14883. activeInfluences.length = 8;
  14884. }
  14885. var morphAttributes = geometry.morphAttributes;
  14886. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  14887. var influence = activeInfluences[ i ];
  14888. morphInfluences[ i ] = influence[ 0 ];
  14889. if ( influence[ 0 ] !== 0 ) {
  14890. var index = influence[ 1 ];
  14891. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  14892. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  14893. } else {
  14894. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  14895. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  14896. }
  14897. }
  14898. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  14899. morphInfluences[ i ] = 0.0;
  14900. }
  14901. program.getUniforms().setValue(
  14902. _gl, 'morphTargetInfluences', morphInfluences );
  14903. updateBuffers = true;
  14904. }
  14905. //
  14906. var index = geometry.index;
  14907. var position = geometry.attributes.position;
  14908. var rangeFactor = 1;
  14909. if ( material.wireframe === true ) {
  14910. index = objects.getWireframeAttribute( geometry );
  14911. rangeFactor = 2;
  14912. }
  14913. var renderer;
  14914. if ( index !== null ) {
  14915. renderer = indexedBufferRenderer;
  14916. renderer.setIndex( index );
  14917. } else {
  14918. renderer = bufferRenderer;
  14919. }
  14920. if ( updateBuffers ) {
  14921. setupVertexAttributes( material, program, geometry );
  14922. if ( index !== null ) {
  14923. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  14924. }
  14925. }
  14926. //
  14927. var dataCount = 0;
  14928. if ( index !== null ) {
  14929. dataCount = index.count;
  14930. } else if ( position !== undefined ) {
  14931. dataCount = position.count;
  14932. }
  14933. var rangeStart = geometry.drawRange.start * rangeFactor;
  14934. var rangeCount = geometry.drawRange.count * rangeFactor;
  14935. var groupStart = group !== null ? group.start * rangeFactor : 0;
  14936. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14937. var drawStart = Math.max( rangeStart, groupStart );
  14938. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  14939. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  14940. if ( drawCount === 0 ) return;
  14941. //
  14942. if ( object.isMesh ) {
  14943. if ( material.wireframe === true ) {
  14944. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  14945. renderer.setMode( _gl.LINES );
  14946. } else {
  14947. switch ( object.drawMode ) {
  14948. case TrianglesDrawMode:
  14949. renderer.setMode( _gl.TRIANGLES );
  14950. break;
  14951. case TriangleStripDrawMode:
  14952. renderer.setMode( _gl.TRIANGLE_STRIP );
  14953. break;
  14954. case TriangleFanDrawMode:
  14955. renderer.setMode( _gl.TRIANGLE_FAN );
  14956. break;
  14957. }
  14958. }
  14959. } else if ( object.isLine ) {
  14960. var lineWidth = material.linewidth;
  14961. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  14962. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  14963. if ( object.isLineSegments ) {
  14964. renderer.setMode( _gl.LINES );
  14965. } else {
  14966. renderer.setMode( _gl.LINE_STRIP );
  14967. }
  14968. } else if ( object.isPoints ) {
  14969. renderer.setMode( _gl.POINTS );
  14970. }
  14971. if ( geometry && geometry.isInstancedBufferGeometry ) {
  14972. if ( geometry.maxInstancedCount > 0 ) {
  14973. renderer.renderInstances( geometry, drawStart, drawCount );
  14974. }
  14975. } else {
  14976. renderer.render( drawStart, drawCount );
  14977. }
  14978. };
  14979. function setupVertexAttributes( material, program, geometry, startIndex ) {
  14980. var extension;
  14981. if ( geometry && geometry.isInstancedBufferGeometry ) {
  14982. extension = extensions.get( 'ANGLE_instanced_arrays' );
  14983. if ( extension === null ) {
  14984. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  14985. return;
  14986. }
  14987. }
  14988. if ( startIndex === undefined ) startIndex = 0;
  14989. state.initAttributes();
  14990. var geometryAttributes = geometry.attributes;
  14991. var programAttributes = program.getAttributes();
  14992. var materialDefaultAttributeValues = material.defaultAttributeValues;
  14993. for ( var name in programAttributes ) {
  14994. var programAttribute = programAttributes[ name ];
  14995. if ( programAttribute >= 0 ) {
  14996. var geometryAttribute = geometryAttributes[ name ];
  14997. if ( geometryAttribute !== undefined ) {
  14998. var normalized = geometryAttribute.normalized;
  14999. var size = geometryAttribute.itemSize;
  15000. var attributeProperties = objects.getAttributeProperties( geometryAttribute );
  15001. var buffer = attributeProperties.__webglBuffer;
  15002. var type = attributeProperties.type;
  15003. var bytesPerElement = attributeProperties.bytesPerElement;
  15004. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  15005. var data = geometryAttribute.data;
  15006. var stride = data.stride;
  15007. var offset = geometryAttribute.offset;
  15008. if ( data && data.isInstancedInterleavedBuffer ) {
  15009. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  15010. if ( geometry.maxInstancedCount === undefined ) {
  15011. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  15012. }
  15013. } else {
  15014. state.enableAttribute( programAttribute );
  15015. }
  15016. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15017. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  15018. } else {
  15019. if ( geometryAttribute.isInstancedBufferAttribute ) {
  15020. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  15021. if ( geometry.maxInstancedCount === undefined ) {
  15022. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15023. }
  15024. } else {
  15025. state.enableAttribute( programAttribute );
  15026. }
  15027. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15028. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  15029. }
  15030. } else if ( materialDefaultAttributeValues !== undefined ) {
  15031. var value = materialDefaultAttributeValues[ name ];
  15032. if ( value !== undefined ) {
  15033. switch ( value.length ) {
  15034. case 2:
  15035. _gl.vertexAttrib2fv( programAttribute, value );
  15036. break;
  15037. case 3:
  15038. _gl.vertexAttrib3fv( programAttribute, value );
  15039. break;
  15040. case 4:
  15041. _gl.vertexAttrib4fv( programAttribute, value );
  15042. break;
  15043. default:
  15044. _gl.vertexAttrib1fv( programAttribute, value );
  15045. }
  15046. }
  15047. }
  15048. }
  15049. }
  15050. state.disableUnusedAttributes();
  15051. }
  15052. // Sorting
  15053. function absNumericalSort( a, b ) {
  15054. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  15055. }
  15056. function painterSortStable( a, b ) {
  15057. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15058. return a.object.renderOrder - b.object.renderOrder;
  15059. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  15060. return a.material.program.id - b.material.program.id;
  15061. } else if ( a.material.id !== b.material.id ) {
  15062. return a.material.id - b.material.id;
  15063. } else if ( a.z !== b.z ) {
  15064. return a.z - b.z;
  15065. } else {
  15066. return a.id - b.id;
  15067. }
  15068. }
  15069. function reversePainterSortStable( a, b ) {
  15070. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15071. return a.object.renderOrder - b.object.renderOrder;
  15072. } if ( a.z !== b.z ) {
  15073. return b.z - a.z;
  15074. } else {
  15075. return a.id - b.id;
  15076. }
  15077. }
  15078. // Rendering
  15079. this.render = function ( scene, camera, renderTarget, forceClear ) {
  15080. if ( camera !== undefined && camera.isCamera !== true ) {
  15081. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15082. return;
  15083. }
  15084. // reset caching for this frame
  15085. _currentGeometryProgram = '';
  15086. _currentMaterialId = - 1;
  15087. _currentCamera = null;
  15088. // update scene graph
  15089. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15090. // update camera matrices and frustum
  15091. if ( camera.parent === null ) camera.updateMatrixWorld();
  15092. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  15093. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15094. _frustum.setFromMatrix( _projScreenMatrix );
  15095. lights.length = 0;
  15096. opaqueObjectsLastIndex = - 1;
  15097. transparentObjectsLastIndex = - 1;
  15098. sprites.length = 0;
  15099. lensFlares.length = 0;
  15100. _localClippingEnabled = this.localClippingEnabled;
  15101. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  15102. projectObject( scene, camera );
  15103. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  15104. transparentObjects.length = transparentObjectsLastIndex + 1;
  15105. if ( _this.sortObjects === true ) {
  15106. opaqueObjects.sort( painterSortStable );
  15107. transparentObjects.sort( reversePainterSortStable );
  15108. }
  15109. //
  15110. if ( _clippingEnabled ) _clipping.beginShadows();
  15111. setupShadows( lights );
  15112. shadowMap.render( scene, camera );
  15113. setupLights( lights, camera );
  15114. if ( _clippingEnabled ) _clipping.endShadows();
  15115. //
  15116. _infoRender.calls = 0;
  15117. _infoRender.vertices = 0;
  15118. _infoRender.faces = 0;
  15119. _infoRender.points = 0;
  15120. if ( renderTarget === undefined ) {
  15121. renderTarget = null;
  15122. }
  15123. this.setRenderTarget( renderTarget );
  15124. //
  15125. var background = scene.background;
  15126. if ( background === null ) {
  15127. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  15128. } else if ( background && background.isColor ) {
  15129. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  15130. forceClear = true;
  15131. }
  15132. if ( this.autoClear || forceClear ) {
  15133. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  15134. }
  15135. if ( background && background.isCubeTexture ) {
  15136. if ( backgroundBoxCamera === undefined ) {
  15137. backgroundBoxCamera = new PerspectiveCamera();
  15138. backgroundBoxMesh = new Mesh(
  15139. new BoxBufferGeometry( 5, 5, 5 ),
  15140. new ShaderMaterial( {
  15141. uniforms: ShaderLib.cube.uniforms,
  15142. vertexShader: ShaderLib.cube.vertexShader,
  15143. fragmentShader: ShaderLib.cube.fragmentShader,
  15144. side: BackSide,
  15145. depthTest: false,
  15146. depthWrite: false,
  15147. fog: false
  15148. } )
  15149. );
  15150. }
  15151. backgroundBoxCamera.projectionMatrix.copy( camera.projectionMatrix );
  15152. backgroundBoxCamera.matrixWorld.extractRotation( camera.matrixWorld );
  15153. backgroundBoxCamera.matrixWorldInverse.getInverse( backgroundBoxCamera.matrixWorld );
  15154. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  15155. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundBoxCamera.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  15156. objects.update( backgroundBoxMesh );
  15157. _this.renderBufferDirect( backgroundBoxCamera, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  15158. } else if ( background && background.isTexture ) {
  15159. if ( backgroundPlaneCamera === undefined ) {
  15160. backgroundPlaneCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  15161. backgroundPlaneMesh = new Mesh(
  15162. new PlaneBufferGeometry( 2, 2 ),
  15163. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  15164. );
  15165. }
  15166. backgroundPlaneMesh.material.map = background;
  15167. objects.update( backgroundPlaneMesh );
  15168. _this.renderBufferDirect( backgroundPlaneCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  15169. }
  15170. //
  15171. if ( scene.overrideMaterial ) {
  15172. var overrideMaterial = scene.overrideMaterial;
  15173. renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  15174. renderObjects( transparentObjects, scene, camera, overrideMaterial );
  15175. } else {
  15176. // opaque pass (front-to-back order)
  15177. state.setBlending( NoBlending );
  15178. renderObjects( opaqueObjects, scene, camera );
  15179. // transparent pass (back-to-front order)
  15180. renderObjects( transparentObjects, scene, camera );
  15181. }
  15182. // custom render plugins (post pass)
  15183. spritePlugin.render( scene, camera );
  15184. lensFlarePlugin.render( scene, camera, _currentViewport );
  15185. // Generate mipmap if we're using any kind of mipmap filtering
  15186. if ( renderTarget ) {
  15187. textures.updateRenderTargetMipmap( renderTarget );
  15188. }
  15189. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15190. state.setDepthTest( true );
  15191. state.setDepthWrite( true );
  15192. state.setColorWrite( true );
  15193. // _gl.finish();
  15194. };
  15195. function pushRenderItem( object, geometry, material, z, group ) {
  15196. var array, index;
  15197. // allocate the next position in the appropriate array
  15198. if ( material.transparent ) {
  15199. array = transparentObjects;
  15200. index = ++ transparentObjectsLastIndex;
  15201. } else {
  15202. array = opaqueObjects;
  15203. index = ++ opaqueObjectsLastIndex;
  15204. }
  15205. // recycle existing render item or grow the array
  15206. var renderItem = array[ index ];
  15207. if ( renderItem !== undefined ) {
  15208. renderItem.id = object.id;
  15209. renderItem.object = object;
  15210. renderItem.geometry = geometry;
  15211. renderItem.material = material;
  15212. renderItem.z = _vector3.z;
  15213. renderItem.group = group;
  15214. } else {
  15215. renderItem = {
  15216. id: object.id,
  15217. object: object,
  15218. geometry: geometry,
  15219. material: material,
  15220. z: _vector3.z,
  15221. group: group
  15222. };
  15223. // assert( index === array.length );
  15224. array.push( renderItem );
  15225. }
  15226. }
  15227. // TODO Duplicated code (Frustum)
  15228. function isObjectViewable( object ) {
  15229. var geometry = object.geometry;
  15230. if ( geometry.boundingSphere === null )
  15231. geometry.computeBoundingSphere();
  15232. _sphere.copy( geometry.boundingSphere ).
  15233. applyMatrix4( object.matrixWorld );
  15234. return isSphereViewable( _sphere );
  15235. }
  15236. function isSpriteViewable( sprite ) {
  15237. _sphere.center.set( 0, 0, 0 );
  15238. _sphere.radius = 0.7071067811865476;
  15239. _sphere.applyMatrix4( sprite.matrixWorld );
  15240. return isSphereViewable( _sphere );
  15241. }
  15242. function isSphereViewable( sphere ) {
  15243. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  15244. var numPlanes = _clipping.numPlanes;
  15245. if ( numPlanes === 0 ) return true;
  15246. var planes = _this.clippingPlanes,
  15247. center = sphere.center,
  15248. negRad = - sphere.radius,
  15249. i = 0;
  15250. do {
  15251. // out when deeper than radius in the negative halfspace
  15252. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  15253. } while ( ++ i !== numPlanes );
  15254. return true;
  15255. }
  15256. function projectObject( object, camera ) {
  15257. if ( object.visible === false ) return;
  15258. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  15259. if ( visible ) {
  15260. if ( object.isLight ) {
  15261. lights.push( object );
  15262. } else if ( object.isSprite ) {
  15263. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  15264. sprites.push( object );
  15265. }
  15266. } else if ( object.isLensFlare ) {
  15267. lensFlares.push( object );
  15268. } else if ( object.isImmediateRenderObject ) {
  15269. if ( _this.sortObjects === true ) {
  15270. _vector3.setFromMatrixPosition( object.matrixWorld );
  15271. _vector3.applyMatrix4( _projScreenMatrix );
  15272. }
  15273. pushRenderItem( object, null, object.material, _vector3.z, null );
  15274. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  15275. if ( object.isSkinnedMesh ) {
  15276. object.skeleton.update();
  15277. }
  15278. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  15279. var material = object.material;
  15280. if ( material.visible === true ) {
  15281. if ( _this.sortObjects === true ) {
  15282. _vector3.setFromMatrixPosition( object.matrixWorld );
  15283. _vector3.applyMatrix4( _projScreenMatrix );
  15284. }
  15285. var geometry = objects.update( object );
  15286. if ( material.isMultiMaterial ) {
  15287. var groups = geometry.groups;
  15288. var materials = material.materials;
  15289. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  15290. var group = groups[ i ];
  15291. var groupMaterial = materials[ group.materialIndex ];
  15292. if ( groupMaterial.visible === true ) {
  15293. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  15294. }
  15295. }
  15296. } else {
  15297. pushRenderItem( object, geometry, material, _vector3.z, null );
  15298. }
  15299. }
  15300. }
  15301. }
  15302. }
  15303. var children = object.children;
  15304. for ( var i = 0, l = children.length; i < l; i ++ ) {
  15305. projectObject( children[ i ], camera );
  15306. }
  15307. }
  15308. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  15309. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  15310. var renderItem = renderList[ i ];
  15311. var object = renderItem.object;
  15312. var geometry = renderItem.geometry;
  15313. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  15314. var group = renderItem.group;
  15315. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15316. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15317. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  15318. if ( object.isImmediateRenderObject ) {
  15319. setMaterial( material );
  15320. var program = setProgram( camera, scene.fog, material, object );
  15321. _currentGeometryProgram = '';
  15322. object.render( function ( object ) {
  15323. _this.renderBufferImmediate( object, program, material );
  15324. } );
  15325. } else {
  15326. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  15327. }
  15328. object.onAfterRender( _this, scene, camera, geometry, material, group );
  15329. }
  15330. }
  15331. function initMaterial( material, fog, object ) {
  15332. var materialProperties = properties.get( material );
  15333. var parameters = programCache.getParameters(
  15334. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  15335. var code = programCache.getProgramCode( material, parameters );
  15336. var program = materialProperties.program;
  15337. var programChange = true;
  15338. if ( program === undefined ) {
  15339. // new material
  15340. material.addEventListener( 'dispose', onMaterialDispose );
  15341. } else if ( program.code !== code ) {
  15342. // changed glsl or parameters
  15343. releaseMaterialProgramReference( material );
  15344. } else if ( parameters.shaderID !== undefined ) {
  15345. // same glsl and uniform list
  15346. return;
  15347. } else {
  15348. // only rebuild uniform list
  15349. programChange = false;
  15350. }
  15351. if ( programChange ) {
  15352. if ( parameters.shaderID ) {
  15353. var shader = ShaderLib[ parameters.shaderID ];
  15354. materialProperties.__webglShader = {
  15355. name: material.type,
  15356. uniforms: UniformsUtils.clone( shader.uniforms ),
  15357. vertexShader: shader.vertexShader,
  15358. fragmentShader: shader.fragmentShader
  15359. };
  15360. } else {
  15361. materialProperties.__webglShader = {
  15362. name: material.type,
  15363. uniforms: material.uniforms,
  15364. vertexShader: material.vertexShader,
  15365. fragmentShader: material.fragmentShader
  15366. };
  15367. }
  15368. material.__webglShader = materialProperties.__webglShader;
  15369. program = programCache.acquireProgram( material, parameters, code );
  15370. materialProperties.program = program;
  15371. material.program = program;
  15372. }
  15373. var attributes = program.getAttributes();
  15374. if ( material.morphTargets ) {
  15375. material.numSupportedMorphTargets = 0;
  15376. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  15377. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  15378. material.numSupportedMorphTargets ++;
  15379. }
  15380. }
  15381. }
  15382. if ( material.morphNormals ) {
  15383. material.numSupportedMorphNormals = 0;
  15384. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  15385. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  15386. material.numSupportedMorphNormals ++;
  15387. }
  15388. }
  15389. }
  15390. var uniforms = materialProperties.__webglShader.uniforms;
  15391. if ( ! material.isShaderMaterial &&
  15392. ! material.isRawShaderMaterial ||
  15393. material.clipping === true ) {
  15394. materialProperties.numClippingPlanes = _clipping.numPlanes;
  15395. materialProperties.numIntersection = _clipping.numIntersection;
  15396. uniforms.clippingPlanes = _clipping.uniform;
  15397. }
  15398. materialProperties.fog = fog;
  15399. // store the light setup it was created for
  15400. materialProperties.lightsHash = _lights.hash;
  15401. if ( material.lights ) {
  15402. // wire up the material to this renderer's lighting state
  15403. uniforms.ambientLightColor.value = _lights.ambient;
  15404. uniforms.directionalLights.value = _lights.directional;
  15405. uniforms.spotLights.value = _lights.spot;
  15406. uniforms.rectAreaLights.value = _lights.rectArea;
  15407. uniforms.pointLights.value = _lights.point;
  15408. uniforms.hemisphereLights.value = _lights.hemi;
  15409. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  15410. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  15411. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  15412. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  15413. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  15414. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  15415. // TODO (abelnation): add area lights shadow info to uniforms
  15416. }
  15417. var progUniforms = materialProperties.program.getUniforms(),
  15418. uniformsList =
  15419. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  15420. materialProperties.uniformsList = uniformsList;
  15421. }
  15422. function setMaterial( material ) {
  15423. material.side === DoubleSide
  15424. ? state.disable( _gl.CULL_FACE )
  15425. : state.enable( _gl.CULL_FACE );
  15426. state.setFlipSided( material.side === BackSide );
  15427. material.transparent === true
  15428. ? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  15429. : state.setBlending( NoBlending );
  15430. state.setDepthFunc( material.depthFunc );
  15431. state.setDepthTest( material.depthTest );
  15432. state.setDepthWrite( material.depthWrite );
  15433. state.setColorWrite( material.colorWrite );
  15434. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  15435. }
  15436. function setProgram( camera, fog, material, object ) {
  15437. _usedTextureUnits = 0;
  15438. var materialProperties = properties.get( material );
  15439. if ( _clippingEnabled ) {
  15440. if ( _localClippingEnabled || camera !== _currentCamera ) {
  15441. var useCache =
  15442. camera === _currentCamera &&
  15443. material.id === _currentMaterialId;
  15444. // we might want to call this function with some ClippingGroup
  15445. // object instead of the material, once it becomes feasible
  15446. // (#8465, #8379)
  15447. _clipping.setState(
  15448. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  15449. camera, materialProperties, useCache );
  15450. }
  15451. }
  15452. if ( material.needsUpdate === false ) {
  15453. if ( materialProperties.program === undefined ) {
  15454. material.needsUpdate = true;
  15455. } else if ( material.fog && materialProperties.fog !== fog ) {
  15456. material.needsUpdate = true;
  15457. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  15458. material.needsUpdate = true;
  15459. } else if ( materialProperties.numClippingPlanes !== undefined &&
  15460. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  15461. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  15462. material.needsUpdate = true;
  15463. }
  15464. }
  15465. if ( material.needsUpdate ) {
  15466. initMaterial( material, fog, object );
  15467. material.needsUpdate = false;
  15468. }
  15469. var refreshProgram = false;
  15470. var refreshMaterial = false;
  15471. var refreshLights = false;
  15472. var program = materialProperties.program,
  15473. p_uniforms = program.getUniforms(),
  15474. m_uniforms = materialProperties.__webglShader.uniforms;
  15475. if ( program.id !== _currentProgram ) {
  15476. _gl.useProgram( program.program );
  15477. _currentProgram = program.id;
  15478. refreshProgram = true;
  15479. refreshMaterial = true;
  15480. refreshLights = true;
  15481. }
  15482. if ( material.id !== _currentMaterialId ) {
  15483. _currentMaterialId = material.id;
  15484. refreshMaterial = true;
  15485. }
  15486. if ( refreshProgram || camera !== _currentCamera ) {
  15487. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  15488. if ( capabilities.logarithmicDepthBuffer ) {
  15489. p_uniforms.setValue( _gl, 'logDepthBufFC',
  15490. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15491. }
  15492. if ( camera !== _currentCamera ) {
  15493. _currentCamera = camera;
  15494. // lighting uniforms depend on the camera so enforce an update
  15495. // now, in case this material supports lights - or later, when
  15496. // the next material that does gets activated:
  15497. refreshMaterial = true; // set to true on material change
  15498. refreshLights = true; // remains set until update done
  15499. }
  15500. // load material specific uniforms
  15501. // (shader material also gets them for the sake of genericity)
  15502. if ( material.isShaderMaterial ||
  15503. material.isMeshPhongMaterial ||
  15504. material.isMeshStandardMaterial ||
  15505. material.envMap ) {
  15506. var uCamPos = p_uniforms.map.cameraPosition;
  15507. if ( uCamPos !== undefined ) {
  15508. uCamPos.setValue( _gl,
  15509. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  15510. }
  15511. }
  15512. if ( material.isMeshPhongMaterial ||
  15513. material.isMeshLambertMaterial ||
  15514. material.isMeshBasicMaterial ||
  15515. material.isMeshStandardMaterial ||
  15516. material.isShaderMaterial ||
  15517. material.skinning ) {
  15518. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  15519. }
  15520. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  15521. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  15522. }
  15523. // skinning uniforms must be set even if material didn't change
  15524. // auto-setting of texture unit for bone texture must go before other textures
  15525. // not sure why, but otherwise weird things happen
  15526. if ( material.skinning ) {
  15527. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  15528. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  15529. var skeleton = object.skeleton;
  15530. if ( skeleton ) {
  15531. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  15532. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  15533. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  15534. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  15535. } else {
  15536. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  15537. }
  15538. }
  15539. }
  15540. if ( refreshMaterial ) {
  15541. if ( material.lights ) {
  15542. // the current material requires lighting info
  15543. // note: all lighting uniforms are always set correctly
  15544. // they simply reference the renderer's state for their
  15545. // values
  15546. //
  15547. // use the current material's .needsUpdate flags to set
  15548. // the GL state when required
  15549. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  15550. }
  15551. // refresh uniforms common to several materials
  15552. if ( fog && material.fog ) {
  15553. refreshUniformsFog( m_uniforms, fog );
  15554. }
  15555. if ( material.isMeshBasicMaterial ||
  15556. material.isMeshLambertMaterial ||
  15557. material.isMeshPhongMaterial ||
  15558. material.isMeshStandardMaterial ||
  15559. material.isMeshNormalMaterial ||
  15560. material.isMeshDepthMaterial ) {
  15561. refreshUniformsCommon( m_uniforms, material );
  15562. }
  15563. // refresh single material specific uniforms
  15564. if ( material.isLineBasicMaterial ) {
  15565. refreshUniformsLine( m_uniforms, material );
  15566. } else if ( material.isLineDashedMaterial ) {
  15567. refreshUniformsLine( m_uniforms, material );
  15568. refreshUniformsDash( m_uniforms, material );
  15569. } else if ( material.isPointsMaterial ) {
  15570. refreshUniformsPoints( m_uniforms, material );
  15571. } else if ( material.isMeshLambertMaterial ) {
  15572. refreshUniformsLambert( m_uniforms, material );
  15573. } else if ( material.isMeshToonMaterial ) {
  15574. refreshUniformsToon( m_uniforms, material );
  15575. } else if ( material.isMeshPhongMaterial ) {
  15576. refreshUniformsPhong( m_uniforms, material );
  15577. } else if ( material.isMeshPhysicalMaterial ) {
  15578. refreshUniformsPhysical( m_uniforms, material );
  15579. } else if ( material.isMeshStandardMaterial ) {
  15580. refreshUniformsStandard( m_uniforms, material );
  15581. } else if ( material.isMeshDepthMaterial ) {
  15582. if ( material.displacementMap ) {
  15583. m_uniforms.displacementMap.value = material.displacementMap;
  15584. m_uniforms.displacementScale.value = material.displacementScale;
  15585. m_uniforms.displacementBias.value = material.displacementBias;
  15586. }
  15587. } else if ( material.isMeshNormalMaterial ) {
  15588. refreshUniformsNormal( m_uniforms, material );
  15589. }
  15590. // RectAreaLight Texture
  15591. // TODO (mrdoob): Find a nicer implementation
  15592. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = THREE.UniformsLib.LTC_MAT_TEXTURE;
  15593. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = THREE.UniformsLib.LTC_MAG_TEXTURE;
  15594. WebGLUniforms.upload(
  15595. _gl, materialProperties.uniformsList, m_uniforms, _this );
  15596. }
  15597. // common matrices
  15598. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  15599. p_uniforms.set( _gl, object, 'normalMatrix' );
  15600. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  15601. return program;
  15602. }
  15603. // Uniforms (refresh uniforms objects)
  15604. function refreshUniformsCommon( uniforms, material ) {
  15605. uniforms.opacity.value = material.opacity;
  15606. uniforms.diffuse.value = material.color;
  15607. if ( material.emissive ) {
  15608. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15609. }
  15610. uniforms.map.value = material.map;
  15611. uniforms.specularMap.value = material.specularMap;
  15612. uniforms.alphaMap.value = material.alphaMap;
  15613. if ( material.lightMap ) {
  15614. uniforms.lightMap.value = material.lightMap;
  15615. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15616. }
  15617. if ( material.aoMap ) {
  15618. uniforms.aoMap.value = material.aoMap;
  15619. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15620. }
  15621. // uv repeat and offset setting priorities
  15622. // 1. color map
  15623. // 2. specular map
  15624. // 3. normal map
  15625. // 4. bump map
  15626. // 5. alpha map
  15627. // 6. emissive map
  15628. var uvScaleMap;
  15629. if ( material.map ) {
  15630. uvScaleMap = material.map;
  15631. } else if ( material.specularMap ) {
  15632. uvScaleMap = material.specularMap;
  15633. } else if ( material.displacementMap ) {
  15634. uvScaleMap = material.displacementMap;
  15635. } else if ( material.normalMap ) {
  15636. uvScaleMap = material.normalMap;
  15637. } else if ( material.bumpMap ) {
  15638. uvScaleMap = material.bumpMap;
  15639. } else if ( material.roughnessMap ) {
  15640. uvScaleMap = material.roughnessMap;
  15641. } else if ( material.metalnessMap ) {
  15642. uvScaleMap = material.metalnessMap;
  15643. } else if ( material.alphaMap ) {
  15644. uvScaleMap = material.alphaMap;
  15645. } else if ( material.emissiveMap ) {
  15646. uvScaleMap = material.emissiveMap;
  15647. }
  15648. if ( uvScaleMap !== undefined ) {
  15649. // backwards compatibility
  15650. if ( uvScaleMap.isWebGLRenderTarget ) {
  15651. uvScaleMap = uvScaleMap.texture;
  15652. }
  15653. var offset = uvScaleMap.offset;
  15654. var repeat = uvScaleMap.repeat;
  15655. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15656. }
  15657. uniforms.envMap.value = material.envMap;
  15658. // don't flip CubeTexture envMaps, flip everything else:
  15659. // WebGLRenderTargetCube will be flipped for backwards compatibility
  15660. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  15661. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  15662. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  15663. uniforms.reflectivity.value = material.reflectivity;
  15664. uniforms.refractionRatio.value = material.refractionRatio;
  15665. }
  15666. function refreshUniformsLine( uniforms, material ) {
  15667. uniforms.diffuse.value = material.color;
  15668. uniforms.opacity.value = material.opacity;
  15669. }
  15670. function refreshUniformsDash( uniforms, material ) {
  15671. uniforms.dashSize.value = material.dashSize;
  15672. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15673. uniforms.scale.value = material.scale;
  15674. }
  15675. function refreshUniformsPoints( uniforms, material ) {
  15676. uniforms.diffuse.value = material.color;
  15677. uniforms.opacity.value = material.opacity;
  15678. uniforms.size.value = material.size * _pixelRatio;
  15679. uniforms.scale.value = _height * 0.5;
  15680. uniforms.map.value = material.map;
  15681. if ( material.map !== null ) {
  15682. var offset = material.map.offset;
  15683. var repeat = material.map.repeat;
  15684. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15685. }
  15686. }
  15687. function refreshUniformsFog( uniforms, fog ) {
  15688. uniforms.fogColor.value = fog.color;
  15689. if ( fog.isFog ) {
  15690. uniforms.fogNear.value = fog.near;
  15691. uniforms.fogFar.value = fog.far;
  15692. } else if ( fog.isFogExp2 ) {
  15693. uniforms.fogDensity.value = fog.density;
  15694. }
  15695. }
  15696. function refreshUniformsLambert( uniforms, material ) {
  15697. if ( material.emissiveMap ) {
  15698. uniforms.emissiveMap.value = material.emissiveMap;
  15699. }
  15700. }
  15701. function refreshUniformsPhong( uniforms, material ) {
  15702. uniforms.specular.value = material.specular;
  15703. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15704. if ( material.emissiveMap ) {
  15705. uniforms.emissiveMap.value = material.emissiveMap;
  15706. }
  15707. if ( material.bumpMap ) {
  15708. uniforms.bumpMap.value = material.bumpMap;
  15709. uniforms.bumpScale.value = material.bumpScale;
  15710. }
  15711. if ( material.normalMap ) {
  15712. uniforms.normalMap.value = material.normalMap;
  15713. uniforms.normalScale.value.copy( material.normalScale );
  15714. }
  15715. if ( material.displacementMap ) {
  15716. uniforms.displacementMap.value = material.displacementMap;
  15717. uniforms.displacementScale.value = material.displacementScale;
  15718. uniforms.displacementBias.value = material.displacementBias;
  15719. }
  15720. }
  15721. function refreshUniformsToon( uniforms, material ) {
  15722. refreshUniformsPhong( uniforms, material );
  15723. if ( material.gradientMap ) {
  15724. uniforms.gradientMap.value = material.gradientMap;
  15725. }
  15726. }
  15727. function refreshUniformsStandard( uniforms, material ) {
  15728. uniforms.roughness.value = material.roughness;
  15729. uniforms.metalness.value = material.metalness;
  15730. if ( material.roughnessMap ) {
  15731. uniforms.roughnessMap.value = material.roughnessMap;
  15732. }
  15733. if ( material.metalnessMap ) {
  15734. uniforms.metalnessMap.value = material.metalnessMap;
  15735. }
  15736. if ( material.emissiveMap ) {
  15737. uniforms.emissiveMap.value = material.emissiveMap;
  15738. }
  15739. if ( material.bumpMap ) {
  15740. uniforms.bumpMap.value = material.bumpMap;
  15741. uniforms.bumpScale.value = material.bumpScale;
  15742. }
  15743. if ( material.normalMap ) {
  15744. uniforms.normalMap.value = material.normalMap;
  15745. uniforms.normalScale.value.copy( material.normalScale );
  15746. }
  15747. if ( material.displacementMap ) {
  15748. uniforms.displacementMap.value = material.displacementMap;
  15749. uniforms.displacementScale.value = material.displacementScale;
  15750. uniforms.displacementBias.value = material.displacementBias;
  15751. }
  15752. if ( material.envMap ) {
  15753. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15754. uniforms.envMapIntensity.value = material.envMapIntensity;
  15755. }
  15756. }
  15757. function refreshUniformsPhysical( uniforms, material ) {
  15758. uniforms.clearCoat.value = material.clearCoat;
  15759. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  15760. refreshUniformsStandard( uniforms, material );
  15761. }
  15762. function refreshUniformsNormal( uniforms, material ) {
  15763. if ( material.bumpMap ) {
  15764. uniforms.bumpMap.value = material.bumpMap;
  15765. uniforms.bumpScale.value = material.bumpScale;
  15766. }
  15767. if ( material.normalMap ) {
  15768. uniforms.normalMap.value = material.normalMap;
  15769. uniforms.normalScale.value.copy( material.normalScale );
  15770. }
  15771. if ( material.displacementMap ) {
  15772. uniforms.displacementMap.value = material.displacementMap;
  15773. uniforms.displacementScale.value = material.displacementScale;
  15774. uniforms.displacementBias.value = material.displacementBias;
  15775. }
  15776. }
  15777. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15778. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  15779. uniforms.ambientLightColor.needsUpdate = value;
  15780. uniforms.directionalLights.needsUpdate = value;
  15781. uniforms.pointLights.needsUpdate = value;
  15782. uniforms.spotLights.needsUpdate = value;
  15783. uniforms.rectAreaLights.needsUpdate = value;
  15784. uniforms.hemisphereLights.needsUpdate = value;
  15785. }
  15786. // Lighting
  15787. function setupShadows( lights ) {
  15788. var lightShadowsLength = 0;
  15789. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  15790. var light = lights[ i ];
  15791. if ( light.castShadow ) {
  15792. _lights.shadows[ lightShadowsLength ++ ] = light;
  15793. }
  15794. }
  15795. _lights.shadows.length = lightShadowsLength;
  15796. }
  15797. function setupLights( lights, camera ) {
  15798. var l, ll, light,
  15799. r = 0, g = 0, b = 0,
  15800. color,
  15801. intensity,
  15802. distance,
  15803. shadowMap,
  15804. viewMatrix = camera.matrixWorldInverse,
  15805. directionalLength = 0,
  15806. pointLength = 0,
  15807. spotLength = 0,
  15808. rectAreaLength = 0,
  15809. hemiLength = 0;
  15810. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15811. light = lights[ l ];
  15812. color = light.color;
  15813. intensity = light.intensity;
  15814. distance = light.distance;
  15815. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  15816. if ( light.isAmbientLight ) {
  15817. r += color.r * intensity;
  15818. g += color.g * intensity;
  15819. b += color.b * intensity;
  15820. } else if ( light.isDirectionalLight ) {
  15821. var uniforms = lightCache.get( light );
  15822. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  15823. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  15824. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15825. uniforms.direction.sub( _vector3 );
  15826. uniforms.direction.transformDirection( viewMatrix );
  15827. uniforms.shadow = light.castShadow;
  15828. if ( light.castShadow ) {
  15829. uniforms.shadowBias = light.shadow.bias;
  15830. uniforms.shadowRadius = light.shadow.radius;
  15831. uniforms.shadowMapSize = light.shadow.mapSize;
  15832. }
  15833. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  15834. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  15835. _lights.directional[ directionalLength ++ ] = uniforms;
  15836. } else if ( light.isSpotLight ) {
  15837. var uniforms = lightCache.get( light );
  15838. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  15839. uniforms.position.applyMatrix4( viewMatrix );
  15840. uniforms.color.copy( color ).multiplyScalar( intensity );
  15841. uniforms.distance = distance;
  15842. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  15843. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15844. uniforms.direction.sub( _vector3 );
  15845. uniforms.direction.transformDirection( viewMatrix );
  15846. uniforms.coneCos = Math.cos( light.angle );
  15847. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  15848. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  15849. uniforms.shadow = light.castShadow;
  15850. if ( light.castShadow ) {
  15851. uniforms.shadowBias = light.shadow.bias;
  15852. uniforms.shadowRadius = light.shadow.radius;
  15853. uniforms.shadowMapSize = light.shadow.mapSize;
  15854. }
  15855. _lights.spotShadowMap[ spotLength ] = shadowMap;
  15856. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  15857. _lights.spot[ spotLength ++ ] = uniforms;
  15858. } else if ( light.isRectAreaLight ) {
  15859. var uniforms = lightCache.get( light );
  15860. // (a) intensity controls irradiance of entire light
  15861. uniforms.color
  15862. .copy( color )
  15863. .multiplyScalar( intensity / ( light.width * light.height ) );
  15864. // (b) intensity controls the radiance per light area
  15865. // uniforms.color.copy( color ).multiplyScalar( intensity );
  15866. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  15867. uniforms.position.applyMatrix4( viewMatrix );
  15868. // extract local rotation of light to derive width/height half vectors
  15869. _matrix42.identity();
  15870. _matrix4.copy( light.matrixWorld );
  15871. _matrix4.premultiply( viewMatrix );
  15872. _matrix42.extractRotation( _matrix4 );
  15873. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  15874. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  15875. uniforms.halfWidth.applyMatrix4( _matrix42 );
  15876. uniforms.halfHeight.applyMatrix4( _matrix42 );
  15877. // TODO (abelnation): RectAreaLight distance?
  15878. // uniforms.distance = distance;
  15879. _lights.rectArea[ rectAreaLength ++ ] = uniforms;
  15880. } else if ( light.isPointLight ) {
  15881. var uniforms = lightCache.get( light );
  15882. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  15883. uniforms.position.applyMatrix4( viewMatrix );
  15884. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  15885. uniforms.distance = light.distance;
  15886. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  15887. uniforms.shadow = light.castShadow;
  15888. if ( light.castShadow ) {
  15889. uniforms.shadowBias = light.shadow.bias;
  15890. uniforms.shadowRadius = light.shadow.radius;
  15891. uniforms.shadowMapSize = light.shadow.mapSize;
  15892. }
  15893. _lights.pointShadowMap[ pointLength ] = shadowMap;
  15894. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  15895. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  15896. }
  15897. // for point lights we set the shadow matrix to be a translation-only matrix
  15898. // equal to inverse of the light's position
  15899. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  15900. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  15901. _lights.point[ pointLength ++ ] = uniforms;
  15902. } else if ( light.isHemisphereLight ) {
  15903. var uniforms = lightCache.get( light );
  15904. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  15905. uniforms.direction.transformDirection( viewMatrix );
  15906. uniforms.direction.normalize();
  15907. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  15908. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  15909. _lights.hemi[ hemiLength ++ ] = uniforms;
  15910. }
  15911. }
  15912. _lights.ambient[ 0 ] = r;
  15913. _lights.ambient[ 1 ] = g;
  15914. _lights.ambient[ 2 ] = b;
  15915. _lights.directional.length = directionalLength;
  15916. _lights.spot.length = spotLength;
  15917. _lights.rectArea.length = rectAreaLength;
  15918. _lights.point.length = pointLength;
  15919. _lights.hemi.length = hemiLength;
  15920. // TODO (sam-g-steel) why aren't we using join
  15921. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  15922. }
  15923. // GL state setting
  15924. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  15925. state.setCullFace( cullFace );
  15926. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  15927. };
  15928. // Textures
  15929. function allocTextureUnit() {
  15930. var textureUnit = _usedTextureUnits;
  15931. if ( textureUnit >= capabilities.maxTextures ) {
  15932. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  15933. }
  15934. _usedTextureUnits += 1;
  15935. return textureUnit;
  15936. }
  15937. this.allocTextureUnit = allocTextureUnit;
  15938. // this.setTexture2D = setTexture2D;
  15939. this.setTexture2D = ( function() {
  15940. var warned = false;
  15941. // backwards compatibility: peel texture.texture
  15942. return function setTexture2D( texture, slot ) {
  15943. if ( texture && texture.isWebGLRenderTarget ) {
  15944. if ( ! warned ) {
  15945. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  15946. warned = true;
  15947. }
  15948. texture = texture.texture;
  15949. }
  15950. textures.setTexture2D( texture, slot );
  15951. };
  15952. }() );
  15953. this.setTexture = ( function() {
  15954. var warned = false;
  15955. return function setTexture( texture, slot ) {
  15956. if ( ! warned ) {
  15957. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  15958. warned = true;
  15959. }
  15960. textures.setTexture2D( texture, slot );
  15961. };
  15962. }() );
  15963. this.setTextureCube = ( function() {
  15964. var warned = false;
  15965. return function setTextureCube( texture, slot ) {
  15966. // backwards compatibility: peel texture.texture
  15967. if ( texture && texture.isWebGLRenderTargetCube ) {
  15968. if ( ! warned ) {
  15969. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  15970. warned = true;
  15971. }
  15972. texture = texture.texture;
  15973. }
  15974. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  15975. // TODO: unify these code paths
  15976. if ( ( texture && texture.isCubeTexture ) ||
  15977. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  15978. // CompressedTexture can have Array in image :/
  15979. // this function alone should take care of cube textures
  15980. textures.setTextureCube( texture, slot );
  15981. } else {
  15982. // assumed: texture property of THREE.WebGLRenderTargetCube
  15983. textures.setTextureCubeDynamic( texture, slot );
  15984. }
  15985. };
  15986. }() );
  15987. this.getCurrentRenderTarget = function() {
  15988. return _currentRenderTarget;
  15989. };
  15990. this.setRenderTarget = function ( renderTarget ) {
  15991. _currentRenderTarget = renderTarget;
  15992. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  15993. textures.setupRenderTarget( renderTarget );
  15994. }
  15995. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  15996. var framebuffer;
  15997. if ( renderTarget ) {
  15998. var renderTargetProperties = properties.get( renderTarget );
  15999. if ( isCube ) {
  16000. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  16001. } else {
  16002. framebuffer = renderTargetProperties.__webglFramebuffer;
  16003. }
  16004. _currentScissor.copy( renderTarget.scissor );
  16005. _currentScissorTest = renderTarget.scissorTest;
  16006. _currentViewport.copy( renderTarget.viewport );
  16007. } else {
  16008. framebuffer = null;
  16009. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  16010. _currentScissorTest = _scissorTest;
  16011. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  16012. }
  16013. if ( _currentFramebuffer !== framebuffer ) {
  16014. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16015. _currentFramebuffer = framebuffer;
  16016. }
  16017. state.scissor( _currentScissor );
  16018. state.setScissorTest( _currentScissorTest );
  16019. state.viewport( _currentViewport );
  16020. if ( isCube ) {
  16021. var textureProperties = properties.get( renderTarget.texture );
  16022. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  16023. }
  16024. };
  16025. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  16026. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  16027. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16028. return;
  16029. }
  16030. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16031. if ( framebuffer ) {
  16032. var restore = false;
  16033. if ( framebuffer !== _currentFramebuffer ) {
  16034. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16035. restore = true;
  16036. }
  16037. try {
  16038. var texture = renderTarget.texture;
  16039. var textureFormat = texture.format;
  16040. var textureType = texture.type;
  16041. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  16042. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16043. return;
  16044. }
  16045. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  16046. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  16047. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  16048. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16049. return;
  16050. }
  16051. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  16052. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16053. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  16054. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  16055. }
  16056. } else {
  16057. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  16058. }
  16059. } finally {
  16060. if ( restore ) {
  16061. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  16062. }
  16063. }
  16064. }
  16065. };
  16066. // Map three.js constants to WebGL constants
  16067. function paramThreeToGL( p ) {
  16068. var extension;
  16069. if ( p === RepeatWrapping ) return _gl.REPEAT;
  16070. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  16071. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  16072. if ( p === NearestFilter ) return _gl.NEAREST;
  16073. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  16074. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  16075. if ( p === LinearFilter ) return _gl.LINEAR;
  16076. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  16077. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  16078. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  16079. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  16080. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  16081. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  16082. if ( p === ByteType ) return _gl.BYTE;
  16083. if ( p === ShortType ) return _gl.SHORT;
  16084. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  16085. if ( p === IntType ) return _gl.INT;
  16086. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  16087. if ( p === FloatType ) return _gl.FLOAT;
  16088. if ( p === HalfFloatType ) {
  16089. extension = extensions.get( 'OES_texture_half_float' );
  16090. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  16091. }
  16092. if ( p === AlphaFormat ) return _gl.ALPHA;
  16093. if ( p === RGBFormat ) return _gl.RGB;
  16094. if ( p === RGBAFormat ) return _gl.RGBA;
  16095. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  16096. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  16097. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  16098. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  16099. if ( p === AddEquation ) return _gl.FUNC_ADD;
  16100. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  16101. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  16102. if ( p === ZeroFactor ) return _gl.ZERO;
  16103. if ( p === OneFactor ) return _gl.ONE;
  16104. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  16105. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  16106. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  16107. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  16108. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  16109. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  16110. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  16111. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  16112. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  16113. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  16114. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  16115. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  16116. if ( extension !== null ) {
  16117. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  16118. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  16119. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  16120. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  16121. }
  16122. }
  16123. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  16124. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  16125. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  16126. if ( extension !== null ) {
  16127. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  16128. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  16129. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  16130. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  16131. }
  16132. }
  16133. if ( p === RGB_ETC1_Format ) {
  16134. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  16135. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  16136. }
  16137. if ( p === MinEquation || p === MaxEquation ) {
  16138. extension = extensions.get( 'EXT_blend_minmax' );
  16139. if ( extension !== null ) {
  16140. if ( p === MinEquation ) return extension.MIN_EXT;
  16141. if ( p === MaxEquation ) return extension.MAX_EXT;
  16142. }
  16143. }
  16144. if ( p === UnsignedInt248Type ) {
  16145. extension = extensions.get( 'WEBGL_depth_texture' );
  16146. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  16147. }
  16148. return 0;
  16149. }
  16150. }
  16151. function LineCurve( v1, v2 ) {
  16152. this.v1 = v1;
  16153. this.v2 = v2;
  16154. }
  16155. LineCurve.prototype = Object.create( Curve.prototype );
  16156. LineCurve.prototype.constructor = LineCurve;
  16157. LineCurve.prototype.isLineCurve = true;
  16158. LineCurve.prototype.getPoint = function ( t ) {
  16159. if ( t === 1 ) {
  16160. return this.v2.clone();
  16161. }
  16162. var point = this.v2.clone().sub( this.v1 );
  16163. point.multiplyScalar( t ).add( this.v1 );
  16164. return point;
  16165. };
  16166. // Line curve is linear, so we can overwrite default getPointAt
  16167. LineCurve.prototype.getPointAt = function ( u ) {
  16168. return this.getPoint( u );
  16169. };
  16170. LineCurve.prototype.getTangent = function ( t ) {
  16171. var tangent = this.v2.clone().sub( this.v1 );
  16172. return tangent.normalize();
  16173. };
  16174. /**
  16175. * @author zz85 / http://www.lab4games.net/zz85/blog
  16176. *
  16177. **/
  16178. /**************************************************************
  16179. * Curved Path - a curve path is simply a array of connected
  16180. * curves, but retains the api of a curve
  16181. **************************************************************/
  16182. function CurvePath() {
  16183. this.curves = [];
  16184. this.autoClose = false; // Automatically closes the path
  16185. }
  16186. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  16187. constructor: CurvePath,
  16188. add: function ( curve ) {
  16189. this.curves.push( curve );
  16190. },
  16191. closePath: function () {
  16192. // Add a line curve if start and end of lines are not connected
  16193. var startPoint = this.curves[ 0 ].getPoint( 0 );
  16194. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  16195. if ( ! startPoint.equals( endPoint ) ) {
  16196. this.curves.push( new LineCurve( endPoint, startPoint ) );
  16197. }
  16198. },
  16199. // To get accurate point with reference to
  16200. // entire path distance at time t,
  16201. // following has to be done:
  16202. // 1. Length of each sub path have to be known
  16203. // 2. Locate and identify type of curve
  16204. // 3. Get t for the curve
  16205. // 4. Return curve.getPointAt(t')
  16206. getPoint: function ( t ) {
  16207. var d = t * this.getLength();
  16208. var curveLengths = this.getCurveLengths();
  16209. var i = 0;
  16210. // To think about boundaries points.
  16211. while ( i < curveLengths.length ) {
  16212. if ( curveLengths[ i ] >= d ) {
  16213. var diff = curveLengths[ i ] - d;
  16214. var curve = this.curves[ i ];
  16215. var segmentLength = curve.getLength();
  16216. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  16217. return curve.getPointAt( u );
  16218. }
  16219. i ++;
  16220. }
  16221. return null;
  16222. // loop where sum != 0, sum > d , sum+1 <d
  16223. },
  16224. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16225. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16226. // getPoint() depends on getLength
  16227. getLength: function () {
  16228. var lens = this.getCurveLengths();
  16229. return lens[ lens.length - 1 ];
  16230. },
  16231. // cacheLengths must be recalculated.
  16232. updateArcLengths: function () {
  16233. this.needsUpdate = true;
  16234. this.cacheLengths = null;
  16235. this.getLengths();
  16236. },
  16237. // Compute lengths and cache them
  16238. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16239. getCurveLengths: function () {
  16240. // We use cache values if curves and cache array are same length
  16241. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  16242. return this.cacheLengths;
  16243. }
  16244. // Get length of sub-curve
  16245. // Push sums into cached array
  16246. var lengths = [], sums = 0;
  16247. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  16248. sums += this.curves[ i ].getLength();
  16249. lengths.push( sums );
  16250. }
  16251. this.cacheLengths = lengths;
  16252. return lengths;
  16253. },
  16254. getSpacedPoints: function ( divisions ) {
  16255. if ( isNaN( divisions ) ) divisions = 40;
  16256. var points = [];
  16257. for ( var i = 0; i <= divisions; i ++ ) {
  16258. points.push( this.getPoint( i / divisions ) );
  16259. }
  16260. if ( this.autoClose ) {
  16261. points.push( points[ 0 ] );
  16262. }
  16263. return points;
  16264. },
  16265. getPoints: function ( divisions ) {
  16266. divisions = divisions || 12;
  16267. var points = [], last;
  16268. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  16269. var curve = curves[ i ];
  16270. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  16271. : (curve && curve.isLineCurve) ? 1
  16272. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  16273. : divisions;
  16274. var pts = curve.getPoints( resolution );
  16275. for ( var j = 0; j < pts.length; j++ ) {
  16276. var point = pts[ j ];
  16277. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  16278. points.push( point );
  16279. last = point;
  16280. }
  16281. }
  16282. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  16283. points.push( points[ 0 ] );
  16284. }
  16285. return points;
  16286. },
  16287. /**************************************************************
  16288. * Create Geometries Helpers
  16289. **************************************************************/
  16290. /// Generate geometry from path points (for Line or Points objects)
  16291. createPointsGeometry: function ( divisions ) {
  16292. var pts = this.getPoints( divisions );
  16293. return this.createGeometry( pts );
  16294. },
  16295. // Generate geometry from equidistant sampling along the path
  16296. createSpacedPointsGeometry: function ( divisions ) {
  16297. var pts = this.getSpacedPoints( divisions );
  16298. return this.createGeometry( pts );
  16299. },
  16300. createGeometry: function ( points ) {
  16301. var geometry = new Geometry();
  16302. for ( var i = 0, l = points.length; i < l; i ++ ) {
  16303. var point = points[ i ];
  16304. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  16305. }
  16306. return geometry;
  16307. }
  16308. } );
  16309. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  16310. this.aX = aX;
  16311. this.aY = aY;
  16312. this.xRadius = xRadius;
  16313. this.yRadius = yRadius;
  16314. this.aStartAngle = aStartAngle;
  16315. this.aEndAngle = aEndAngle;
  16316. this.aClockwise = aClockwise;
  16317. this.aRotation = aRotation || 0;
  16318. }
  16319. EllipseCurve.prototype = Object.create( Curve.prototype );
  16320. EllipseCurve.prototype.constructor = EllipseCurve;
  16321. EllipseCurve.prototype.isEllipseCurve = true;
  16322. EllipseCurve.prototype.getPoint = function ( t ) {
  16323. var twoPi = Math.PI * 2;
  16324. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16325. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  16326. // ensures that deltaAngle is 0 .. 2 PI
  16327. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  16328. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  16329. if ( deltaAngle < Number.EPSILON ) {
  16330. if ( samePoints ) {
  16331. deltaAngle = 0;
  16332. } else {
  16333. deltaAngle = twoPi;
  16334. }
  16335. }
  16336. if ( this.aClockwise === true && ! samePoints ) {
  16337. if ( deltaAngle === twoPi ) {
  16338. deltaAngle = - twoPi;
  16339. } else {
  16340. deltaAngle = deltaAngle - twoPi;
  16341. }
  16342. }
  16343. var angle = this.aStartAngle + t * deltaAngle;
  16344. var x = this.aX + this.xRadius * Math.cos( angle );
  16345. var y = this.aY + this.yRadius * Math.sin( angle );
  16346. if ( this.aRotation !== 0 ) {
  16347. var cos = Math.cos( this.aRotation );
  16348. var sin = Math.sin( this.aRotation );
  16349. var tx = x - this.aX;
  16350. var ty = y - this.aY;
  16351. // Rotate the point about the center of the ellipse.
  16352. x = tx * cos - ty * sin + this.aX;
  16353. y = tx * sin + ty * cos + this.aY;
  16354. }
  16355. return new Vector2( x, y );
  16356. };
  16357. /**
  16358. * @author zz85 / http://www.lab4games.net/zz85/blog
  16359. *
  16360. * Bezier Curves formulas obtained from
  16361. * http://en.wikipedia.org/wiki/Bézier_curve
  16362. */
  16363. function CatmullRom( t, p0, p1, p2, p3 ) {
  16364. var v0 = ( p2 - p0 ) * 0.5;
  16365. var v1 = ( p3 - p1 ) * 0.5;
  16366. var t2 = t * t;
  16367. var t3 = t * t2;
  16368. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16369. }
  16370. //
  16371. function QuadraticBezierP0( t, p ) {
  16372. var k = 1 - t;
  16373. return k * k * p;
  16374. }
  16375. function QuadraticBezierP1( t, p ) {
  16376. return 2 * ( 1 - t ) * t * p;
  16377. }
  16378. function QuadraticBezierP2( t, p ) {
  16379. return t * t * p;
  16380. }
  16381. function QuadraticBezier( t, p0, p1, p2 ) {
  16382. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  16383. QuadraticBezierP2( t, p2 );
  16384. }
  16385. //
  16386. function CubicBezierP0( t, p ) {
  16387. var k = 1 - t;
  16388. return k * k * k * p;
  16389. }
  16390. function CubicBezierP1( t, p ) {
  16391. var k = 1 - t;
  16392. return 3 * k * k * t * p;
  16393. }
  16394. function CubicBezierP2( t, p ) {
  16395. return 3 * ( 1 - t ) * t * t * p;
  16396. }
  16397. function CubicBezierP3( t, p ) {
  16398. return t * t * t * p;
  16399. }
  16400. function CubicBezier( t, p0, p1, p2, p3 ) {
  16401. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  16402. CubicBezierP3( t, p3 );
  16403. }
  16404. function SplineCurve( points /* array of Vector2 */ ) {
  16405. this.points = ( points === undefined ) ? [] : points;
  16406. }
  16407. SplineCurve.prototype = Object.create( Curve.prototype );
  16408. SplineCurve.prototype.constructor = SplineCurve;
  16409. SplineCurve.prototype.isSplineCurve = true;
  16410. SplineCurve.prototype.getPoint = function ( t ) {
  16411. var points = this.points;
  16412. var point = ( points.length - 1 ) * t;
  16413. var intPoint = Math.floor( point );
  16414. var weight = point - intPoint;
  16415. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  16416. var point1 = points[ intPoint ];
  16417. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  16418. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  16419. return new Vector2(
  16420. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  16421. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  16422. );
  16423. };
  16424. function CubicBezierCurve( v0, v1, v2, v3 ) {
  16425. this.v0 = v0;
  16426. this.v1 = v1;
  16427. this.v2 = v2;
  16428. this.v3 = v3;
  16429. }
  16430. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  16431. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  16432. CubicBezierCurve.prototype.getPoint = function ( t ) {
  16433. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  16434. return new Vector2(
  16435. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  16436. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  16437. );
  16438. };
  16439. function QuadraticBezierCurve( v0, v1, v2 ) {
  16440. this.v0 = v0;
  16441. this.v1 = v1;
  16442. this.v2 = v2;
  16443. }
  16444. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  16445. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  16446. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16447. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  16448. return new Vector2(
  16449. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  16450. QuadraticBezier( t, v0.y, v1.y, v2.y )
  16451. );
  16452. };
  16453. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  16454. fromPoints: function ( vectors ) {
  16455. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16456. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  16457. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  16458. }
  16459. },
  16460. moveTo: function ( x, y ) {
  16461. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  16462. },
  16463. lineTo: function ( x, y ) {
  16464. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  16465. this.curves.push( curve );
  16466. this.currentPoint.set( x, y );
  16467. },
  16468. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  16469. var curve = new QuadraticBezierCurve(
  16470. this.currentPoint.clone(),
  16471. new Vector2( aCPx, aCPy ),
  16472. new Vector2( aX, aY )
  16473. );
  16474. this.curves.push( curve );
  16475. this.currentPoint.set( aX, aY );
  16476. },
  16477. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  16478. var curve = new CubicBezierCurve(
  16479. this.currentPoint.clone(),
  16480. new Vector2( aCP1x, aCP1y ),
  16481. new Vector2( aCP2x, aCP2y ),
  16482. new Vector2( aX, aY )
  16483. );
  16484. this.curves.push( curve );
  16485. this.currentPoint.set( aX, aY );
  16486. },
  16487. splineThru: function ( pts /*Array of Vector*/ ) {
  16488. var npts = [ this.currentPoint.clone() ].concat( pts );
  16489. var curve = new SplineCurve( npts );
  16490. this.curves.push( curve );
  16491. this.currentPoint.copy( pts[ pts.length - 1 ] );
  16492. },
  16493. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16494. var x0 = this.currentPoint.x;
  16495. var y0 = this.currentPoint.y;
  16496. this.absarc( aX + x0, aY + y0, aRadius,
  16497. aStartAngle, aEndAngle, aClockwise );
  16498. },
  16499. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16500. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16501. },
  16502. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  16503. var x0 = this.currentPoint.x;
  16504. var y0 = this.currentPoint.y;
  16505. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  16506. },
  16507. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  16508. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  16509. if ( this.curves.length > 0 ) {
  16510. // if a previous curve is present, attempt to join
  16511. var firstPoint = curve.getPoint( 0 );
  16512. if ( ! firstPoint.equals( this.currentPoint ) ) {
  16513. this.lineTo( firstPoint.x, firstPoint.y );
  16514. }
  16515. }
  16516. this.curves.push( curve );
  16517. var lastPoint = curve.getPoint( 1 );
  16518. this.currentPoint.copy( lastPoint );
  16519. }
  16520. } );
  16521. /**
  16522. * @author zz85 / http://www.lab4games.net/zz85/blog
  16523. * Creates free form 2d path using series of points, lines or curves.
  16524. **/
  16525. function Path( points ) {
  16526. CurvePath.call( this );
  16527. this.currentPoint = new Vector2();
  16528. if ( points ) {
  16529. this.fromPoints( points );
  16530. }
  16531. }
  16532. Path.prototype = PathPrototype;
  16533. PathPrototype.constructor = Path;
  16534. /**
  16535. * @author zz85 / http://www.lab4games.net/zz85/blog
  16536. * Defines a 2d shape plane using paths.
  16537. **/
  16538. // STEP 1 Create a path.
  16539. // STEP 2 Turn path into shape.
  16540. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16541. // STEP 3a - Extract points from each shape, turn to vertices
  16542. // STEP 3b - Triangulate each shape, add faces.
  16543. function Shape() {
  16544. Path.apply( this, arguments );
  16545. this.holes = [];
  16546. }
  16547. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  16548. constructor: Shape,
  16549. getPointsHoles: function ( divisions ) {
  16550. var holesPts = [];
  16551. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  16552. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  16553. }
  16554. return holesPts;
  16555. },
  16556. // Get points of shape and holes (keypoints based on segments parameter)
  16557. extractAllPoints: function ( divisions ) {
  16558. return {
  16559. shape: this.getPoints( divisions ),
  16560. holes: this.getPointsHoles( divisions )
  16561. };
  16562. },
  16563. extractPoints: function ( divisions ) {
  16564. return this.extractAllPoints( divisions );
  16565. }
  16566. } );
  16567. /**
  16568. * @author mrdoob / http://mrdoob.com/
  16569. */
  16570. function Face4( a, b, c, d, normal, color, materialIndex ) {
  16571. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  16572. return new Face3( a, b, c, normal, color, materialIndex );
  16573. }
  16574. var LineStrip = 0;
  16575. var LinePieces = 1;
  16576. function MeshFaceMaterial( materials ) {
  16577. console.warn( 'THREE.MeshFaceMaterial has been renamed to THREE.MultiMaterial.' );
  16578. return new MultiMaterial( materials );
  16579. }
  16580. function PointCloud( geometry, material ) {
  16581. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  16582. return new Points( geometry, material );
  16583. }
  16584. function Particle( material ) {
  16585. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  16586. return new Sprite( material );
  16587. }
  16588. function ParticleSystem( geometry, material ) {
  16589. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  16590. return new Points( geometry, material );
  16591. }
  16592. function PointCloudMaterial( parameters ) {
  16593. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  16594. return new PointsMaterial( parameters );
  16595. }
  16596. function ParticleBasicMaterial( parameters ) {
  16597. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  16598. return new PointsMaterial( parameters );
  16599. }
  16600. function ParticleSystemMaterial( parameters ) {
  16601. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  16602. return new PointsMaterial( parameters );
  16603. }
  16604. function Vertex( x, y, z ) {
  16605. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  16606. return new Vector3( x, y, z );
  16607. }
  16608. //
  16609. function DynamicBufferAttribute( array, itemSize ) {
  16610. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  16611. return new BufferAttribute( array, itemSize ).setDynamic( true );
  16612. }
  16613. function Int8Attribute( array, itemSize ) {
  16614. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  16615. return new Int8BufferAttribute( array, itemSize );
  16616. }
  16617. function Uint8Attribute( array, itemSize ) {
  16618. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  16619. return new Uint8BufferAttribute( array, itemSize );
  16620. }
  16621. function Uint8ClampedAttribute( array, itemSize ) {
  16622. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  16623. return new Uint8ClampedBufferAttribute( array, itemSize );
  16624. }
  16625. function Int16Attribute( array, itemSize ) {
  16626. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  16627. return new Int16BufferAttribute( array, itemSize );
  16628. }
  16629. function Uint16Attribute( array, itemSize ) {
  16630. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  16631. return new Uint16BufferAttribute( array, itemSize );
  16632. }
  16633. function Int32Attribute( array, itemSize ) {
  16634. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  16635. return new Int32BufferAttribute( array, itemSize );
  16636. }
  16637. function Uint32Attribute( array, itemSize ) {
  16638. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  16639. return new Uint32BufferAttribute( array, itemSize );
  16640. }
  16641. function Float32Attribute( array, itemSize ) {
  16642. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  16643. return new Float32BufferAttribute( array, itemSize );
  16644. }
  16645. function Float64Attribute( array, itemSize ) {
  16646. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  16647. return new Float64BufferAttribute( array, itemSize );
  16648. }
  16649. //
  16650. Curve.create = function ( construct, getPoint ) {
  16651. console.log( 'THREE.Curve.create() has been deprecated' );
  16652. construct.prototype = Object.create( Curve.prototype );
  16653. construct.prototype.constructor = construct;
  16654. construct.prototype.getPoint = getPoint;
  16655. return construct;
  16656. };
  16657. //
  16658. function ClosedSplineCurve3( points ) {
  16659. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  16660. CatmullRomCurve3.call( this, points );
  16661. this.type = 'catmullrom';
  16662. this.closed = true;
  16663. }
  16664. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  16665. //
  16666. function SplineCurve3( points ) {
  16667. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  16668. CatmullRomCurve3.call( this, points );
  16669. this.type = 'catmullrom';
  16670. }
  16671. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  16672. //
  16673. function Spline( points ) {
  16674. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  16675. CatmullRomCurve3.call( this, points );
  16676. this.type = 'catmullrom';
  16677. }
  16678. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  16679. Object.assign( Spline.prototype, {
  16680. initFromArray: function ( a ) {
  16681. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  16682. },
  16683. getControlPointsArray: function ( optionalTarget ) {
  16684. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  16685. },
  16686. reparametrizeByArcLength: function ( samplingCoef ) {
  16687. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  16688. }
  16689. } );
  16690. //
  16691. function BoundingBoxHelper( object, color ) {
  16692. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  16693. return new BoxHelper( object, color );
  16694. }
  16695. function EdgesHelper( object, hex ) {
  16696. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  16697. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  16698. }
  16699. GridHelper.prototype.setColors = function () {
  16700. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  16701. };
  16702. function WireframeHelper( object, hex ) {
  16703. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  16704. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  16705. }
  16706. //
  16707. function XHRLoader( manager ) {
  16708. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  16709. return new FileLoader( manager );
  16710. }
  16711. function BinaryTextureLoader( manager ) {
  16712. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  16713. return new DataTextureLoader( manager );
  16714. }
  16715. //
  16716. Object.assign( Box2.prototype, {
  16717. center: function ( optionalTarget ) {
  16718. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  16719. return this.getCenter( optionalTarget );
  16720. },
  16721. empty: function () {
  16722. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  16723. return this.isEmpty();
  16724. },
  16725. isIntersectionBox: function ( box ) {
  16726. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  16727. return this.intersectsBox( box );
  16728. },
  16729. size: function ( optionalTarget ) {
  16730. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  16731. return this.getSize( optionalTarget );
  16732. }
  16733. } );
  16734. Object.assign( Box3.prototype, {
  16735. center: function ( optionalTarget ) {
  16736. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  16737. return this.getCenter( optionalTarget );
  16738. },
  16739. empty: function () {
  16740. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  16741. return this.isEmpty();
  16742. },
  16743. isIntersectionBox: function ( box ) {
  16744. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  16745. return this.intersectsBox( box );
  16746. },
  16747. isIntersectionSphere: function ( sphere ) {
  16748. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  16749. return this.intersectsSphere( sphere );
  16750. },
  16751. size: function ( optionalTarget ) {
  16752. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  16753. return this.getSize( optionalTarget );
  16754. }
  16755. } );
  16756. Line3.prototype.center = function ( optionalTarget ) {
  16757. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  16758. return this.getCenter( optionalTarget );
  16759. };
  16760. _Math.random16 = function () {
  16761. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  16762. return Math.random();
  16763. };
  16764. Object.assign( Matrix3.prototype, {
  16765. flattenToArrayOffset: function ( array, offset ) {
  16766. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  16767. return this.toArray( array, offset );
  16768. },
  16769. multiplyVector3: function ( vector ) {
  16770. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  16771. return vector.applyMatrix3( this );
  16772. },
  16773. multiplyVector3Array: function ( a ) {
  16774. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  16775. return this.applyToVector3Array( a );
  16776. },
  16777. applyToBuffer: function( buffer, offset, length ) {
  16778. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  16779. return this.applyToBufferAttribute( buffer );
  16780. },
  16781. applyToVector3Array: function( array, offset, length ) {
  16782. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  16783. }
  16784. } );
  16785. Object.assign( Matrix4.prototype, {
  16786. extractPosition: function ( m ) {
  16787. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  16788. return this.copyPosition( m );
  16789. },
  16790. flattenToArrayOffset: function ( array, offset ) {
  16791. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  16792. return this.toArray( array, offset );
  16793. },
  16794. getPosition: function () {
  16795. var v1;
  16796. return function getPosition() {
  16797. if ( v1 === undefined ) v1 = new Vector3();
  16798. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  16799. return v1.setFromMatrixColumn( this, 3 );
  16800. };
  16801. }(),
  16802. setRotationFromQuaternion: function ( q ) {
  16803. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  16804. return this.makeRotationFromQuaternion( q );
  16805. },
  16806. multiplyVector3: function ( vector ) {
  16807. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  16808. return vector.applyMatrix4( this );
  16809. },
  16810. multiplyVector4: function ( vector ) {
  16811. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  16812. return vector.applyMatrix4( this );
  16813. },
  16814. multiplyVector3Array: function ( a ) {
  16815. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  16816. return this.applyToVector3Array( a );
  16817. },
  16818. rotateAxis: function ( v ) {
  16819. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  16820. v.transformDirection( this );
  16821. },
  16822. crossVector: function ( vector ) {
  16823. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  16824. return vector.applyMatrix4( this );
  16825. },
  16826. translate: function () {
  16827. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  16828. },
  16829. rotateX: function () {
  16830. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  16831. },
  16832. rotateY: function () {
  16833. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  16834. },
  16835. rotateZ: function () {
  16836. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  16837. },
  16838. rotateByAxis: function () {
  16839. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  16840. },
  16841. applyToBuffer: function( buffer, offset, length ) {
  16842. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  16843. return this.applyToBufferAttribute( buffer );
  16844. },
  16845. applyToVector3Array: function( array, offset, length ) {
  16846. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  16847. },
  16848. makeFrustum: function( left, right, bottom, top, near, far ) {
  16849. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  16850. return this.makePerspective( left, right, top, bottom, near, far );
  16851. }
  16852. } );
  16853. Plane.prototype.isIntersectionLine = function ( line ) {
  16854. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  16855. return this.intersectsLine( line );
  16856. };
  16857. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  16858. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  16859. return vector.applyQuaternion( this );
  16860. };
  16861. Object.assign( Ray.prototype, {
  16862. isIntersectionBox: function ( box ) {
  16863. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  16864. return this.intersectsBox( box );
  16865. },
  16866. isIntersectionPlane: function ( plane ) {
  16867. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  16868. return this.intersectsPlane( plane );
  16869. },
  16870. isIntersectionSphere: function ( sphere ) {
  16871. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  16872. return this.intersectsSphere( sphere );
  16873. }
  16874. } );
  16875. Object.assign( Shape.prototype, {
  16876. extrude: function ( options ) {
  16877. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  16878. return new ExtrudeGeometry( this, options );
  16879. },
  16880. makeGeometry: function ( options ) {
  16881. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  16882. return new ShapeGeometry( this, options );
  16883. }
  16884. } );
  16885. Object.assign( Vector2.prototype, {
  16886. fromAttribute: function ( attribute, index, offset ) {
  16887. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  16888. return this.fromBufferAttribute( attribute, index, offset );
  16889. }
  16890. } );
  16891. Object.assign( Vector3.prototype, {
  16892. setEulerFromRotationMatrix: function () {
  16893. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  16894. },
  16895. setEulerFromQuaternion: function () {
  16896. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  16897. },
  16898. getPositionFromMatrix: function ( m ) {
  16899. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  16900. return this.setFromMatrixPosition( m );
  16901. },
  16902. getScaleFromMatrix: function ( m ) {
  16903. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  16904. return this.setFromMatrixScale( m );
  16905. },
  16906. getColumnFromMatrix: function ( index, matrix ) {
  16907. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  16908. return this.setFromMatrixColumn( matrix, index );
  16909. },
  16910. applyProjection: function ( m ) {
  16911. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  16912. return this.applyMatrix4( m );
  16913. },
  16914. fromAttribute: function ( attribute, index, offset ) {
  16915. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  16916. return this.fromBufferAttribute( attribute, index, offset );
  16917. }
  16918. } );
  16919. Object.assign( Vector4.prototype, {
  16920. fromAttribute: function ( attribute, index, offset ) {
  16921. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  16922. return this.fromBufferAttribute( attribute, index, offset );
  16923. }
  16924. } );
  16925. //
  16926. Geometry.prototype.computeTangents = function () {
  16927. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  16928. };
  16929. Object.assign( Object3D.prototype, {
  16930. getChildByName: function ( name ) {
  16931. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  16932. return this.getObjectByName( name );
  16933. },
  16934. renderDepth: function () {
  16935. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  16936. },
  16937. translate: function ( distance, axis ) {
  16938. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  16939. return this.translateOnAxis( axis, distance );
  16940. }
  16941. } );
  16942. Object.defineProperties( Object3D.prototype, {
  16943. eulerOrder: {
  16944. get: function () {
  16945. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  16946. return this.rotation.order;
  16947. },
  16948. set: function ( value ) {
  16949. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  16950. this.rotation.order = value;
  16951. }
  16952. },
  16953. useQuaternion: {
  16954. get: function () {
  16955. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  16956. },
  16957. set: function () {
  16958. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  16959. }
  16960. }
  16961. } );
  16962. Object.defineProperties( LOD.prototype, {
  16963. objects: {
  16964. get: function () {
  16965. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  16966. return this.levels;
  16967. }
  16968. }
  16969. } );
  16970. //
  16971. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  16972. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  16973. "Use .setFocalLength and .filmGauge for a photographic setup." );
  16974. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  16975. this.setFocalLength( focalLength );
  16976. };
  16977. //
  16978. Object.defineProperties( Light.prototype, {
  16979. onlyShadow: {
  16980. set: function () {
  16981. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  16982. }
  16983. },
  16984. shadowCameraFov: {
  16985. set: function ( value ) {
  16986. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  16987. this.shadow.camera.fov = value;
  16988. }
  16989. },
  16990. shadowCameraLeft: {
  16991. set: function ( value ) {
  16992. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  16993. this.shadow.camera.left = value;
  16994. }
  16995. },
  16996. shadowCameraRight: {
  16997. set: function ( value ) {
  16998. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  16999. this.shadow.camera.right = value;
  17000. }
  17001. },
  17002. shadowCameraTop: {
  17003. set: function ( value ) {
  17004. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  17005. this.shadow.camera.top = value;
  17006. }
  17007. },
  17008. shadowCameraBottom: {
  17009. set: function ( value ) {
  17010. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  17011. this.shadow.camera.bottom = value;
  17012. }
  17013. },
  17014. shadowCameraNear: {
  17015. set: function ( value ) {
  17016. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  17017. this.shadow.camera.near = value;
  17018. }
  17019. },
  17020. shadowCameraFar: {
  17021. set: function ( value ) {
  17022. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  17023. this.shadow.camera.far = value;
  17024. }
  17025. },
  17026. shadowCameraVisible: {
  17027. set: function () {
  17028. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  17029. }
  17030. },
  17031. shadowBias: {
  17032. set: function ( value ) {
  17033. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  17034. this.shadow.bias = value;
  17035. }
  17036. },
  17037. shadowDarkness: {
  17038. set: function () {
  17039. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  17040. }
  17041. },
  17042. shadowMapWidth: {
  17043. set: function ( value ) {
  17044. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  17045. this.shadow.mapSize.width = value;
  17046. }
  17047. },
  17048. shadowMapHeight: {
  17049. set: function ( value ) {
  17050. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  17051. this.shadow.mapSize.height = value;
  17052. }
  17053. }
  17054. } );
  17055. //
  17056. Object.defineProperties( BufferAttribute.prototype, {
  17057. length: {
  17058. get: function () {
  17059. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  17060. return this.array.length;
  17061. }
  17062. }
  17063. } );
  17064. Object.assign( BufferGeometry.prototype, {
  17065. addIndex: function ( index ) {
  17066. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  17067. this.setIndex( index );
  17068. },
  17069. addDrawCall: function ( start, count, indexOffset ) {
  17070. if ( indexOffset !== undefined ) {
  17071. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  17072. }
  17073. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  17074. this.addGroup( start, count );
  17075. },
  17076. clearDrawCalls: function () {
  17077. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  17078. this.clearGroups();
  17079. },
  17080. computeTangents: function () {
  17081. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  17082. },
  17083. computeOffsets: function () {
  17084. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  17085. }
  17086. } );
  17087. Object.defineProperties( BufferGeometry.prototype, {
  17088. drawcalls: {
  17089. get: function () {
  17090. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  17091. return this.groups;
  17092. }
  17093. },
  17094. offsets: {
  17095. get: function () {
  17096. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  17097. return this.groups;
  17098. }
  17099. }
  17100. } );
  17101. //
  17102. Object.defineProperties( Uniform.prototype, {
  17103. dynamic: {
  17104. set: function () {
  17105. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  17106. }
  17107. },
  17108. onUpdate: {
  17109. value: function () {
  17110. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  17111. return this;
  17112. }
  17113. }
  17114. } );
  17115. //
  17116. Object.defineProperties( Material.prototype, {
  17117. wrapAround: {
  17118. get: function () {
  17119. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  17120. },
  17121. set: function () {
  17122. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  17123. }
  17124. },
  17125. wrapRGB: {
  17126. get: function () {
  17127. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  17128. return new Color();
  17129. }
  17130. }
  17131. } );
  17132. Object.defineProperties( MeshPhongMaterial.prototype, {
  17133. metal: {
  17134. get: function () {
  17135. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  17136. return false;
  17137. },
  17138. set: function () {
  17139. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  17140. }
  17141. }
  17142. } );
  17143. Object.defineProperties( ShaderMaterial.prototype, {
  17144. derivatives: {
  17145. get: function () {
  17146. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  17147. return this.extensions.derivatives;
  17148. },
  17149. set: function ( value ) {
  17150. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  17151. this.extensions.derivatives = value;
  17152. }
  17153. }
  17154. } );
  17155. //
  17156. Object.assign( WebGLRenderer.prototype, {
  17157. supportsFloatTextures: function () {
  17158. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  17159. return this.extensions.get( 'OES_texture_float' );
  17160. },
  17161. supportsHalfFloatTextures: function () {
  17162. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  17163. return this.extensions.get( 'OES_texture_half_float' );
  17164. },
  17165. supportsStandardDerivatives: function () {
  17166. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  17167. return this.extensions.get( 'OES_standard_derivatives' );
  17168. },
  17169. supportsCompressedTextureS3TC: function () {
  17170. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  17171. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  17172. },
  17173. supportsCompressedTexturePVRTC: function () {
  17174. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  17175. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  17176. },
  17177. supportsBlendMinMax: function () {
  17178. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  17179. return this.extensions.get( 'EXT_blend_minmax' );
  17180. },
  17181. supportsVertexTextures: function () {
  17182. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  17183. return this.capabilities.vertexTextures;
  17184. },
  17185. supportsInstancedArrays: function () {
  17186. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  17187. return this.extensions.get( 'ANGLE_instanced_arrays' );
  17188. },
  17189. enableScissorTest: function ( boolean ) {
  17190. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  17191. this.setScissorTest( boolean );
  17192. },
  17193. initMaterial: function () {
  17194. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  17195. },
  17196. addPrePlugin: function () {
  17197. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  17198. },
  17199. addPostPlugin: function () {
  17200. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  17201. },
  17202. updateShadowMap: function () {
  17203. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  17204. }
  17205. } );
  17206. Object.defineProperties( WebGLRenderer.prototype, {
  17207. shadowMapEnabled: {
  17208. get: function () {
  17209. return this.shadowMap.enabled;
  17210. },
  17211. set: function ( value ) {
  17212. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  17213. this.shadowMap.enabled = value;
  17214. }
  17215. },
  17216. shadowMapType: {
  17217. get: function () {
  17218. return this.shadowMap.type;
  17219. },
  17220. set: function ( value ) {
  17221. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  17222. this.shadowMap.type = value;
  17223. }
  17224. },
  17225. shadowMapCullFace: {
  17226. get: function () {
  17227. return this.shadowMap.cullFace;
  17228. },
  17229. set: function ( value ) {
  17230. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  17231. this.shadowMap.cullFace = value;
  17232. }
  17233. }
  17234. } );
  17235. Object.defineProperties( WebGLShadowMap.prototype, {
  17236. cullFace: {
  17237. get: function () {
  17238. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  17239. },
  17240. set: function ( cullFace ) {
  17241. var value = ( cullFace !== CullFaceBack );
  17242. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  17243. this.renderReverseSided = value;
  17244. }
  17245. }
  17246. } );
  17247. //
  17248. Object.defineProperties( WebGLRenderTarget.prototype, {
  17249. wrapS: {
  17250. get: function () {
  17251. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  17252. return this.texture.wrapS;
  17253. },
  17254. set: function ( value ) {
  17255. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  17256. this.texture.wrapS = value;
  17257. }
  17258. },
  17259. wrapT: {
  17260. get: function () {
  17261. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  17262. return this.texture.wrapT;
  17263. },
  17264. set: function ( value ) {
  17265. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  17266. this.texture.wrapT = value;
  17267. }
  17268. },
  17269. magFilter: {
  17270. get: function () {
  17271. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  17272. return this.texture.magFilter;
  17273. },
  17274. set: function ( value ) {
  17275. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  17276. this.texture.magFilter = value;
  17277. }
  17278. },
  17279. minFilter: {
  17280. get: function () {
  17281. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  17282. return this.texture.minFilter;
  17283. },
  17284. set: function ( value ) {
  17285. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  17286. this.texture.minFilter = value;
  17287. }
  17288. },
  17289. anisotropy: {
  17290. get: function () {
  17291. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  17292. return this.texture.anisotropy;
  17293. },
  17294. set: function ( value ) {
  17295. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  17296. this.texture.anisotropy = value;
  17297. }
  17298. },
  17299. offset: {
  17300. get: function () {
  17301. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  17302. return this.texture.offset;
  17303. },
  17304. set: function ( value ) {
  17305. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  17306. this.texture.offset = value;
  17307. }
  17308. },
  17309. repeat: {
  17310. get: function () {
  17311. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  17312. return this.texture.repeat;
  17313. },
  17314. set: function ( value ) {
  17315. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  17316. this.texture.repeat = value;
  17317. }
  17318. },
  17319. format: {
  17320. get: function () {
  17321. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  17322. return this.texture.format;
  17323. },
  17324. set: function ( value ) {
  17325. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  17326. this.texture.format = value;
  17327. }
  17328. },
  17329. type: {
  17330. get: function () {
  17331. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  17332. return this.texture.type;
  17333. },
  17334. set: function ( value ) {
  17335. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  17336. this.texture.type = value;
  17337. }
  17338. },
  17339. generateMipmaps: {
  17340. get: function () {
  17341. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  17342. return this.texture.generateMipmaps;
  17343. },
  17344. set: function ( value ) {
  17345. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  17346. this.texture.generateMipmaps = value;
  17347. }
  17348. }
  17349. } );
  17350. //
  17351. Audio.prototype.load = function ( file ) {
  17352. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  17353. var scope = this;
  17354. var audioLoader = new AudioLoader();
  17355. audioLoader.load( file, function ( buffer ) {
  17356. scope.setBuffer( buffer );
  17357. } );
  17358. return this;
  17359. };
  17360. AudioAnalyser.prototype.getData = function () {
  17361. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  17362. return this.getFrequencyData();
  17363. };
  17364. //
  17365. var GeometryUtils = {
  17366. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  17367. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  17368. var matrix;
  17369. if ( geometry2.isMesh ) {
  17370. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  17371. matrix = geometry2.matrix;
  17372. geometry2 = geometry2.geometry;
  17373. }
  17374. geometry1.merge( geometry2, matrix, materialIndexOffset );
  17375. },
  17376. center: function ( geometry ) {
  17377. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  17378. return geometry.center();
  17379. }
  17380. };
  17381. var ImageUtils = {
  17382. crossOrigin: undefined,
  17383. loadTexture: function ( url, mapping, onLoad, onError ) {
  17384. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  17385. var loader = new TextureLoader();
  17386. loader.setCrossOrigin( this.crossOrigin );
  17387. var texture = loader.load( url, onLoad, undefined, onError );
  17388. if ( mapping ) texture.mapping = mapping;
  17389. return texture;
  17390. },
  17391. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  17392. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  17393. var loader = new CubeTextureLoader();
  17394. loader.setCrossOrigin( this.crossOrigin );
  17395. var texture = loader.load( urls, onLoad, undefined, onError );
  17396. if ( mapping ) texture.mapping = mapping;
  17397. return texture;
  17398. },
  17399. loadCompressedTexture: function () {
  17400. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  17401. },
  17402. loadCompressedTextureCube: function () {
  17403. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  17404. }
  17405. };
  17406. //
  17407. function Projector() {
  17408. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  17409. this.projectVector = function ( vector, camera ) {
  17410. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  17411. vector.project( camera );
  17412. };
  17413. this.unprojectVector = function ( vector, camera ) {
  17414. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  17415. vector.unproject( camera );
  17416. };
  17417. this.pickingRay = function () {
  17418. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  17419. };
  17420. }
  17421. //
  17422. function CanvasRenderer() {
  17423. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  17424. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  17425. this.clear = function () {};
  17426. this.render = function () {};
  17427. this.setClearColor = function () {};
  17428. this.setSize = function () {};
  17429. }
  17430. /**
  17431. *
  17432. * Action provided by AnimationMixer for scheduling clip playback on specific
  17433. * objects.
  17434. *
  17435. * @author Ben Houston / http://clara.io/
  17436. * @author David Sarno / http://lighthaus.us/
  17437. * @author tschw
  17438. *
  17439. */
  17440. function AnimationAction( mixer, clip, localRoot ) {
  17441. this._mixer = mixer;
  17442. this._clip = clip;
  17443. this._localRoot = localRoot || null;
  17444. var tracks = clip.tracks,
  17445. nTracks = tracks.length,
  17446. interpolants = new Array( nTracks );
  17447. var interpolantSettings = {
  17448. endingStart: ZeroCurvatureEnding,
  17449. endingEnd: ZeroCurvatureEnding
  17450. };
  17451. for ( var i = 0; i !== nTracks; ++ i ) {
  17452. var interpolant = tracks[ i ].createInterpolant( null );
  17453. interpolants[ i ] = interpolant;
  17454. interpolant.settings = interpolantSettings;
  17455. }
  17456. this._interpolantSettings = interpolantSettings;
  17457. this._interpolants = interpolants; // bound by the mixer
  17458. // inside: PropertyMixer (managed by the mixer)
  17459. this._propertyBindings = new Array( nTracks );
  17460. this._cacheIndex = null; // for the memory manager
  17461. this._byClipCacheIndex = null; // for the memory manager
  17462. this._timeScaleInterpolant = null;
  17463. this._weightInterpolant = null;
  17464. this.loop = LoopRepeat;
  17465. this._loopCount = -1;
  17466. // global mixer time when the action is to be started
  17467. // it's set back to 'null' upon start of the action
  17468. this._startTime = null;
  17469. // scaled local time of the action
  17470. // gets clamped or wrapped to 0..clip.duration according to loop
  17471. this.time = 0;
  17472. this.timeScale = 1;
  17473. this._effectiveTimeScale = 1;
  17474. this.weight = 1;
  17475. this._effectiveWeight = 1;
  17476. this.repetitions = Infinity; // no. of repetitions when looping
  17477. this.paused = false; // false -> zero effective time scale
  17478. this.enabled = true; // true -> zero effective weight
  17479. this.clampWhenFinished = false; // keep feeding the last frame?
  17480. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  17481. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  17482. }
  17483. AnimationAction.prototype = {
  17484. constructor: AnimationAction,
  17485. // State & Scheduling
  17486. play: function() {
  17487. this._mixer._activateAction( this );
  17488. return this;
  17489. },
  17490. stop: function() {
  17491. this._mixer._deactivateAction( this );
  17492. return this.reset();
  17493. },
  17494. reset: function() {
  17495. this.paused = false;
  17496. this.enabled = true;
  17497. this.time = 0; // restart clip
  17498. this._loopCount = -1; // forget previous loops
  17499. this._startTime = null; // forget scheduling
  17500. return this.stopFading().stopWarping();
  17501. },
  17502. isRunning: function() {
  17503. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  17504. this._startTime === null && this._mixer._isActiveAction( this );
  17505. },
  17506. // return true when play has been called
  17507. isScheduled: function() {
  17508. return this._mixer._isActiveAction( this );
  17509. },
  17510. startAt: function( time ) {
  17511. this._startTime = time;
  17512. return this;
  17513. },
  17514. setLoop: function( mode, repetitions ) {
  17515. this.loop = mode;
  17516. this.repetitions = repetitions;
  17517. return this;
  17518. },
  17519. // Weight
  17520. // set the weight stopping any scheduled fading
  17521. // although .enabled = false yields an effective weight of zero, this
  17522. // method does *not* change .enabled, because it would be confusing
  17523. setEffectiveWeight: function( weight ) {
  17524. this.weight = weight;
  17525. // note: same logic as when updated at runtime
  17526. this._effectiveWeight = this.enabled ? weight : 0;
  17527. return this.stopFading();
  17528. },
  17529. // return the weight considering fading and .enabled
  17530. getEffectiveWeight: function() {
  17531. return this._effectiveWeight;
  17532. },
  17533. fadeIn: function( duration ) {
  17534. return this._scheduleFading( duration, 0, 1 );
  17535. },
  17536. fadeOut: function( duration ) {
  17537. return this._scheduleFading( duration, 1, 0 );
  17538. },
  17539. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  17540. fadeOutAction.fadeOut( duration );
  17541. this.fadeIn( duration );
  17542. if( warp ) {
  17543. var fadeInDuration = this._clip.duration,
  17544. fadeOutDuration = fadeOutAction._clip.duration,
  17545. startEndRatio = fadeOutDuration / fadeInDuration,
  17546. endStartRatio = fadeInDuration / fadeOutDuration;
  17547. fadeOutAction.warp( 1.0, startEndRatio, duration );
  17548. this.warp( endStartRatio, 1.0, duration );
  17549. }
  17550. return this;
  17551. },
  17552. crossFadeTo: function( fadeInAction, duration, warp ) {
  17553. return fadeInAction.crossFadeFrom( this, duration, warp );
  17554. },
  17555. stopFading: function() {
  17556. var weightInterpolant = this._weightInterpolant;
  17557. if ( weightInterpolant !== null ) {
  17558. this._weightInterpolant = null;
  17559. this._mixer._takeBackControlInterpolant( weightInterpolant );
  17560. }
  17561. return this;
  17562. },
  17563. // Time Scale Control
  17564. // set the weight stopping any scheduled warping
  17565. // although .paused = true yields an effective time scale of zero, this
  17566. // method does *not* change .paused, because it would be confusing
  17567. setEffectiveTimeScale: function( timeScale ) {
  17568. this.timeScale = timeScale;
  17569. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  17570. return this.stopWarping();
  17571. },
  17572. // return the time scale considering warping and .paused
  17573. getEffectiveTimeScale: function() {
  17574. return this._effectiveTimeScale;
  17575. },
  17576. setDuration: function( duration ) {
  17577. this.timeScale = this._clip.duration / duration;
  17578. return this.stopWarping();
  17579. },
  17580. syncWith: function( action ) {
  17581. this.time = action.time;
  17582. this.timeScale = action.timeScale;
  17583. return this.stopWarping();
  17584. },
  17585. halt: function( duration ) {
  17586. return this.warp( this._effectiveTimeScale, 0, duration );
  17587. },
  17588. warp: function( startTimeScale, endTimeScale, duration ) {
  17589. var mixer = this._mixer, now = mixer.time,
  17590. interpolant = this._timeScaleInterpolant,
  17591. timeScale = this.timeScale;
  17592. if ( interpolant === null ) {
  17593. interpolant = mixer._lendControlInterpolant();
  17594. this._timeScaleInterpolant = interpolant;
  17595. }
  17596. var times = interpolant.parameterPositions,
  17597. values = interpolant.sampleValues;
  17598. times[ 0 ] = now;
  17599. times[ 1 ] = now + duration;
  17600. values[ 0 ] = startTimeScale / timeScale;
  17601. values[ 1 ] = endTimeScale / timeScale;
  17602. return this;
  17603. },
  17604. stopWarping: function() {
  17605. var timeScaleInterpolant = this._timeScaleInterpolant;
  17606. if ( timeScaleInterpolant !== null ) {
  17607. this._timeScaleInterpolant = null;
  17608. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  17609. }
  17610. return this;
  17611. },
  17612. // Object Accessors
  17613. getMixer: function() {
  17614. return this._mixer;
  17615. },
  17616. getClip: function() {
  17617. return this._clip;
  17618. },
  17619. getRoot: function() {
  17620. return this._localRoot || this._mixer._root;
  17621. },
  17622. // Interna
  17623. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  17624. // called by the mixer
  17625. var startTime = this._startTime;
  17626. if ( startTime !== null ) {
  17627. // check for scheduled start of action
  17628. var timeRunning = ( time - startTime ) * timeDirection;
  17629. if ( timeRunning < 0 || timeDirection === 0 ) {
  17630. return; // yet to come / don't decide when delta = 0
  17631. }
  17632. // start
  17633. this._startTime = null; // unschedule
  17634. deltaTime = timeDirection * timeRunning;
  17635. }
  17636. // apply time scale and advance time
  17637. deltaTime *= this._updateTimeScale( time );
  17638. var clipTime = this._updateTime( deltaTime );
  17639. // note: _updateTime may disable the action resulting in
  17640. // an effective weight of 0
  17641. var weight = this._updateWeight( time );
  17642. if ( weight > 0 ) {
  17643. var interpolants = this._interpolants;
  17644. var propertyMixers = this._propertyBindings;
  17645. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  17646. interpolants[ j ].evaluate( clipTime );
  17647. propertyMixers[ j ].accumulate( accuIndex, weight );
  17648. }
  17649. }
  17650. },
  17651. _updateWeight: function( time ) {
  17652. var weight = 0;
  17653. if ( this.enabled ) {
  17654. weight = this.weight;
  17655. var interpolant = this._weightInterpolant;
  17656. if ( interpolant !== null ) {
  17657. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  17658. weight *= interpolantValue;
  17659. if ( time > interpolant.parameterPositions[ 1 ] ) {
  17660. this.stopFading();
  17661. if ( interpolantValue === 0 ) {
  17662. // faded out, disable
  17663. this.enabled = false;
  17664. }
  17665. }
  17666. }
  17667. }
  17668. this._effectiveWeight = weight;
  17669. return weight;
  17670. },
  17671. _updateTimeScale: function( time ) {
  17672. var timeScale = 0;
  17673. if ( ! this.paused ) {
  17674. timeScale = this.timeScale;
  17675. var interpolant = this._timeScaleInterpolant;
  17676. if ( interpolant !== null ) {
  17677. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  17678. timeScale *= interpolantValue;
  17679. if ( time > interpolant.parameterPositions[ 1 ] ) {
  17680. this.stopWarping();
  17681. if ( timeScale === 0 ) {
  17682. // motion has halted, pause
  17683. this.paused = true;
  17684. } else {
  17685. // warp done - apply final time scale
  17686. this.timeScale = timeScale;
  17687. }
  17688. }
  17689. }
  17690. }
  17691. this._effectiveTimeScale = timeScale;
  17692. return timeScale;
  17693. },
  17694. _updateTime: function( deltaTime ) {
  17695. var time = this.time + deltaTime;
  17696. if ( deltaTime === 0 ) return time;
  17697. var duration = this._clip.duration,
  17698. loop = this.loop,
  17699. loopCount = this._loopCount;
  17700. if ( loop === LoopOnce ) {
  17701. if ( loopCount === -1 ) {
  17702. // just started
  17703. this._loopCount = 0;
  17704. this._setEndings( true, true, false );
  17705. }
  17706. handle_stop: {
  17707. if ( time >= duration ) {
  17708. time = duration;
  17709. } else if ( time < 0 ) {
  17710. time = 0;
  17711. } else break handle_stop;
  17712. if ( this.clampWhenFinished ) this.paused = true;
  17713. else this.enabled = false;
  17714. this._mixer.dispatchEvent( {
  17715. type: 'finished', action: this,
  17716. direction: deltaTime < 0 ? -1 : 1
  17717. } );
  17718. }
  17719. } else { // repetitive Repeat or PingPong
  17720. var pingPong = ( loop === LoopPingPong );
  17721. if ( loopCount === -1 ) {
  17722. // just started
  17723. if ( deltaTime >= 0 ) {
  17724. loopCount = 0;
  17725. this._setEndings(
  17726. true, this.repetitions === 0, pingPong );
  17727. } else {
  17728. // when looping in reverse direction, the initial
  17729. // transition through zero counts as a repetition,
  17730. // so leave loopCount at -1
  17731. this._setEndings(
  17732. this.repetitions === 0, true, pingPong );
  17733. }
  17734. }
  17735. if ( time >= duration || time < 0 ) {
  17736. // wrap around
  17737. var loopDelta = Math.floor( time / duration ); // signed
  17738. time -= duration * loopDelta;
  17739. loopCount += Math.abs( loopDelta );
  17740. var pending = this.repetitions - loopCount;
  17741. if ( pending < 0 ) {
  17742. // have to stop (switch state, clamp time, fire event)
  17743. if ( this.clampWhenFinished ) this.paused = true;
  17744. else this.enabled = false;
  17745. time = deltaTime > 0 ? duration : 0;
  17746. this._mixer.dispatchEvent( {
  17747. type: 'finished', action: this,
  17748. direction: deltaTime > 0 ? 1 : -1
  17749. } );
  17750. } else {
  17751. // keep running
  17752. if ( pending === 0 ) {
  17753. // entering the last round
  17754. var atStart = deltaTime < 0;
  17755. this._setEndings( atStart, ! atStart, pingPong );
  17756. } else {
  17757. this._setEndings( false, false, pingPong );
  17758. }
  17759. this._loopCount = loopCount;
  17760. this._mixer.dispatchEvent( {
  17761. type: 'loop', action: this, loopDelta: loopDelta
  17762. } );
  17763. }
  17764. }
  17765. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  17766. // invert time for the "pong round"
  17767. this.time = time;
  17768. return duration - time;
  17769. }
  17770. }
  17771. this.time = time;
  17772. return time;
  17773. },
  17774. _setEndings: function( atStart, atEnd, pingPong ) {
  17775. var settings = this._interpolantSettings;
  17776. if ( pingPong ) {
  17777. settings.endingStart = ZeroSlopeEnding;
  17778. settings.endingEnd = ZeroSlopeEnding;
  17779. } else {
  17780. // assuming for LoopOnce atStart == atEnd == true
  17781. if ( atStart ) {
  17782. settings.endingStart = this.zeroSlopeAtStart ?
  17783. ZeroSlopeEnding : ZeroCurvatureEnding;
  17784. } else {
  17785. settings.endingStart = WrapAroundEnding;
  17786. }
  17787. if ( atEnd ) {
  17788. settings.endingEnd = this.zeroSlopeAtEnd ?
  17789. ZeroSlopeEnding : ZeroCurvatureEnding;
  17790. } else {
  17791. settings.endingEnd = WrapAroundEnding;
  17792. }
  17793. }
  17794. },
  17795. _scheduleFading: function( duration, weightNow, weightThen ) {
  17796. var mixer = this._mixer, now = mixer.time,
  17797. interpolant = this._weightInterpolant;
  17798. if ( interpolant === null ) {
  17799. interpolant = mixer._lendControlInterpolant();
  17800. this._weightInterpolant = interpolant;
  17801. }
  17802. var times = interpolant.parameterPositions,
  17803. values = interpolant.sampleValues;
  17804. times[ 0 ] = now; values[ 0 ] = weightNow;
  17805. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  17806. return this;
  17807. }
  17808. };
  17809. /**
  17810. * @author tschw
  17811. * @author Ben Houston / http://clara.io/
  17812. * @author David Sarno / http://lighthaus.us/
  17813. */
  17814. var AnimationUtils = {
  17815. // same as Array.prototype.slice, but also works on typed arrays
  17816. arraySlice: function( array, from, to ) {
  17817. if ( AnimationUtils.isTypedArray( array ) ) {
  17818. return new array.constructor( array.subarray( from, to ) );
  17819. }
  17820. return array.slice( from, to );
  17821. },
  17822. // converts an array to a specific type
  17823. convertArray: function( array, type, forceClone ) {
  17824. if ( ! array || // let 'undefined' and 'null' pass
  17825. ! forceClone && array.constructor === type ) return array;
  17826. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  17827. return new type( array ); // create typed array
  17828. }
  17829. return Array.prototype.slice.call( array ); // create Array
  17830. },
  17831. isTypedArray: function( object ) {
  17832. return ArrayBuffer.isView( object ) &&
  17833. ! ( object instanceof DataView );
  17834. },
  17835. // returns an array by which times and values can be sorted
  17836. getKeyframeOrder: function( times ) {
  17837. function compareTime( i, j ) {
  17838. return times[ i ] - times[ j ];
  17839. }
  17840. var n = times.length;
  17841. var result = new Array( n );
  17842. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  17843. result.sort( compareTime );
  17844. return result;
  17845. },
  17846. // uses the array previously returned by 'getKeyframeOrder' to sort data
  17847. sortedArray: function( values, stride, order ) {
  17848. var nValues = values.length;
  17849. var result = new values.constructor( nValues );
  17850. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  17851. var srcOffset = order[ i ] * stride;
  17852. for ( var j = 0; j !== stride; ++ j ) {
  17853. result[ dstOffset ++ ] = values[ srcOffset + j ];
  17854. }
  17855. }
  17856. return result;
  17857. },
  17858. // function for parsing AOS keyframe formats
  17859. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  17860. var i = 1, key = jsonKeys[ 0 ];
  17861. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  17862. key = jsonKeys[ i ++ ];
  17863. }
  17864. if ( key === undefined ) return; // no data
  17865. var value = key[ valuePropertyName ];
  17866. if ( value === undefined ) return; // no data
  17867. if ( Array.isArray( value ) ) {
  17868. do {
  17869. value = key[ valuePropertyName ];
  17870. if ( value !== undefined ) {
  17871. times.push( key.time );
  17872. values.push.apply( values, value ); // push all elements
  17873. }
  17874. key = jsonKeys[ i ++ ];
  17875. } while ( key !== undefined );
  17876. } else if ( value.toArray !== undefined ) {
  17877. // ...assume THREE.Math-ish
  17878. do {
  17879. value = key[ valuePropertyName ];
  17880. if ( value !== undefined ) {
  17881. times.push( key.time );
  17882. value.toArray( values, values.length );
  17883. }
  17884. key = jsonKeys[ i ++ ];
  17885. } while ( key !== undefined );
  17886. } else {
  17887. // otherwise push as-is
  17888. do {
  17889. value = key[ valuePropertyName ];
  17890. if ( value !== undefined ) {
  17891. times.push( key.time );
  17892. values.push( value );
  17893. }
  17894. key = jsonKeys[ i ++ ];
  17895. } while ( key !== undefined );
  17896. }
  17897. }
  17898. };
  17899. /**
  17900. * Abstract base class of interpolants over parametric samples.
  17901. *
  17902. * The parameter domain is one dimensional, typically the time or a path
  17903. * along a curve defined by the data.
  17904. *
  17905. * The sample values can have any dimensionality and derived classes may
  17906. * apply special interpretations to the data.
  17907. *
  17908. * This class provides the interval seek in a Template Method, deferring
  17909. * the actual interpolation to derived classes.
  17910. *
  17911. * Time complexity is O(1) for linear access crossing at most two points
  17912. * and O(log N) for random access, where N is the number of positions.
  17913. *
  17914. * References:
  17915. *
  17916. * http://www.oodesign.com/template-method-pattern.html
  17917. *
  17918. * @author tschw
  17919. */
  17920. function Interpolant(
  17921. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  17922. this.parameterPositions = parameterPositions;
  17923. this._cachedIndex = 0;
  17924. this.resultBuffer = resultBuffer !== undefined ?
  17925. resultBuffer : new sampleValues.constructor( sampleSize );
  17926. this.sampleValues = sampleValues;
  17927. this.valueSize = sampleSize;
  17928. }
  17929. Interpolant.prototype = {
  17930. constructor: Interpolant,
  17931. evaluate: function( t ) {
  17932. var pp = this.parameterPositions,
  17933. i1 = this._cachedIndex,
  17934. t1 = pp[ i1 ],
  17935. t0 = pp[ i1 - 1 ];
  17936. validate_interval: {
  17937. seek: {
  17938. var right;
  17939. linear_scan: {
  17940. //- See http://jsperf.com/comparison-to-undefined/3
  17941. //- slower code:
  17942. //-
  17943. //- if ( t >= t1 || t1 === undefined ) {
  17944. forward_scan: if ( ! ( t < t1 ) ) {
  17945. for ( var giveUpAt = i1 + 2; ;) {
  17946. if ( t1 === undefined ) {
  17947. if ( t < t0 ) break forward_scan;
  17948. // after end
  17949. i1 = pp.length;
  17950. this._cachedIndex = i1;
  17951. return this.afterEnd_( i1 - 1, t, t0 );
  17952. }
  17953. if ( i1 === giveUpAt ) break; // this loop
  17954. t0 = t1;
  17955. t1 = pp[ ++ i1 ];
  17956. if ( t < t1 ) {
  17957. // we have arrived at the sought interval
  17958. break seek;
  17959. }
  17960. }
  17961. // prepare binary search on the right side of the index
  17962. right = pp.length;
  17963. break linear_scan;
  17964. }
  17965. //- slower code:
  17966. //- if ( t < t0 || t0 === undefined ) {
  17967. if ( ! ( t >= t0 ) ) {
  17968. // looping?
  17969. var t1global = pp[ 1 ];
  17970. if ( t < t1global ) {
  17971. i1 = 2; // + 1, using the scan for the details
  17972. t0 = t1global;
  17973. }
  17974. // linear reverse scan
  17975. for ( var giveUpAt = i1 - 2; ;) {
  17976. if ( t0 === undefined ) {
  17977. // before start
  17978. this._cachedIndex = 0;
  17979. return this.beforeStart_( 0, t, t1 );
  17980. }
  17981. if ( i1 === giveUpAt ) break; // this loop
  17982. t1 = t0;
  17983. t0 = pp[ -- i1 - 1 ];
  17984. if ( t >= t0 ) {
  17985. // we have arrived at the sought interval
  17986. break seek;
  17987. }
  17988. }
  17989. // prepare binary search on the left side of the index
  17990. right = i1;
  17991. i1 = 0;
  17992. break linear_scan;
  17993. }
  17994. // the interval is valid
  17995. break validate_interval;
  17996. } // linear scan
  17997. // binary search
  17998. while ( i1 < right ) {
  17999. var mid = ( i1 + right ) >>> 1;
  18000. if ( t < pp[ mid ] ) {
  18001. right = mid;
  18002. } else {
  18003. i1 = mid + 1;
  18004. }
  18005. }
  18006. t1 = pp[ i1 ];
  18007. t0 = pp[ i1 - 1 ];
  18008. // check boundary cases, again
  18009. if ( t0 === undefined ) {
  18010. this._cachedIndex = 0;
  18011. return this.beforeStart_( 0, t, t1 );
  18012. }
  18013. if ( t1 === undefined ) {
  18014. i1 = pp.length;
  18015. this._cachedIndex = i1;
  18016. return this.afterEnd_( i1 - 1, t0, t );
  18017. }
  18018. } // seek
  18019. this._cachedIndex = i1;
  18020. this.intervalChanged_( i1, t0, t1 );
  18021. } // validate_interval
  18022. return this.interpolate_( i1, t0, t, t1 );
  18023. },
  18024. settings: null, // optional, subclass-specific settings structure
  18025. // Note: The indirection allows central control of many interpolants.
  18026. // --- Protected interface
  18027. DefaultSettings_: {},
  18028. getSettings_: function() {
  18029. return this.settings || this.DefaultSettings_;
  18030. },
  18031. copySampleValue_: function( index ) {
  18032. // copies a sample value to the result buffer
  18033. var result = this.resultBuffer,
  18034. values = this.sampleValues,
  18035. stride = this.valueSize,
  18036. offset = index * stride;
  18037. for ( var i = 0; i !== stride; ++ i ) {
  18038. result[ i ] = values[ offset + i ];
  18039. }
  18040. return result;
  18041. },
  18042. // Template methods for derived classes:
  18043. interpolate_: function( i1, t0, t, t1 ) {
  18044. throw new Error( "call to abstract method" );
  18045. // implementations shall return this.resultBuffer
  18046. },
  18047. intervalChanged_: function( i1, t0, t1 ) {
  18048. // empty
  18049. }
  18050. };
  18051. Object.assign( Interpolant.prototype, {
  18052. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  18053. Interpolant.prototype.copySampleValue_,
  18054. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  18055. Interpolant.prototype.copySampleValue_
  18056. } );
  18057. /**
  18058. * Fast and simple cubic spline interpolant.
  18059. *
  18060. * It was derived from a Hermitian construction setting the first derivative
  18061. * at each sample position to the linear slope between neighboring positions
  18062. * over their parameter interval.
  18063. *
  18064. * @author tschw
  18065. */
  18066. function CubicInterpolant(
  18067. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18068. Interpolant.call(
  18069. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18070. this._weightPrev = -0;
  18071. this._offsetPrev = -0;
  18072. this._weightNext = -0;
  18073. this._offsetNext = -0;
  18074. }
  18075. CubicInterpolant.prototype =
  18076. Object.assign( Object.create( Interpolant.prototype ), {
  18077. constructor: CubicInterpolant,
  18078. DefaultSettings_: {
  18079. endingStart: ZeroCurvatureEnding,
  18080. endingEnd: ZeroCurvatureEnding
  18081. },
  18082. intervalChanged_: function( i1, t0, t1 ) {
  18083. var pp = this.parameterPositions,
  18084. iPrev = i1 - 2,
  18085. iNext = i1 + 1,
  18086. tPrev = pp[ iPrev ],
  18087. tNext = pp[ iNext ];
  18088. if ( tPrev === undefined ) {
  18089. switch ( this.getSettings_().endingStart ) {
  18090. case ZeroSlopeEnding:
  18091. // f'(t0) = 0
  18092. iPrev = i1;
  18093. tPrev = 2 * t0 - t1;
  18094. break;
  18095. case WrapAroundEnding:
  18096. // use the other end of the curve
  18097. iPrev = pp.length - 2;
  18098. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  18099. break;
  18100. default: // ZeroCurvatureEnding
  18101. // f''(t0) = 0 a.k.a. Natural Spline
  18102. iPrev = i1;
  18103. tPrev = t1;
  18104. }
  18105. }
  18106. if ( tNext === undefined ) {
  18107. switch ( this.getSettings_().endingEnd ) {
  18108. case ZeroSlopeEnding:
  18109. // f'(tN) = 0
  18110. iNext = i1;
  18111. tNext = 2 * t1 - t0;
  18112. break;
  18113. case WrapAroundEnding:
  18114. // use the other end of the curve
  18115. iNext = 1;
  18116. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  18117. break;
  18118. default: // ZeroCurvatureEnding
  18119. // f''(tN) = 0, a.k.a. Natural Spline
  18120. iNext = i1 - 1;
  18121. tNext = t0;
  18122. }
  18123. }
  18124. var halfDt = ( t1 - t0 ) * 0.5,
  18125. stride = this.valueSize;
  18126. this._weightPrev = halfDt / ( t0 - tPrev );
  18127. this._weightNext = halfDt / ( tNext - t1 );
  18128. this._offsetPrev = iPrev * stride;
  18129. this._offsetNext = iNext * stride;
  18130. },
  18131. interpolate_: function( i1, t0, t, t1 ) {
  18132. var result = this.resultBuffer,
  18133. values = this.sampleValues,
  18134. stride = this.valueSize,
  18135. o1 = i1 * stride, o0 = o1 - stride,
  18136. oP = this._offsetPrev, oN = this._offsetNext,
  18137. wP = this._weightPrev, wN = this._weightNext,
  18138. p = ( t - t0 ) / ( t1 - t0 ),
  18139. pp = p * p,
  18140. ppp = pp * p;
  18141. // evaluate polynomials
  18142. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  18143. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  18144. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  18145. var sN = wN * ppp - wN * pp;
  18146. // combine data linearly
  18147. for ( var i = 0; i !== stride; ++ i ) {
  18148. result[ i ] =
  18149. sP * values[ oP + i ] +
  18150. s0 * values[ o0 + i ] +
  18151. s1 * values[ o1 + i ] +
  18152. sN * values[ oN + i ];
  18153. }
  18154. return result;
  18155. }
  18156. } );
  18157. /**
  18158. * @author tschw
  18159. */
  18160. function LinearInterpolant(
  18161. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18162. Interpolant.call(
  18163. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18164. }
  18165. LinearInterpolant.prototype =
  18166. Object.assign( Object.create( Interpolant.prototype ), {
  18167. constructor: LinearInterpolant,
  18168. interpolate_: function( i1, t0, t, t1 ) {
  18169. var result = this.resultBuffer,
  18170. values = this.sampleValues,
  18171. stride = this.valueSize,
  18172. offset1 = i1 * stride,
  18173. offset0 = offset1 - stride,
  18174. weight1 = ( t - t0 ) / ( t1 - t0 ),
  18175. weight0 = 1 - weight1;
  18176. for ( var i = 0; i !== stride; ++ i ) {
  18177. result[ i ] =
  18178. values[ offset0 + i ] * weight0 +
  18179. values[ offset1 + i ] * weight1;
  18180. }
  18181. return result;
  18182. }
  18183. } );
  18184. /**
  18185. *
  18186. * Interpolant that evaluates to the sample value at the position preceeding
  18187. * the parameter.
  18188. *
  18189. * @author tschw
  18190. */
  18191. function DiscreteInterpolant(
  18192. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18193. Interpolant.call(
  18194. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18195. }
  18196. DiscreteInterpolant.prototype =
  18197. Object.assign( Object.create( Interpolant.prototype ), {
  18198. constructor: DiscreteInterpolant,
  18199. interpolate_: function( i1, t0, t, t1 ) {
  18200. return this.copySampleValue_( i1 - 1 );
  18201. }
  18202. } );
  18203. exports.KeyframeTrackPrototype = {
  18204. TimeBufferType: Float32Array,
  18205. ValueBufferType: Float32Array,
  18206. DefaultInterpolation: InterpolateLinear,
  18207. InterpolantFactoryMethodDiscrete: function ( result ) {
  18208. return new DiscreteInterpolant(
  18209. this.times, this.values, this.getValueSize(), result );
  18210. },
  18211. InterpolantFactoryMethodLinear: function ( result ) {
  18212. return new LinearInterpolant(
  18213. this.times, this.values, this.getValueSize(), result );
  18214. },
  18215. InterpolantFactoryMethodSmooth: function ( result ) {
  18216. return new CubicInterpolant(
  18217. this.times, this.values, this.getValueSize(), result );
  18218. },
  18219. setInterpolation: function ( interpolation ) {
  18220. var factoryMethod;
  18221. switch ( interpolation ) {
  18222. case InterpolateDiscrete:
  18223. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  18224. break;
  18225. case InterpolateLinear:
  18226. factoryMethod = this.InterpolantFactoryMethodLinear;
  18227. break;
  18228. case InterpolateSmooth:
  18229. factoryMethod = this.InterpolantFactoryMethodSmooth;
  18230. break;
  18231. }
  18232. if ( factoryMethod === undefined ) {
  18233. var message = "unsupported interpolation for " +
  18234. this.ValueTypeName + " keyframe track named " + this.name;
  18235. if ( this.createInterpolant === undefined ) {
  18236. // fall back to default, unless the default itself is messed up
  18237. if ( interpolation !== this.DefaultInterpolation ) {
  18238. this.setInterpolation( this.DefaultInterpolation );
  18239. } else {
  18240. throw new Error( message ); // fatal, in this case
  18241. }
  18242. }
  18243. console.warn( message );
  18244. return;
  18245. }
  18246. this.createInterpolant = factoryMethod;
  18247. },
  18248. getInterpolation: function () {
  18249. switch ( this.createInterpolant ) {
  18250. case this.InterpolantFactoryMethodDiscrete:
  18251. return InterpolateDiscrete;
  18252. case this.InterpolantFactoryMethodLinear:
  18253. return InterpolateLinear;
  18254. case this.InterpolantFactoryMethodSmooth:
  18255. return InterpolateSmooth;
  18256. }
  18257. },
  18258. getValueSize: function () {
  18259. return this.values.length / this.times.length;
  18260. },
  18261. // move all keyframes either forwards or backwards in time
  18262. shift: function ( timeOffset ) {
  18263. if ( timeOffset !== 0.0 ) {
  18264. var times = this.times;
  18265. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18266. times[ i ] += timeOffset;
  18267. }
  18268. }
  18269. return this;
  18270. },
  18271. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  18272. scale: function ( timeScale ) {
  18273. if ( timeScale !== 1.0 ) {
  18274. var times = this.times;
  18275. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  18276. times[ i ] *= timeScale;
  18277. }
  18278. }
  18279. return this;
  18280. },
  18281. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  18282. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  18283. trim: function ( startTime, endTime ) {
  18284. var times = this.times,
  18285. nKeys = times.length,
  18286. from = 0,
  18287. to = nKeys - 1;
  18288. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  18289. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  18290. ++ to; // inclusive -> exclusive bound
  18291. if ( from !== 0 || to !== nKeys ) {
  18292. // empty tracks are forbidden, so keep at least one keyframe
  18293. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  18294. var stride = this.getValueSize();
  18295. this.times = AnimationUtils.arraySlice( times, from, to );
  18296. this.values = AnimationUtils.
  18297. arraySlice( this.values, from * stride, to * stride );
  18298. }
  18299. return this;
  18300. },
  18301. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  18302. validate: function () {
  18303. var valid = true;
  18304. var valueSize = this.getValueSize();
  18305. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  18306. console.error( "invalid value size in track", this );
  18307. valid = false;
  18308. }
  18309. var times = this.times,
  18310. values = this.values,
  18311. nKeys = times.length;
  18312. if ( nKeys === 0 ) {
  18313. console.error( "track is empty", this );
  18314. valid = false;
  18315. }
  18316. var prevTime = null;
  18317. for ( var i = 0; i !== nKeys; i ++ ) {
  18318. var currTime = times[ i ];
  18319. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  18320. console.error( "time is not a valid number", this, i, currTime );
  18321. valid = false;
  18322. break;
  18323. }
  18324. if ( prevTime !== null && prevTime > currTime ) {
  18325. console.error( "out of order keys", this, i, currTime, prevTime );
  18326. valid = false;
  18327. break;
  18328. }
  18329. prevTime = currTime;
  18330. }
  18331. if ( values !== undefined ) {
  18332. if ( AnimationUtils.isTypedArray( values ) ) {
  18333. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  18334. var value = values[ i ];
  18335. if ( isNaN( value ) ) {
  18336. console.error( "value is not a valid number", this, i, value );
  18337. valid = false;
  18338. break;
  18339. }
  18340. }
  18341. }
  18342. }
  18343. return valid;
  18344. },
  18345. // removes equivalent sequential keys as common in morph target sequences
  18346. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  18347. optimize: function () {
  18348. var times = this.times,
  18349. values = this.values,
  18350. stride = this.getValueSize(),
  18351. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  18352. writeIndex = 1,
  18353. lastIndex = times.length - 1;
  18354. for ( var i = 1; i < lastIndex; ++ i ) {
  18355. var keep = false;
  18356. var time = times[ i ];
  18357. var timeNext = times[ i + 1 ];
  18358. // remove adjacent keyframes scheduled at the same time
  18359. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  18360. if ( ! smoothInterpolation ) {
  18361. // remove unnecessary keyframes same as their neighbors
  18362. var offset = i * stride,
  18363. offsetP = offset - stride,
  18364. offsetN = offset + stride;
  18365. for ( var j = 0; j !== stride; ++ j ) {
  18366. var value = values[ offset + j ];
  18367. if ( value !== values[ offsetP + j ] ||
  18368. value !== values[ offsetN + j ] ) {
  18369. keep = true;
  18370. break;
  18371. }
  18372. }
  18373. } else keep = true;
  18374. }
  18375. // in-place compaction
  18376. if ( keep ) {
  18377. if ( i !== writeIndex ) {
  18378. times[ writeIndex ] = times[ i ];
  18379. var readOffset = i * stride,
  18380. writeOffset = writeIndex * stride;
  18381. for ( var j = 0; j !== stride; ++ j )
  18382. values[ writeOffset + j ] = values[ readOffset + j ];
  18383. }
  18384. ++ writeIndex;
  18385. }
  18386. }
  18387. // flush last keyframe (compaction looks ahead)
  18388. if ( lastIndex > 0 ) {
  18389. times[ writeIndex ] = times[ lastIndex ];
  18390. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  18391. values[ writeOffset + j ] = values[ readOffset + j ];
  18392. ++ writeIndex;
  18393. }
  18394. if ( writeIndex !== times.length ) {
  18395. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  18396. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  18397. }
  18398. return this;
  18399. }
  18400. };
  18401. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  18402. if( name === undefined ) throw new Error( "track name is undefined" );
  18403. if( times === undefined || times.length === 0 ) {
  18404. throw new Error( "no keyframes in track named " + name );
  18405. }
  18406. this.name = name;
  18407. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  18408. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  18409. this.setInterpolation( interpolation || this.DefaultInterpolation );
  18410. this.validate();
  18411. this.optimize();
  18412. }
  18413. /**
  18414. *
  18415. * A Track of vectored keyframe values.
  18416. *
  18417. *
  18418. * @author Ben Houston / http://clara.io/
  18419. * @author David Sarno / http://lighthaus.us/
  18420. * @author tschw
  18421. */
  18422. function VectorKeyframeTrack( name, times, values, interpolation ) {
  18423. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18424. }
  18425. VectorKeyframeTrack.prototype =
  18426. Object.assign( Object.create( exports.KeyframeTrackPrototype ), {
  18427. constructor: VectorKeyframeTrack,
  18428. ValueTypeName: 'vector'
  18429. // ValueBufferType is inherited
  18430. // DefaultInterpolation is inherited
  18431. } );
  18432. /**
  18433. * Spherical linear unit quaternion interpolant.
  18434. *
  18435. * @author tschw
  18436. */
  18437. function QuaternionLinearInterpolant(
  18438. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  18439. Interpolant.call(
  18440. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  18441. }
  18442. QuaternionLinearInterpolant.prototype =
  18443. Object.assign( Object.create( Interpolant.prototype ), {
  18444. constructor: QuaternionLinearInterpolant,
  18445. interpolate_: function( i1, t0, t, t1 ) {
  18446. var result = this.resultBuffer,
  18447. values = this.sampleValues,
  18448. stride = this.valueSize,
  18449. offset = i1 * stride,
  18450. alpha = ( t - t0 ) / ( t1 - t0 );
  18451. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  18452. Quaternion.slerpFlat( result, 0,
  18453. values, offset - stride, values, offset, alpha );
  18454. }
  18455. return result;
  18456. }
  18457. } );
  18458. /**
  18459. *
  18460. * A Track of quaternion keyframe values.
  18461. *
  18462. * @author Ben Houston / http://clara.io/
  18463. * @author David Sarno / http://lighthaus.us/
  18464. * @author tschw
  18465. */
  18466. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  18467. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18468. }
  18469. QuaternionKeyframeTrack.prototype =
  18470. Object.assign( Object.create( exports.KeyframeTrackPrototype ), {
  18471. constructor: QuaternionKeyframeTrack,
  18472. ValueTypeName: 'quaternion',
  18473. // ValueBufferType is inherited
  18474. DefaultInterpolation: InterpolateLinear,
  18475. InterpolantFactoryMethodLinear: function( result ) {
  18476. return new QuaternionLinearInterpolant(
  18477. this.times, this.values, this.getValueSize(), result );
  18478. },
  18479. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  18480. } );
  18481. /**
  18482. *
  18483. * A Track of numeric keyframe values.
  18484. *
  18485. * @author Ben Houston / http://clara.io/
  18486. * @author David Sarno / http://lighthaus.us/
  18487. * @author tschw
  18488. */
  18489. function NumberKeyframeTrack( name, times, values, interpolation ) {
  18490. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18491. }
  18492. NumberKeyframeTrack.prototype =
  18493. Object.assign( Object.create( exports.KeyframeTrackPrototype ), {
  18494. constructor: NumberKeyframeTrack,
  18495. ValueTypeName: 'number'
  18496. // ValueBufferType is inherited
  18497. // DefaultInterpolation is inherited
  18498. } );
  18499. /**
  18500. *
  18501. * A Track that interpolates Strings
  18502. *
  18503. *
  18504. * @author Ben Houston / http://clara.io/
  18505. * @author David Sarno / http://lighthaus.us/
  18506. * @author tschw
  18507. */
  18508. function StringKeyframeTrack( name, times, values, interpolation ) {
  18509. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18510. }
  18511. StringKeyframeTrack.prototype =
  18512. Object.assign( Object.create( exports.KeyframeTrackPrototype ), {
  18513. constructor: StringKeyframeTrack,
  18514. ValueTypeName: 'string',
  18515. ValueBufferType: Array,
  18516. DefaultInterpolation: InterpolateDiscrete,
  18517. InterpolantFactoryMethodLinear: undefined,
  18518. InterpolantFactoryMethodSmooth: undefined
  18519. } );
  18520. /**
  18521. *
  18522. * A Track of Boolean keyframe values.
  18523. *
  18524. *
  18525. * @author Ben Houston / http://clara.io/
  18526. * @author David Sarno / http://lighthaus.us/
  18527. * @author tschw
  18528. */
  18529. function BooleanKeyframeTrack( name, times, values ) {
  18530. KeyframeTrackConstructor.call( this, name, times, values );
  18531. }
  18532. BooleanKeyframeTrack.prototype =
  18533. Object.assign( Object.create( exports.KeyframeTrackPrototype ), {
  18534. constructor: BooleanKeyframeTrack,
  18535. ValueTypeName: 'bool',
  18536. ValueBufferType: Array,
  18537. DefaultInterpolation: InterpolateDiscrete,
  18538. InterpolantFactoryMethodLinear: undefined,
  18539. InterpolantFactoryMethodSmooth: undefined
  18540. // Note: Actually this track could have a optimized / compressed
  18541. // representation of a single value and a custom interpolant that
  18542. // computes "firstValue ^ isOdd( index )".
  18543. } );
  18544. /**
  18545. *
  18546. * A Track of keyframe values that represent color.
  18547. *
  18548. *
  18549. * @author Ben Houston / http://clara.io/
  18550. * @author David Sarno / http://lighthaus.us/
  18551. * @author tschw
  18552. */
  18553. function ColorKeyframeTrack( name, times, values, interpolation ) {
  18554. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  18555. }
  18556. ColorKeyframeTrack.prototype =
  18557. Object.assign( Object.create( exports.KeyframeTrackPrototype ), {
  18558. constructor: ColorKeyframeTrack,
  18559. ValueTypeName: 'color'
  18560. // ValueBufferType is inherited
  18561. // DefaultInterpolation is inherited
  18562. // Note: Very basic implementation and nothing special yet.
  18563. // However, this is the place for color space parameterization.
  18564. } );
  18565. /**
  18566. *
  18567. * A timed sequence of keyframes for a specific property.
  18568. *
  18569. *
  18570. * @author Ben Houston / http://clara.io/
  18571. * @author David Sarno / http://lighthaus.us/
  18572. * @author tschw
  18573. */
  18574. function KeyframeTrack( name, times, values, interpolation ) {
  18575. KeyframeTrackConstructor.apply( this, arguments );
  18576. }
  18577. KeyframeTrack.prototype = exports.KeyframeTrackPrototype;
  18578. exports.KeyframeTrackPrototype.constructor = KeyframeTrack;
  18579. // Static methods:
  18580. Object.assign( KeyframeTrack, {
  18581. // Serialization (in static context, because of constructor invocation
  18582. // and automatic invocation of .toJSON):
  18583. parse: function( json ) {
  18584. if( json.type === undefined ) {
  18585. throw new Error( "track type undefined, can not parse" );
  18586. }
  18587. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  18588. if ( json.times === undefined ) {
  18589. var times = [], values = [];
  18590. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  18591. json.times = times;
  18592. json.values = values;
  18593. }
  18594. // derived classes can define a static parse method
  18595. if ( trackType.parse !== undefined ) {
  18596. return trackType.parse( json );
  18597. } else {
  18598. // by default, we asssume a constructor compatible with the base
  18599. return new trackType(
  18600. json.name, json.times, json.values, json.interpolation );
  18601. }
  18602. },
  18603. toJSON: function( track ) {
  18604. var trackType = track.constructor;
  18605. var json;
  18606. // derived classes can define a static toJSON method
  18607. if ( trackType.toJSON !== undefined ) {
  18608. json = trackType.toJSON( track );
  18609. } else {
  18610. // by default, we assume the data can be serialized as-is
  18611. json = {
  18612. 'name': track.name,
  18613. 'times': AnimationUtils.convertArray( track.times, Array ),
  18614. 'values': AnimationUtils.convertArray( track.values, Array )
  18615. };
  18616. var interpolation = track.getInterpolation();
  18617. if ( interpolation !== track.DefaultInterpolation ) {
  18618. json.interpolation = interpolation;
  18619. }
  18620. }
  18621. json.type = track.ValueTypeName; // mandatory
  18622. return json;
  18623. },
  18624. _getTrackTypeForValueTypeName: function( typeName ) {
  18625. switch( typeName.toLowerCase() ) {
  18626. case "scalar":
  18627. case "double":
  18628. case "float":
  18629. case "number":
  18630. case "integer":
  18631. return NumberKeyframeTrack;
  18632. case "vector":
  18633. case "vector2":
  18634. case "vector3":
  18635. case "vector4":
  18636. return VectorKeyframeTrack;
  18637. case "color":
  18638. return ColorKeyframeTrack;
  18639. case "quaternion":
  18640. return QuaternionKeyframeTrack;
  18641. case "bool":
  18642. case "boolean":
  18643. return BooleanKeyframeTrack;
  18644. case "string":
  18645. return StringKeyframeTrack;
  18646. }
  18647. throw new Error( "Unsupported typeName: " + typeName );
  18648. }
  18649. } );
  18650. /**
  18651. *
  18652. * Reusable set of Tracks that represent an animation.
  18653. *
  18654. * @author Ben Houston / http://clara.io/
  18655. * @author David Sarno / http://lighthaus.us/
  18656. */
  18657. function AnimationClip( name, duration, tracks ) {
  18658. this.name = name;
  18659. this.tracks = tracks;
  18660. this.duration = ( duration !== undefined ) ? duration : -1;
  18661. this.uuid = _Math.generateUUID();
  18662. // this means it should figure out its duration by scanning the tracks
  18663. if ( this.duration < 0 ) {
  18664. this.resetDuration();
  18665. }
  18666. this.optimize();
  18667. }
  18668. AnimationClip.prototype = {
  18669. constructor: AnimationClip,
  18670. resetDuration: function() {
  18671. var tracks = this.tracks,
  18672. duration = 0;
  18673. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  18674. var track = this.tracks[ i ];
  18675. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  18676. }
  18677. this.duration = duration;
  18678. },
  18679. trim: function() {
  18680. for ( var i = 0; i < this.tracks.length; i ++ ) {
  18681. this.tracks[ i ].trim( 0, this.duration );
  18682. }
  18683. return this;
  18684. },
  18685. optimize: function() {
  18686. for ( var i = 0; i < this.tracks.length; i ++ ) {
  18687. this.tracks[ i ].optimize();
  18688. }
  18689. return this;
  18690. }
  18691. };
  18692. // Static methods:
  18693. Object.assign( AnimationClip, {
  18694. parse: function( json ) {
  18695. var tracks = [],
  18696. jsonTracks = json.tracks,
  18697. frameTime = 1.0 / ( json.fps || 1.0 );
  18698. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  18699. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  18700. }
  18701. return new AnimationClip( json.name, json.duration, tracks );
  18702. },
  18703. toJSON: function( clip ) {
  18704. var tracks = [],
  18705. clipTracks = clip.tracks;
  18706. var json = {
  18707. 'name': clip.name,
  18708. 'duration': clip.duration,
  18709. 'tracks': tracks
  18710. };
  18711. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  18712. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  18713. }
  18714. return json;
  18715. },
  18716. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  18717. var numMorphTargets = morphTargetSequence.length;
  18718. var tracks = [];
  18719. for ( var i = 0; i < numMorphTargets; i ++ ) {
  18720. var times = [];
  18721. var values = [];
  18722. times.push(
  18723. ( i + numMorphTargets - 1 ) % numMorphTargets,
  18724. i,
  18725. ( i + 1 ) % numMorphTargets );
  18726. values.push( 0, 1, 0 );
  18727. var order = AnimationUtils.getKeyframeOrder( times );
  18728. times = AnimationUtils.sortedArray( times, 1, order );
  18729. values = AnimationUtils.sortedArray( values, 1, order );
  18730. // if there is a key at the first frame, duplicate it as the
  18731. // last frame as well for perfect loop.
  18732. if ( ! noLoop && times[ 0 ] === 0 ) {
  18733. times.push( numMorphTargets );
  18734. values.push( values[ 0 ] );
  18735. }
  18736. tracks.push(
  18737. new NumberKeyframeTrack(
  18738. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  18739. times, values
  18740. ).scale( 1.0 / fps ) );
  18741. }
  18742. return new AnimationClip( name, -1, tracks );
  18743. },
  18744. findByName: function( objectOrClipArray, name ) {
  18745. var clipArray = objectOrClipArray;
  18746. if ( ! Array.isArray( objectOrClipArray ) ) {
  18747. var o = objectOrClipArray;
  18748. clipArray = o.geometry && o.geometry.animations || o.animations;
  18749. }
  18750. for ( var i = 0; i < clipArray.length; i ++ ) {
  18751. if ( clipArray[ i ].name === name ) {
  18752. return clipArray[ i ];
  18753. }
  18754. }
  18755. return null;
  18756. },
  18757. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  18758. var animationToMorphTargets = {};
  18759. // tested with https://regex101.com/ on trick sequences
  18760. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  18761. var pattern = /^([\w-]*?)([\d]+)$/;
  18762. // sort morph target names into animation groups based
  18763. // patterns like Walk_001, Walk_002, Run_001, Run_002
  18764. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  18765. var morphTarget = morphTargets[ i ];
  18766. var parts = morphTarget.name.match( pattern );
  18767. if ( parts && parts.length > 1 ) {
  18768. var name = parts[ 1 ];
  18769. var animationMorphTargets = animationToMorphTargets[ name ];
  18770. if ( ! animationMorphTargets ) {
  18771. animationToMorphTargets[ name ] = animationMorphTargets = [];
  18772. }
  18773. animationMorphTargets.push( morphTarget );
  18774. }
  18775. }
  18776. var clips = [];
  18777. for ( var name in animationToMorphTargets ) {
  18778. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  18779. }
  18780. return clips;
  18781. },
  18782. // parse the animation.hierarchy format
  18783. parseAnimation: function( animation, bones ) {
  18784. if ( ! animation ) {
  18785. console.error( " no animation in JSONLoader data" );
  18786. return null;
  18787. }
  18788. var addNonemptyTrack = function(
  18789. trackType, trackName, animationKeys, propertyName, destTracks ) {
  18790. // only return track if there are actually keys.
  18791. if ( animationKeys.length !== 0 ) {
  18792. var times = [];
  18793. var values = [];
  18794. AnimationUtils.flattenJSON(
  18795. animationKeys, times, values, propertyName );
  18796. // empty keys are filtered out, so check again
  18797. if ( times.length !== 0 ) {
  18798. destTracks.push( new trackType( trackName, times, values ) );
  18799. }
  18800. }
  18801. };
  18802. var tracks = [];
  18803. var clipName = animation.name || 'default';
  18804. // automatic length determination in AnimationClip.
  18805. var duration = animation.length || -1;
  18806. var fps = animation.fps || 30;
  18807. var hierarchyTracks = animation.hierarchy || [];
  18808. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  18809. var animationKeys = hierarchyTracks[ h ].keys;
  18810. // skip empty tracks
  18811. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  18812. // process morph targets in a way exactly compatible
  18813. // with AnimationHandler.init( animation )
  18814. if ( animationKeys[0].morphTargets ) {
  18815. // figure out all morph targets used in this track
  18816. var morphTargetNames = {};
  18817. for ( var k = 0; k < animationKeys.length; k ++ ) {
  18818. if ( animationKeys[k].morphTargets ) {
  18819. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  18820. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  18821. }
  18822. }
  18823. }
  18824. // create a track for each morph target with all zero
  18825. // morphTargetInfluences except for the keys in which
  18826. // the morphTarget is named.
  18827. for ( var morphTargetName in morphTargetNames ) {
  18828. var times = [];
  18829. var values = [];
  18830. for ( var m = 0; m !== animationKeys[k].morphTargets.length; ++ m ) {
  18831. var animationKey = animationKeys[k];
  18832. times.push( animationKey.time );
  18833. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  18834. }
  18835. tracks.push( new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  18836. }
  18837. duration = morphTargetNames.length * ( fps || 1.0 );
  18838. } else {
  18839. // ...assume skeletal animation
  18840. var boneName = '.bones[' + bones[ h ].name + ']';
  18841. addNonemptyTrack(
  18842. VectorKeyframeTrack, boneName + '.position',
  18843. animationKeys, 'pos', tracks );
  18844. addNonemptyTrack(
  18845. QuaternionKeyframeTrack, boneName + '.quaternion',
  18846. animationKeys, 'rot', tracks );
  18847. addNonemptyTrack(
  18848. VectorKeyframeTrack, boneName + '.scale',
  18849. animationKeys, 'scl', tracks );
  18850. }
  18851. }
  18852. if ( tracks.length === 0 ) {
  18853. return null;
  18854. }
  18855. var clip = new AnimationClip( clipName, duration, tracks );
  18856. return clip;
  18857. }
  18858. } );
  18859. /**
  18860. *
  18861. * A reference to a real property in the scene graph.
  18862. *
  18863. *
  18864. * @author Ben Houston / http://clara.io/
  18865. * @author David Sarno / http://lighthaus.us/
  18866. * @author tschw
  18867. */
  18868. function PropertyBinding( rootNode, path, parsedPath ) {
  18869. this.path = path;
  18870. this.parsedPath = parsedPath ||
  18871. PropertyBinding.parseTrackName( path );
  18872. this.node = PropertyBinding.findNode(
  18873. rootNode, this.parsedPath.nodeName ) || rootNode;
  18874. this.rootNode = rootNode;
  18875. }
  18876. PropertyBinding.prototype = {
  18877. constructor: PropertyBinding,
  18878. getValue: function getValue_unbound( targetArray, offset ) {
  18879. this.bind();
  18880. this.getValue( targetArray, offset );
  18881. // Note: This class uses a State pattern on a per-method basis:
  18882. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18883. // prototype version of these methods with one that represents
  18884. // the bound state. When the property is not found, the methods
  18885. // become no-ops.
  18886. },
  18887. setValue: function getValue_unbound( sourceArray, offset ) {
  18888. this.bind();
  18889. this.setValue( sourceArray, offset );
  18890. },
  18891. // create getter / setter pair for a property in the scene graph
  18892. bind: function() {
  18893. var targetObject = this.node,
  18894. parsedPath = this.parsedPath,
  18895. objectName = parsedPath.objectName,
  18896. propertyName = parsedPath.propertyName,
  18897. propertyIndex = parsedPath.propertyIndex;
  18898. if ( ! targetObject ) {
  18899. targetObject = PropertyBinding.findNode(
  18900. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  18901. this.node = targetObject;
  18902. }
  18903. // set fail state so we can just 'return' on error
  18904. this.getValue = this._getValue_unavailable;
  18905. this.setValue = this._setValue_unavailable;
  18906. // ensure there is a value node
  18907. if ( ! targetObject ) {
  18908. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  18909. return;
  18910. }
  18911. if ( objectName ) {
  18912. var objectIndex = parsedPath.objectIndex;
  18913. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18914. switch ( objectName ) {
  18915. case 'materials':
  18916. if ( ! targetObject.material ) {
  18917. console.error( ' can not bind to material as node does not have a material', this );
  18918. return;
  18919. }
  18920. if ( ! targetObject.material.materials ) {
  18921. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  18922. return;
  18923. }
  18924. targetObject = targetObject.material.materials;
  18925. break;
  18926. case 'bones':
  18927. if ( ! targetObject.skeleton ) {
  18928. console.error( ' can not bind to bones as node does not have a skeleton', this );
  18929. return;
  18930. }
  18931. // potential future optimization: skip this if propertyIndex is already an integer
  18932. // and convert the integer string to a true integer.
  18933. targetObject = targetObject.skeleton.bones;
  18934. // support resolving morphTarget names into indices.
  18935. for ( var i = 0; i < targetObject.length; i ++ ) {
  18936. if ( targetObject[ i ].name === objectIndex ) {
  18937. objectIndex = i;
  18938. break;
  18939. }
  18940. }
  18941. break;
  18942. default:
  18943. if ( targetObject[ objectName ] === undefined ) {
  18944. console.error( ' can not bind to objectName of node, undefined', this );
  18945. return;
  18946. }
  18947. targetObject = targetObject[ objectName ];
  18948. }
  18949. if ( objectIndex !== undefined ) {
  18950. if ( targetObject[ objectIndex ] === undefined ) {
  18951. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  18952. return;
  18953. }
  18954. targetObject = targetObject[ objectIndex ];
  18955. }
  18956. }
  18957. // resolve property
  18958. var nodeProperty = targetObject[ propertyName ];
  18959. if ( nodeProperty === undefined ) {
  18960. var nodeName = parsedPath.nodeName;
  18961. console.error( " trying to update property for track: " + nodeName +
  18962. '.' + propertyName + " but it wasn't found.", targetObject );
  18963. return;
  18964. }
  18965. // determine versioning scheme
  18966. var versioning = this.Versioning.None;
  18967. if ( targetObject.needsUpdate !== undefined ) { // material
  18968. versioning = this.Versioning.NeedsUpdate;
  18969. this.targetObject = targetObject;
  18970. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  18971. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  18972. this.targetObject = targetObject;
  18973. }
  18974. // determine how the property gets bound
  18975. var bindingType = this.BindingType.Direct;
  18976. if ( propertyIndex !== undefined ) {
  18977. // access a sub element of the property array (only primitives are supported right now)
  18978. if ( propertyName === "morphTargetInfluences" ) {
  18979. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  18980. // support resolving morphTarget names into indices.
  18981. if ( ! targetObject.geometry ) {
  18982. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  18983. return;
  18984. }
  18985. if ( ! targetObject.geometry.morphTargets ) {
  18986. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  18987. return;
  18988. }
  18989. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  18990. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  18991. propertyIndex = i;
  18992. break;
  18993. }
  18994. }
  18995. }
  18996. bindingType = this.BindingType.ArrayElement;
  18997. this.resolvedProperty = nodeProperty;
  18998. this.propertyIndex = propertyIndex;
  18999. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  19000. // must use copy for Object3D.Euler/Quaternion
  19001. bindingType = this.BindingType.HasFromToArray;
  19002. this.resolvedProperty = nodeProperty;
  19003. } else if ( nodeProperty.length !== undefined ) {
  19004. bindingType = this.BindingType.EntireArray;
  19005. this.resolvedProperty = nodeProperty;
  19006. } else {
  19007. this.propertyName = propertyName;
  19008. }
  19009. // select getter / setter
  19010. this.getValue = this.GetterByBindingType[ bindingType ];
  19011. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  19012. },
  19013. unbind: function() {
  19014. this.node = null;
  19015. // back to the prototype version of getValue / setValue
  19016. // note: avoiding to mutate the shape of 'this' via 'delete'
  19017. this.getValue = this._getValue_unbound;
  19018. this.setValue = this._setValue_unbound;
  19019. }
  19020. };
  19021. Object.assign( PropertyBinding.prototype, { // prototype, continued
  19022. // these are used to "bind" a nonexistent property
  19023. _getValue_unavailable: function() {},
  19024. _setValue_unavailable: function() {},
  19025. // initial state of these methods that calls 'bind'
  19026. _getValue_unbound: PropertyBinding.prototype.getValue,
  19027. _setValue_unbound: PropertyBinding.prototype.setValue,
  19028. BindingType: {
  19029. Direct: 0,
  19030. EntireArray: 1,
  19031. ArrayElement: 2,
  19032. HasFromToArray: 3
  19033. },
  19034. Versioning: {
  19035. None: 0,
  19036. NeedsUpdate: 1,
  19037. MatrixWorldNeedsUpdate: 2
  19038. },
  19039. GetterByBindingType: [
  19040. function getValue_direct( buffer, offset ) {
  19041. buffer[ offset ] = this.node[ this.propertyName ];
  19042. },
  19043. function getValue_array( buffer, offset ) {
  19044. var source = this.resolvedProperty;
  19045. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  19046. buffer[ offset ++ ] = source[ i ];
  19047. }
  19048. },
  19049. function getValue_arrayElement( buffer, offset ) {
  19050. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  19051. },
  19052. function getValue_toArray( buffer, offset ) {
  19053. this.resolvedProperty.toArray( buffer, offset );
  19054. }
  19055. ],
  19056. SetterByBindingTypeAndVersioning: [
  19057. [
  19058. // Direct
  19059. function setValue_direct( buffer, offset ) {
  19060. this.node[ this.propertyName ] = buffer[ offset ];
  19061. },
  19062. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  19063. this.node[ this.propertyName ] = buffer[ offset ];
  19064. this.targetObject.needsUpdate = true;
  19065. },
  19066. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  19067. this.node[ this.propertyName ] = buffer[ offset ];
  19068. this.targetObject.matrixWorldNeedsUpdate = true;
  19069. }
  19070. ], [
  19071. // EntireArray
  19072. function setValue_array( buffer, offset ) {
  19073. var dest = this.resolvedProperty;
  19074. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  19075. dest[ i ] = buffer[ offset ++ ];
  19076. }
  19077. },
  19078. function setValue_array_setNeedsUpdate( buffer, offset ) {
  19079. var dest = this.resolvedProperty;
  19080. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  19081. dest[ i ] = buffer[ offset ++ ];
  19082. }
  19083. this.targetObject.needsUpdate = true;
  19084. },
  19085. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  19086. var dest = this.resolvedProperty;
  19087. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  19088. dest[ i ] = buffer[ offset ++ ];
  19089. }
  19090. this.targetObject.matrixWorldNeedsUpdate = true;
  19091. }
  19092. ], [
  19093. // ArrayElement
  19094. function setValue_arrayElement( buffer, offset ) {
  19095. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  19096. },
  19097. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  19098. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  19099. this.targetObject.needsUpdate = true;
  19100. },
  19101. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  19102. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  19103. this.targetObject.matrixWorldNeedsUpdate = true;
  19104. }
  19105. ], [
  19106. // HasToFromArray
  19107. function setValue_fromArray( buffer, offset ) {
  19108. this.resolvedProperty.fromArray( buffer, offset );
  19109. },
  19110. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  19111. this.resolvedProperty.fromArray( buffer, offset );
  19112. this.targetObject.needsUpdate = true;
  19113. },
  19114. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  19115. this.resolvedProperty.fromArray( buffer, offset );
  19116. this.targetObject.matrixWorldNeedsUpdate = true;
  19117. }
  19118. ]
  19119. ]
  19120. } );
  19121. PropertyBinding.Composite =
  19122. function( targetGroup, path, optionalParsedPath ) {
  19123. var parsedPath = optionalParsedPath ||
  19124. PropertyBinding.parseTrackName( path );
  19125. this._targetGroup = targetGroup;
  19126. this._bindings = targetGroup.subscribe_( path, parsedPath );
  19127. };
  19128. PropertyBinding.Composite.prototype = {
  19129. constructor: PropertyBinding.Composite,
  19130. getValue: function( array, offset ) {
  19131. this.bind(); // bind all binding
  19132. var firstValidIndex = this._targetGroup.nCachedObjects_,
  19133. binding = this._bindings[ firstValidIndex ];
  19134. // and only call .getValue on the first
  19135. if ( binding !== undefined ) binding.getValue( array, offset );
  19136. },
  19137. setValue: function( array, offset ) {
  19138. var bindings = this._bindings;
  19139. for ( var i = this._targetGroup.nCachedObjects_,
  19140. n = bindings.length; i !== n; ++ i ) {
  19141. bindings[ i ].setValue( array, offset );
  19142. }
  19143. },
  19144. bind: function() {
  19145. var bindings = this._bindings;
  19146. for ( var i = this._targetGroup.nCachedObjects_,
  19147. n = bindings.length; i !== n; ++ i ) {
  19148. bindings[ i ].bind();
  19149. }
  19150. },
  19151. unbind: function() {
  19152. var bindings = this._bindings;
  19153. for ( var i = this._targetGroup.nCachedObjects_,
  19154. n = bindings.length; i !== n; ++ i ) {
  19155. bindings[ i ].unbind();
  19156. }
  19157. }
  19158. };
  19159. PropertyBinding.create = function( root, path, parsedPath ) {
  19160. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  19161. return new PropertyBinding( root, path, parsedPath );
  19162. } else {
  19163. return new PropertyBinding.Composite( root, path, parsedPath );
  19164. }
  19165. };
  19166. PropertyBinding.parseTrackName = function( trackName ) {
  19167. // matches strings in the form of:
  19168. // nodeName.property
  19169. // nodeName.property[accessor]
  19170. // nodeName.material.property[accessor]
  19171. // uuid.property[accessor]
  19172. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  19173. // parentName/nodeName.property
  19174. // parentName/parentName/nodeName.property[index]
  19175. // .bone[Armature.DEF_cog].position
  19176. // scene:helium_balloon_model:helium_balloon_model.position
  19177. // created and tested via https://regex101.com/#javascript
  19178. var re = /^((?:[\w-]+[\/:])*)([\w-]+)?(?:\.([\w-]+)(?:\[(.+)\])?)?\.([\w-]+)(?:\[(.+)\])?$/;
  19179. var matches = re.exec( trackName );
  19180. if ( ! matches ) {
  19181. throw new Error( "cannot parse trackName at all: " + trackName );
  19182. }
  19183. var results = {
  19184. // directoryName: matches[ 1 ], // (tschw) currently unused
  19185. nodeName: matches[ 2 ], // allowed to be null, specified root node.
  19186. objectName: matches[ 3 ],
  19187. objectIndex: matches[ 4 ],
  19188. propertyName: matches[ 5 ],
  19189. propertyIndex: matches[ 6 ] // allowed to be null, specifies that the whole property is set.
  19190. };
  19191. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  19192. throw new Error( "can not parse propertyName from trackName: " + trackName );
  19193. }
  19194. return results;
  19195. };
  19196. PropertyBinding.findNode = function( root, nodeName ) {
  19197. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  19198. return root;
  19199. }
  19200. // search into skeleton bones.
  19201. if ( root.skeleton ) {
  19202. var searchSkeleton = function( skeleton ) {
  19203. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  19204. var bone = skeleton.bones[ i ];
  19205. if ( bone.name === nodeName ) {
  19206. return bone;
  19207. }
  19208. }
  19209. return null;
  19210. };
  19211. var bone = searchSkeleton( root.skeleton );
  19212. if ( bone ) {
  19213. return bone;
  19214. }
  19215. }
  19216. // search into node subtree.
  19217. if ( root.children ) {
  19218. var searchNodeSubtree = function( children ) {
  19219. for( var i = 0; i < children.length; i ++ ) {
  19220. var childNode = children[ i ];
  19221. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  19222. return childNode;
  19223. }
  19224. var result = searchNodeSubtree( childNode.children );
  19225. if ( result ) return result;
  19226. }
  19227. return null;
  19228. };
  19229. var subTreeNode = searchNodeSubtree( root.children );
  19230. if ( subTreeNode ) {
  19231. return subTreeNode;
  19232. }
  19233. }
  19234. return null;
  19235. };
  19236. /**
  19237. *
  19238. * Buffered scene graph property that allows weighted accumulation.
  19239. *
  19240. *
  19241. * @author Ben Houston / http://clara.io/
  19242. * @author David Sarno / http://lighthaus.us/
  19243. * @author tschw
  19244. */
  19245. function PropertyMixer( binding, typeName, valueSize ) {
  19246. this.binding = binding;
  19247. this.valueSize = valueSize;
  19248. var bufferType = Float64Array,
  19249. mixFunction;
  19250. switch ( typeName ) {
  19251. case 'quaternion':
  19252. mixFunction = this._slerp;
  19253. break;
  19254. case 'string':
  19255. case 'bool':
  19256. bufferType = Array;
  19257. mixFunction = this._select;
  19258. break;
  19259. default:
  19260. mixFunction = this._lerp;
  19261. }
  19262. this.buffer = new bufferType( valueSize * 4 );
  19263. // layout: [ incoming | accu0 | accu1 | orig ]
  19264. //
  19265. // interpolators can use .buffer as their .result
  19266. // the data then goes to 'incoming'
  19267. //
  19268. // 'accu0' and 'accu1' are used frame-interleaved for
  19269. // the cumulative result and are compared to detect
  19270. // changes
  19271. //
  19272. // 'orig' stores the original state of the property
  19273. this._mixBufferRegion = mixFunction;
  19274. this.cumulativeWeight = 0;
  19275. this.useCount = 0;
  19276. this.referenceCount = 0;
  19277. }
  19278. PropertyMixer.prototype = {
  19279. constructor: PropertyMixer,
  19280. // accumulate data in the 'incoming' region into 'accu<i>'
  19281. accumulate: function( accuIndex, weight ) {
  19282. // note: happily accumulating nothing when weight = 0, the caller knows
  19283. // the weight and shouldn't have made the call in the first place
  19284. var buffer = this.buffer,
  19285. stride = this.valueSize,
  19286. offset = accuIndex * stride + stride,
  19287. currentWeight = this.cumulativeWeight;
  19288. if ( currentWeight === 0 ) {
  19289. // accuN := incoming * weight
  19290. for ( var i = 0; i !== stride; ++ i ) {
  19291. buffer[ offset + i ] = buffer[ i ];
  19292. }
  19293. currentWeight = weight;
  19294. } else {
  19295. // accuN := accuN + incoming * weight
  19296. currentWeight += weight;
  19297. var mix = weight / currentWeight;
  19298. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  19299. }
  19300. this.cumulativeWeight = currentWeight;
  19301. },
  19302. // apply the state of 'accu<i>' to the binding when accus differ
  19303. apply: function( accuIndex ) {
  19304. var stride = this.valueSize,
  19305. buffer = this.buffer,
  19306. offset = accuIndex * stride + stride,
  19307. weight = this.cumulativeWeight,
  19308. binding = this.binding;
  19309. this.cumulativeWeight = 0;
  19310. if ( weight < 1 ) {
  19311. // accuN := accuN + original * ( 1 - cumulativeWeight )
  19312. var originalValueOffset = stride * 3;
  19313. this._mixBufferRegion(
  19314. buffer, offset, originalValueOffset, 1 - weight, stride );
  19315. }
  19316. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  19317. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  19318. // value has changed -> update scene graph
  19319. binding.setValue( buffer, offset );
  19320. break;
  19321. }
  19322. }
  19323. },
  19324. // remember the state of the bound property and copy it to both accus
  19325. saveOriginalState: function() {
  19326. var binding = this.binding;
  19327. var buffer = this.buffer,
  19328. stride = this.valueSize,
  19329. originalValueOffset = stride * 3;
  19330. binding.getValue( buffer, originalValueOffset );
  19331. // accu[0..1] := orig -- initially detect changes against the original
  19332. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  19333. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  19334. }
  19335. this.cumulativeWeight = 0;
  19336. },
  19337. // apply the state previously taken via 'saveOriginalState' to the binding
  19338. restoreOriginalState: function() {
  19339. var originalValueOffset = this.valueSize * 3;
  19340. this.binding.setValue( this.buffer, originalValueOffset );
  19341. },
  19342. // mix functions
  19343. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  19344. if ( t >= 0.5 ) {
  19345. for ( var i = 0; i !== stride; ++ i ) {
  19346. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  19347. }
  19348. }
  19349. },
  19350. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  19351. Quaternion.slerpFlat( buffer, dstOffset,
  19352. buffer, dstOffset, buffer, srcOffset, t );
  19353. },
  19354. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  19355. var s = 1 - t;
  19356. for ( var i = 0; i !== stride; ++ i ) {
  19357. var j = dstOffset + i;
  19358. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  19359. }
  19360. }
  19361. };
  19362. /**
  19363. *
  19364. * Player for AnimationClips.
  19365. *
  19366. *
  19367. * @author Ben Houston / http://clara.io/
  19368. * @author David Sarno / http://lighthaus.us/
  19369. * @author tschw
  19370. */
  19371. function AnimationMixer( root ) {
  19372. this._root = root;
  19373. this._initMemoryManager();
  19374. this._accuIndex = 0;
  19375. this.time = 0;
  19376. this.timeScale = 1.0;
  19377. }
  19378. AnimationMixer.prototype = {
  19379. constructor: AnimationMixer,
  19380. // return an action for a clip optionally using a custom root target
  19381. // object (this method allocates a lot of dynamic memory in case a
  19382. // previously unknown clip/root combination is specified)
  19383. clipAction: function ( clip, optionalRoot ) {
  19384. var root = optionalRoot || this._root,
  19385. rootUuid = root.uuid,
  19386. clipObject = typeof clip === 'string' ?
  19387. AnimationClip.findByName( root, clip ) : clip,
  19388. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  19389. actionsForClip = this._actionsByClip[ clipUuid ],
  19390. prototypeAction = null;
  19391. if ( actionsForClip !== undefined ) {
  19392. var existingAction =
  19393. actionsForClip.actionByRoot[ rootUuid ];
  19394. if ( existingAction !== undefined ) {
  19395. return existingAction;
  19396. }
  19397. // we know the clip, so we don't have to parse all
  19398. // the bindings again but can just copy
  19399. prototypeAction = actionsForClip.knownActions[ 0 ];
  19400. // also, take the clip from the prototype action
  19401. if ( clipObject === null )
  19402. clipObject = prototypeAction._clip;
  19403. }
  19404. // clip must be known when specified via string
  19405. if ( clipObject === null ) return null;
  19406. // allocate all resources required to run it
  19407. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  19408. this._bindAction( newAction, prototypeAction );
  19409. // and make the action known to the memory manager
  19410. this._addInactiveAction( newAction, clipUuid, rootUuid );
  19411. return newAction;
  19412. },
  19413. // get an existing action
  19414. existingAction: function ( clip, optionalRoot ) {
  19415. var root = optionalRoot || this._root,
  19416. rootUuid = root.uuid,
  19417. clipObject = typeof clip === 'string' ?
  19418. AnimationClip.findByName( root, clip ) : clip,
  19419. clipUuid = clipObject ? clipObject.uuid : clip,
  19420. actionsForClip = this._actionsByClip[ clipUuid ];
  19421. if ( actionsForClip !== undefined ) {
  19422. return actionsForClip.actionByRoot[ rootUuid ] || null;
  19423. }
  19424. return null;
  19425. },
  19426. // deactivates all previously scheduled actions
  19427. stopAllAction: function () {
  19428. var actions = this._actions,
  19429. nActions = this._nActiveActions,
  19430. bindings = this._bindings,
  19431. nBindings = this._nActiveBindings;
  19432. this._nActiveActions = 0;
  19433. this._nActiveBindings = 0;
  19434. for ( var i = 0; i !== nActions; ++ i ) {
  19435. actions[ i ].reset();
  19436. }
  19437. for ( var i = 0; i !== nBindings; ++ i ) {
  19438. bindings[ i ].useCount = 0;
  19439. }
  19440. return this;
  19441. },
  19442. // advance the time and update apply the animation
  19443. update: function ( deltaTime ) {
  19444. deltaTime *= this.timeScale;
  19445. var actions = this._actions,
  19446. nActions = this._nActiveActions,
  19447. time = this.time += deltaTime,
  19448. timeDirection = Math.sign( deltaTime ),
  19449. accuIndex = this._accuIndex ^= 1;
  19450. // run active actions
  19451. for ( var i = 0; i !== nActions; ++ i ) {
  19452. var action = actions[ i ];
  19453. if ( action.enabled ) {
  19454. action._update( time, deltaTime, timeDirection, accuIndex );
  19455. }
  19456. }
  19457. // update scene graph
  19458. var bindings = this._bindings,
  19459. nBindings = this._nActiveBindings;
  19460. for ( var i = 0; i !== nBindings; ++ i ) {
  19461. bindings[ i ].apply( accuIndex );
  19462. }
  19463. return this;
  19464. },
  19465. // return this mixer's root target object
  19466. getRoot: function () {
  19467. return this._root;
  19468. },
  19469. // free all resources specific to a particular clip
  19470. uncacheClip: function ( clip ) {
  19471. var actions = this._actions,
  19472. clipUuid = clip.uuid,
  19473. actionsByClip = this._actionsByClip,
  19474. actionsForClip = actionsByClip[ clipUuid ];
  19475. if ( actionsForClip !== undefined ) {
  19476. // note: just calling _removeInactiveAction would mess up the
  19477. // iteration state and also require updating the state we can
  19478. // just throw away
  19479. var actionsToRemove = actionsForClip.knownActions;
  19480. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  19481. var action = actionsToRemove[ i ];
  19482. this._deactivateAction( action );
  19483. var cacheIndex = action._cacheIndex,
  19484. lastInactiveAction = actions[ actions.length - 1 ];
  19485. action._cacheIndex = null;
  19486. action._byClipCacheIndex = null;
  19487. lastInactiveAction._cacheIndex = cacheIndex;
  19488. actions[ cacheIndex ] = lastInactiveAction;
  19489. actions.pop();
  19490. this._removeInactiveBindingsForAction( action );
  19491. }
  19492. delete actionsByClip[ clipUuid ];
  19493. }
  19494. },
  19495. // free all resources specific to a particular root target object
  19496. uncacheRoot: function ( root ) {
  19497. var rootUuid = root.uuid,
  19498. actionsByClip = this._actionsByClip;
  19499. for ( var clipUuid in actionsByClip ) {
  19500. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  19501. action = actionByRoot[ rootUuid ];
  19502. if ( action !== undefined ) {
  19503. this._deactivateAction( action );
  19504. this._removeInactiveAction( action );
  19505. }
  19506. }
  19507. var bindingsByRoot = this._bindingsByRootAndName,
  19508. bindingByName = bindingsByRoot[ rootUuid ];
  19509. if ( bindingByName !== undefined ) {
  19510. for ( var trackName in bindingByName ) {
  19511. var binding = bindingByName[ trackName ];
  19512. binding.restoreOriginalState();
  19513. this._removeInactiveBinding( binding );
  19514. }
  19515. }
  19516. },
  19517. // remove a targeted clip from the cache
  19518. uncacheAction: function ( clip, optionalRoot ) {
  19519. var action = this.existingAction( clip, optionalRoot );
  19520. if ( action !== null ) {
  19521. this._deactivateAction( action );
  19522. this._removeInactiveAction( action );
  19523. }
  19524. }
  19525. };
  19526. // Implementation details:
  19527. Object.assign( AnimationMixer.prototype, {
  19528. _bindAction: function ( action, prototypeAction ) {
  19529. var root = action._localRoot || this._root,
  19530. tracks = action._clip.tracks,
  19531. nTracks = tracks.length,
  19532. bindings = action._propertyBindings,
  19533. interpolants = action._interpolants,
  19534. rootUuid = root.uuid,
  19535. bindingsByRoot = this._bindingsByRootAndName,
  19536. bindingsByName = bindingsByRoot[ rootUuid ];
  19537. if ( bindingsByName === undefined ) {
  19538. bindingsByName = {};
  19539. bindingsByRoot[ rootUuid ] = bindingsByName;
  19540. }
  19541. for ( var i = 0; i !== nTracks; ++ i ) {
  19542. var track = tracks[ i ],
  19543. trackName = track.name,
  19544. binding = bindingsByName[ trackName ];
  19545. if ( binding !== undefined ) {
  19546. bindings[ i ] = binding;
  19547. } else {
  19548. binding = bindings[ i ];
  19549. if ( binding !== undefined ) {
  19550. // existing binding, make sure the cache knows
  19551. if ( binding._cacheIndex === null ) {
  19552. ++ binding.referenceCount;
  19553. this._addInactiveBinding( binding, rootUuid, trackName );
  19554. }
  19555. continue;
  19556. }
  19557. var path = prototypeAction && prototypeAction.
  19558. _propertyBindings[ i ].binding.parsedPath;
  19559. binding = new PropertyMixer(
  19560. PropertyBinding.create( root, trackName, path ),
  19561. track.ValueTypeName, track.getValueSize() );
  19562. ++ binding.referenceCount;
  19563. this._addInactiveBinding( binding, rootUuid, trackName );
  19564. bindings[ i ] = binding;
  19565. }
  19566. interpolants[ i ].resultBuffer = binding.buffer;
  19567. }
  19568. },
  19569. _activateAction: function ( action ) {
  19570. if ( ! this._isActiveAction( action ) ) {
  19571. if ( action._cacheIndex === null ) {
  19572. // this action has been forgotten by the cache, but the user
  19573. // appears to be still using it -> rebind
  19574. var rootUuid = ( action._localRoot || this._root ).uuid,
  19575. clipUuid = action._clip.uuid,
  19576. actionsForClip = this._actionsByClip[ clipUuid ];
  19577. this._bindAction( action,
  19578. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19579. this._addInactiveAction( action, clipUuid, rootUuid );
  19580. }
  19581. var bindings = action._propertyBindings;
  19582. // increment reference counts / sort out state
  19583. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  19584. var binding = bindings[ i ];
  19585. if ( binding.useCount ++ === 0 ) {
  19586. this._lendBinding( binding );
  19587. binding.saveOriginalState();
  19588. }
  19589. }
  19590. this._lendAction( action );
  19591. }
  19592. },
  19593. _deactivateAction: function ( action ) {
  19594. if ( this._isActiveAction( action ) ) {
  19595. var bindings = action._propertyBindings;
  19596. // decrement reference counts / sort out state
  19597. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  19598. var binding = bindings[ i ];
  19599. if ( -- binding.useCount === 0 ) {
  19600. binding.restoreOriginalState();
  19601. this._takeBackBinding( binding );
  19602. }
  19603. }
  19604. this._takeBackAction( action );
  19605. }
  19606. },
  19607. // Memory manager
  19608. _initMemoryManager: function () {
  19609. this._actions = []; // 'nActiveActions' followed by inactive ones
  19610. this._nActiveActions = 0;
  19611. this._actionsByClip = {};
  19612. // inside:
  19613. // {
  19614. // knownActions: Array< AnimationAction > - used as prototypes
  19615. // actionByRoot: AnimationAction - lookup
  19616. // }
  19617. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19618. this._nActiveBindings = 0;
  19619. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19620. this._controlInterpolants = []; // same game as above
  19621. this._nActiveControlInterpolants = 0;
  19622. var scope = this;
  19623. this.stats = {
  19624. actions: {
  19625. get total() { return scope._actions.length; },
  19626. get inUse() { return scope._nActiveActions; }
  19627. },
  19628. bindings: {
  19629. get total() { return scope._bindings.length; },
  19630. get inUse() { return scope._nActiveBindings; }
  19631. },
  19632. controlInterpolants: {
  19633. get total() { return scope._controlInterpolants.length; },
  19634. get inUse() { return scope._nActiveControlInterpolants; }
  19635. }
  19636. };
  19637. },
  19638. // Memory management for AnimationAction objects
  19639. _isActiveAction: function ( action ) {
  19640. var index = action._cacheIndex;
  19641. return index !== null && index < this._nActiveActions;
  19642. },
  19643. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  19644. var actions = this._actions,
  19645. actionsByClip = this._actionsByClip,
  19646. actionsForClip = actionsByClip[ clipUuid ];
  19647. if ( actionsForClip === undefined ) {
  19648. actionsForClip = {
  19649. knownActions: [ action ],
  19650. actionByRoot: {}
  19651. };
  19652. action._byClipCacheIndex = 0;
  19653. actionsByClip[ clipUuid ] = actionsForClip;
  19654. } else {
  19655. var knownActions = actionsForClip.knownActions;
  19656. action._byClipCacheIndex = knownActions.length;
  19657. knownActions.push( action );
  19658. }
  19659. action._cacheIndex = actions.length;
  19660. actions.push( action );
  19661. actionsForClip.actionByRoot[ rootUuid ] = action;
  19662. },
  19663. _removeInactiveAction: function ( action ) {
  19664. var actions = this._actions,
  19665. lastInactiveAction = actions[ actions.length - 1 ],
  19666. cacheIndex = action._cacheIndex;
  19667. lastInactiveAction._cacheIndex = cacheIndex;
  19668. actions[ cacheIndex ] = lastInactiveAction;
  19669. actions.pop();
  19670. action._cacheIndex = null;
  19671. var clipUuid = action._clip.uuid,
  19672. actionsByClip = this._actionsByClip,
  19673. actionsForClip = actionsByClip[ clipUuid ],
  19674. knownActionsForClip = actionsForClip.knownActions,
  19675. lastKnownAction =
  19676. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19677. byClipCacheIndex = action._byClipCacheIndex;
  19678. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19679. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19680. knownActionsForClip.pop();
  19681. action._byClipCacheIndex = null;
  19682. var actionByRoot = actionsForClip.actionByRoot,
  19683. rootUuid = ( actions._localRoot || this._root ).uuid;
  19684. delete actionByRoot[ rootUuid ];
  19685. if ( knownActionsForClip.length === 0 ) {
  19686. delete actionsByClip[ clipUuid ];
  19687. }
  19688. this._removeInactiveBindingsForAction( action );
  19689. },
  19690. _removeInactiveBindingsForAction: function ( action ) {
  19691. var bindings = action._propertyBindings;
  19692. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  19693. var binding = bindings[ i ];
  19694. if ( -- binding.referenceCount === 0 ) {
  19695. this._removeInactiveBinding( binding );
  19696. }
  19697. }
  19698. },
  19699. _lendAction: function ( action ) {
  19700. // [ active actions | inactive actions ]
  19701. // [ active actions >| inactive actions ]
  19702. // s a
  19703. // <-swap->
  19704. // a s
  19705. var actions = this._actions,
  19706. prevIndex = action._cacheIndex,
  19707. lastActiveIndex = this._nActiveActions ++,
  19708. firstInactiveAction = actions[ lastActiveIndex ];
  19709. action._cacheIndex = lastActiveIndex;
  19710. actions[ lastActiveIndex ] = action;
  19711. firstInactiveAction._cacheIndex = prevIndex;
  19712. actions[ prevIndex ] = firstInactiveAction;
  19713. },
  19714. _takeBackAction: function ( action ) {
  19715. // [ active actions | inactive actions ]
  19716. // [ active actions |< inactive actions ]
  19717. // a s
  19718. // <-swap->
  19719. // s a
  19720. var actions = this._actions,
  19721. prevIndex = action._cacheIndex,
  19722. firstInactiveIndex = -- this._nActiveActions,
  19723. lastActiveAction = actions[ firstInactiveIndex ];
  19724. action._cacheIndex = firstInactiveIndex;
  19725. actions[ firstInactiveIndex ] = action;
  19726. lastActiveAction._cacheIndex = prevIndex;
  19727. actions[ prevIndex ] = lastActiveAction;
  19728. },
  19729. // Memory management for PropertyMixer objects
  19730. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  19731. var bindingsByRoot = this._bindingsByRootAndName,
  19732. bindingByName = bindingsByRoot[ rootUuid ],
  19733. bindings = this._bindings;
  19734. if ( bindingByName === undefined ) {
  19735. bindingByName = {};
  19736. bindingsByRoot[ rootUuid ] = bindingByName;
  19737. }
  19738. bindingByName[ trackName ] = binding;
  19739. binding._cacheIndex = bindings.length;
  19740. bindings.push( binding );
  19741. },
  19742. _removeInactiveBinding: function ( binding ) {
  19743. var bindings = this._bindings,
  19744. propBinding = binding.binding,
  19745. rootUuid = propBinding.rootNode.uuid,
  19746. trackName = propBinding.path,
  19747. bindingsByRoot = this._bindingsByRootAndName,
  19748. bindingByName = bindingsByRoot[ rootUuid ],
  19749. lastInactiveBinding = bindings[ bindings.length - 1 ],
  19750. cacheIndex = binding._cacheIndex;
  19751. lastInactiveBinding._cacheIndex = cacheIndex;
  19752. bindings[ cacheIndex ] = lastInactiveBinding;
  19753. bindings.pop();
  19754. delete bindingByName[ trackName ];
  19755. remove_empty_map: {
  19756. for ( var _ in bindingByName ) break remove_empty_map;
  19757. delete bindingsByRoot[ rootUuid ];
  19758. }
  19759. },
  19760. _lendBinding: function ( binding ) {
  19761. var bindings = this._bindings,
  19762. prevIndex = binding._cacheIndex,
  19763. lastActiveIndex = this._nActiveBindings ++,
  19764. firstInactiveBinding = bindings[ lastActiveIndex ];
  19765. binding._cacheIndex = lastActiveIndex;
  19766. bindings[ lastActiveIndex ] = binding;
  19767. firstInactiveBinding._cacheIndex = prevIndex;
  19768. bindings[ prevIndex ] = firstInactiveBinding;
  19769. },
  19770. _takeBackBinding: function ( binding ) {
  19771. var bindings = this._bindings,
  19772. prevIndex = binding._cacheIndex,
  19773. firstInactiveIndex = -- this._nActiveBindings,
  19774. lastActiveBinding = bindings[ firstInactiveIndex ];
  19775. binding._cacheIndex = firstInactiveIndex;
  19776. bindings[ firstInactiveIndex ] = binding;
  19777. lastActiveBinding._cacheIndex = prevIndex;
  19778. bindings[ prevIndex ] = lastActiveBinding;
  19779. },
  19780. // Memory management of Interpolants for weight and time scale
  19781. _lendControlInterpolant: function () {
  19782. var interpolants = this._controlInterpolants,
  19783. lastActiveIndex = this._nActiveControlInterpolants ++,
  19784. interpolant = interpolants[ lastActiveIndex ];
  19785. if ( interpolant === undefined ) {
  19786. interpolant = new LinearInterpolant(
  19787. new Float32Array( 2 ), new Float32Array( 2 ),
  19788. 1, this._controlInterpolantsResultBuffer );
  19789. interpolant.__cacheIndex = lastActiveIndex;
  19790. interpolants[ lastActiveIndex ] = interpolant;
  19791. }
  19792. return interpolant;
  19793. },
  19794. _takeBackControlInterpolant: function ( interpolant ) {
  19795. var interpolants = this._controlInterpolants,
  19796. prevIndex = interpolant.__cacheIndex,
  19797. firstInactiveIndex = -- this._nActiveControlInterpolants,
  19798. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  19799. interpolant.__cacheIndex = firstInactiveIndex;
  19800. interpolants[ firstInactiveIndex ] = interpolant;
  19801. lastActiveInterpolant.__cacheIndex = prevIndex;
  19802. interpolants[ prevIndex ] = lastActiveInterpolant;
  19803. },
  19804. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  19805. } );
  19806. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype );
  19807. /**
  19808. *
  19809. * A group of objects that receives a shared animation state.
  19810. *
  19811. * Usage:
  19812. *
  19813. * - Add objects you would otherwise pass as 'root' to the
  19814. * constructor or the .clipAction method of AnimationMixer.
  19815. *
  19816. * - Instead pass this object as 'root'.
  19817. *
  19818. * - You can also add and remove objects later when the mixer
  19819. * is running.
  19820. *
  19821. * Note:
  19822. *
  19823. * Objects of this class appear as one object to the mixer,
  19824. * so cache control of the individual objects must be done
  19825. * on the group.
  19826. *
  19827. * Limitation:
  19828. *
  19829. * - The animated properties must be compatible among the
  19830. * all objects in the group.
  19831. *
  19832. * - A single property can either be controlled through a
  19833. * target group or directly, but not both.
  19834. *
  19835. * @author tschw
  19836. */
  19837. function AnimationObjectGroup( var_args ) {
  19838. this.uuid = _Math.generateUUID();
  19839. // cached objects followed by the active ones
  19840. this._objects = Array.prototype.slice.call( arguments );
  19841. this.nCachedObjects_ = 0; // threshold
  19842. // note: read by PropertyBinding.Composite
  19843. var indices = {};
  19844. this._indicesByUUID = indices; // for bookkeeping
  19845. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  19846. indices[ arguments[ i ].uuid ] = i;
  19847. }
  19848. this._paths = []; // inside: string
  19849. this._parsedPaths = []; // inside: { we don't care, here }
  19850. this._bindings = []; // inside: Array< PropertyBinding >
  19851. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  19852. var scope = this;
  19853. this.stats = {
  19854. objects: {
  19855. get total() { return scope._objects.length; },
  19856. get inUse() { return this.total - scope.nCachedObjects_; }
  19857. },
  19858. get bindingsPerObject() { return scope._bindings.length; }
  19859. };
  19860. }
  19861. AnimationObjectGroup.prototype = {
  19862. constructor: AnimationObjectGroup,
  19863. isAnimationObjectGroup: true,
  19864. add: function( var_args ) {
  19865. var objects = this._objects,
  19866. nObjects = objects.length,
  19867. nCachedObjects = this.nCachedObjects_,
  19868. indicesByUUID = this._indicesByUUID,
  19869. paths = this._paths,
  19870. parsedPaths = this._parsedPaths,
  19871. bindings = this._bindings,
  19872. nBindings = bindings.length;
  19873. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  19874. var object = arguments[ i ],
  19875. uuid = object.uuid,
  19876. index = indicesByUUID[ uuid ],
  19877. knownObject = undefined;
  19878. if ( index === undefined ) {
  19879. // unknown object -> add it to the ACTIVE region
  19880. index = nObjects ++;
  19881. indicesByUUID[ uuid ] = index;
  19882. objects.push( object );
  19883. // accounting is done, now do the same for all bindings
  19884. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  19885. bindings[ j ].push(
  19886. new PropertyBinding(
  19887. object, paths[ j ], parsedPaths[ j ] ) );
  19888. }
  19889. } else if ( index < nCachedObjects ) {
  19890. knownObject = objects[ index ];
  19891. // move existing object to the ACTIVE region
  19892. var firstActiveIndex = -- nCachedObjects,
  19893. lastCachedObject = objects[ firstActiveIndex ];
  19894. indicesByUUID[ lastCachedObject.uuid ] = index;
  19895. objects[ index ] = lastCachedObject;
  19896. indicesByUUID[ uuid ] = firstActiveIndex;
  19897. objects[ firstActiveIndex ] = object;
  19898. // accounting is done, now do the same for all bindings
  19899. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  19900. var bindingsForPath = bindings[ j ],
  19901. lastCached = bindingsForPath[ firstActiveIndex ],
  19902. binding = bindingsForPath[ index ];
  19903. bindingsForPath[ index ] = lastCached;
  19904. if ( binding === undefined ) {
  19905. // since we do not bother to create new bindings
  19906. // for objects that are cached, the binding may
  19907. // or may not exist
  19908. binding = new PropertyBinding(
  19909. object, paths[ j ], parsedPaths[ j ] );
  19910. }
  19911. bindingsForPath[ firstActiveIndex ] = binding;
  19912. }
  19913. } else if ( objects[ index ] !== knownObject) {
  19914. console.error( "Different objects with the same UUID " +
  19915. "detected. Clean the caches or recreate your " +
  19916. "infrastructure when reloading scenes..." );
  19917. } // else the object is already where we want it to be
  19918. } // for arguments
  19919. this.nCachedObjects_ = nCachedObjects;
  19920. },
  19921. remove: function( var_args ) {
  19922. var objects = this._objects,
  19923. nCachedObjects = this.nCachedObjects_,
  19924. indicesByUUID = this._indicesByUUID,
  19925. bindings = this._bindings,
  19926. nBindings = bindings.length;
  19927. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  19928. var object = arguments[ i ],
  19929. uuid = object.uuid,
  19930. index = indicesByUUID[ uuid ];
  19931. if ( index !== undefined && index >= nCachedObjects ) {
  19932. // move existing object into the CACHED region
  19933. var lastCachedIndex = nCachedObjects ++,
  19934. firstActiveObject = objects[ lastCachedIndex ];
  19935. indicesByUUID[ firstActiveObject.uuid ] = index;
  19936. objects[ index ] = firstActiveObject;
  19937. indicesByUUID[ uuid ] = lastCachedIndex;
  19938. objects[ lastCachedIndex ] = object;
  19939. // accounting is done, now do the same for all bindings
  19940. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  19941. var bindingsForPath = bindings[ j ],
  19942. firstActive = bindingsForPath[ lastCachedIndex ],
  19943. binding = bindingsForPath[ index ];
  19944. bindingsForPath[ index ] = firstActive;
  19945. bindingsForPath[ lastCachedIndex ] = binding;
  19946. }
  19947. }
  19948. } // for arguments
  19949. this.nCachedObjects_ = nCachedObjects;
  19950. },
  19951. // remove & forget
  19952. uncache: function( var_args ) {
  19953. var objects = this._objects,
  19954. nObjects = objects.length,
  19955. nCachedObjects = this.nCachedObjects_,
  19956. indicesByUUID = this._indicesByUUID,
  19957. bindings = this._bindings,
  19958. nBindings = bindings.length;
  19959. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  19960. var object = arguments[ i ],
  19961. uuid = object.uuid,
  19962. index = indicesByUUID[ uuid ];
  19963. if ( index !== undefined ) {
  19964. delete indicesByUUID[ uuid ];
  19965. if ( index < nCachedObjects ) {
  19966. // object is cached, shrink the CACHED region
  19967. var firstActiveIndex = -- nCachedObjects,
  19968. lastCachedObject = objects[ firstActiveIndex ],
  19969. lastIndex = -- nObjects,
  19970. lastObject = objects[ lastIndex ];
  19971. // last cached object takes this object's place
  19972. indicesByUUID[ lastCachedObject.uuid ] = index;
  19973. objects[ index ] = lastCachedObject;
  19974. // last object goes to the activated slot and pop
  19975. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19976. objects[ firstActiveIndex ] = lastObject;
  19977. objects.pop();
  19978. // accounting is done, now do the same for all bindings
  19979. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  19980. var bindingsForPath = bindings[ j ],
  19981. lastCached = bindingsForPath[ firstActiveIndex ],
  19982. last = bindingsForPath[ lastIndex ];
  19983. bindingsForPath[ index ] = lastCached;
  19984. bindingsForPath[ firstActiveIndex ] = last;
  19985. bindingsForPath.pop();
  19986. }
  19987. } else {
  19988. // object is active, just swap with the last and pop
  19989. var lastIndex = -- nObjects,
  19990. lastObject = objects[ lastIndex ];
  19991. indicesByUUID[ lastObject.uuid ] = index;
  19992. objects[ index ] = lastObject;
  19993. objects.pop();
  19994. // accounting is done, now do the same for all bindings
  19995. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  19996. var bindingsForPath = bindings[ j ];
  19997. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19998. bindingsForPath.pop();
  19999. }
  20000. } // cached or active
  20001. } // if object is known
  20002. } // for arguments
  20003. this.nCachedObjects_ = nCachedObjects;
  20004. },
  20005. // Internal interface used by befriended PropertyBinding.Composite:
  20006. subscribe_: function( path, parsedPath ) {
  20007. // returns an array of bindings for the given path that is changed
  20008. // according to the contained objects in the group
  20009. var indicesByPath = this._bindingsIndicesByPath,
  20010. index = indicesByPath[ path ],
  20011. bindings = this._bindings;
  20012. if ( index !== undefined ) return bindings[ index ];
  20013. var paths = this._paths,
  20014. parsedPaths = this._parsedPaths,
  20015. objects = this._objects,
  20016. nObjects = objects.length,
  20017. nCachedObjects = this.nCachedObjects_,
  20018. bindingsForPath = new Array( nObjects );
  20019. index = bindings.length;
  20020. indicesByPath[ path ] = index;
  20021. paths.push( path );
  20022. parsedPaths.push( parsedPath );
  20023. bindings.push( bindingsForPath );
  20024. for ( var i = nCachedObjects,
  20025. n = objects.length; i !== n; ++ i ) {
  20026. var object = objects[ i ];
  20027. bindingsForPath[ i ] =
  20028. new PropertyBinding( object, path, parsedPath );
  20029. }
  20030. return bindingsForPath;
  20031. },
  20032. unsubscribe_: function( path ) {
  20033. // tells the group to forget about a property path and no longer
  20034. // update the array previously obtained with 'subscribe_'
  20035. var indicesByPath = this._bindingsIndicesByPath,
  20036. index = indicesByPath[ path ];
  20037. if ( index !== undefined ) {
  20038. var paths = this._paths,
  20039. parsedPaths = this._parsedPaths,
  20040. bindings = this._bindings,
  20041. lastBindingsIndex = bindings.length - 1,
  20042. lastBindings = bindings[ lastBindingsIndex ],
  20043. lastBindingsPath = path[ lastBindingsIndex ];
  20044. indicesByPath[ lastBindingsPath ] = index;
  20045. bindings[ index ] = lastBindings;
  20046. bindings.pop();
  20047. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  20048. parsedPaths.pop();
  20049. paths[ index ] = paths[ lastBindingsIndex ];
  20050. paths.pop();
  20051. }
  20052. }
  20053. };
  20054. /**
  20055. * @author mrdoob / http://mrdoob.com/
  20056. */
  20057. function AudioListener() {
  20058. Object3D.call( this );
  20059. this.type = 'AudioListener';
  20060. this.context = AudioContext.getContext();
  20061. this.gain = this.context.createGain();
  20062. this.gain.connect( this.context.destination );
  20063. this.filter = null;
  20064. }
  20065. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  20066. constructor: AudioListener,
  20067. getInput: function () {
  20068. return this.gain;
  20069. },
  20070. removeFilter: function ( ) {
  20071. if ( this.filter !== null ) {
  20072. this.gain.disconnect( this.filter );
  20073. this.filter.disconnect( this.context.destination );
  20074. this.gain.connect( this.context.destination );
  20075. this.filter = null;
  20076. }
  20077. },
  20078. getFilter: function () {
  20079. return this.filter;
  20080. },
  20081. setFilter: function ( value ) {
  20082. if ( this.filter !== null ) {
  20083. this.gain.disconnect( this.filter );
  20084. this.filter.disconnect( this.context.destination );
  20085. } else {
  20086. this.gain.disconnect( this.context.destination );
  20087. }
  20088. this.filter = value;
  20089. this.gain.connect( this.filter );
  20090. this.filter.connect( this.context.destination );
  20091. },
  20092. getMasterVolume: function () {
  20093. return this.gain.gain.value;
  20094. },
  20095. setMasterVolume: function ( value ) {
  20096. this.gain.gain.value = value;
  20097. },
  20098. updateMatrixWorld: ( function () {
  20099. var position = new Vector3();
  20100. var quaternion = new Quaternion();
  20101. var scale = new Vector3();
  20102. var orientation = new Vector3();
  20103. return function updateMatrixWorld( force ) {
  20104. Object3D.prototype.updateMatrixWorld.call( this, force );
  20105. var listener = this.context.listener;
  20106. var up = this.up;
  20107. this.matrixWorld.decompose( position, quaternion, scale );
  20108. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  20109. if ( listener.positionX ) {
  20110. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  20111. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  20112. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  20113. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  20114. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  20115. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  20116. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  20117. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  20118. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  20119. } else {
  20120. listener.setPosition( position.x, position.y, position.z );
  20121. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  20122. }
  20123. };
  20124. } )()
  20125. } );
  20126. /**
  20127. * @author mrdoob / http://mrdoob.com/
  20128. */
  20129. function PositionalAudio( listener ) {
  20130. Audio.call( this, listener );
  20131. this.panner = this.context.createPanner();
  20132. this.panner.connect( this.gain );
  20133. }
  20134. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  20135. constructor: PositionalAudio,
  20136. getOutput: function () {
  20137. return this.panner;
  20138. },
  20139. getRefDistance: function () {
  20140. return this.panner.refDistance;
  20141. },
  20142. setRefDistance: function ( value ) {
  20143. this.panner.refDistance = value;
  20144. },
  20145. getRolloffFactor: function () {
  20146. return this.panner.rolloffFactor;
  20147. },
  20148. setRolloffFactor: function ( value ) {
  20149. this.panner.rolloffFactor = value;
  20150. },
  20151. getDistanceModel: function () {
  20152. return this.panner.distanceModel;
  20153. },
  20154. setDistanceModel: function ( value ) {
  20155. this.panner.distanceModel = value;
  20156. },
  20157. getMaxDistance: function () {
  20158. return this.panner.maxDistance;
  20159. },
  20160. setMaxDistance: function ( value ) {
  20161. this.panner.maxDistance = value;
  20162. },
  20163. updateMatrixWorld: ( function () {
  20164. var position = new Vector3();
  20165. return function updateMatrixWorld( force ) {
  20166. Object3D.prototype.updateMatrixWorld.call( this, force );
  20167. position.setFromMatrixPosition( this.matrixWorld );
  20168. this.panner.setPosition( position.x, position.y, position.z );
  20169. };
  20170. } )()
  20171. } );
  20172. /**
  20173. * @author alteredq / http://alteredqualia.com
  20174. */
  20175. function WebGLRenderTargetCube( width, height, options ) {
  20176. WebGLRenderTarget.call( this, width, height, options );
  20177. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  20178. this.activeMipMapLevel = 0;
  20179. }
  20180. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  20181. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  20182. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  20183. /**
  20184. * Camera for rendering cube maps
  20185. * - renders scene into axis-aligned cube
  20186. *
  20187. * @author alteredq / http://alteredqualia.com/
  20188. */
  20189. function CubeCamera( near, far, cubeResolution ) {
  20190. Object3D.call( this );
  20191. this.type = 'CubeCamera';
  20192. var fov = 90, aspect = 1;
  20193. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  20194. cameraPX.up.set( 0, - 1, 0 );
  20195. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  20196. this.add( cameraPX );
  20197. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  20198. cameraNX.up.set( 0, - 1, 0 );
  20199. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  20200. this.add( cameraNX );
  20201. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  20202. cameraPY.up.set( 0, 0, 1 );
  20203. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  20204. this.add( cameraPY );
  20205. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  20206. cameraNY.up.set( 0, 0, - 1 );
  20207. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  20208. this.add( cameraNY );
  20209. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  20210. cameraPZ.up.set( 0, - 1, 0 );
  20211. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  20212. this.add( cameraPZ );
  20213. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  20214. cameraNZ.up.set( 0, - 1, 0 );
  20215. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  20216. this.add( cameraNZ );
  20217. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  20218. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  20219. this.updateCubeMap = function ( renderer, scene ) {
  20220. if ( this.parent === null ) this.updateMatrixWorld();
  20221. var renderTarget = this.renderTarget;
  20222. var generateMipmaps = renderTarget.texture.generateMipmaps;
  20223. renderTarget.texture.generateMipmaps = false;
  20224. renderTarget.activeCubeFace = 0;
  20225. renderer.render( scene, cameraPX, renderTarget );
  20226. renderTarget.activeCubeFace = 1;
  20227. renderer.render( scene, cameraNX, renderTarget );
  20228. renderTarget.activeCubeFace = 2;
  20229. renderer.render( scene, cameraPY, renderTarget );
  20230. renderTarget.activeCubeFace = 3;
  20231. renderer.render( scene, cameraNY, renderTarget );
  20232. renderTarget.activeCubeFace = 4;
  20233. renderer.render( scene, cameraPZ, renderTarget );
  20234. renderTarget.texture.generateMipmaps = generateMipmaps;
  20235. renderTarget.activeCubeFace = 5;
  20236. renderer.render( scene, cameraNZ, renderTarget );
  20237. renderer.setRenderTarget( null );
  20238. };
  20239. }
  20240. CubeCamera.prototype = Object.create( Object3D.prototype );
  20241. CubeCamera.prototype.constructor = CubeCamera;
  20242. /**
  20243. * @author mrdoob / http://mrdoob.com/
  20244. */
  20245. function StereoCamera() {
  20246. this.type = 'StereoCamera';
  20247. this.aspect = 1;
  20248. this.eyeSep = 0.064;
  20249. this.cameraL = new PerspectiveCamera();
  20250. this.cameraL.layers.enable( 1 );
  20251. this.cameraL.matrixAutoUpdate = false;
  20252. this.cameraR = new PerspectiveCamera();
  20253. this.cameraR.layers.enable( 2 );
  20254. this.cameraR.matrixAutoUpdate = false;
  20255. }
  20256. Object.assign( StereoCamera.prototype, {
  20257. update: ( function () {
  20258. var instance, focus, fov, aspect, near, far, zoom;
  20259. var eyeRight = new Matrix4();
  20260. var eyeLeft = new Matrix4();
  20261. return function update( camera ) {
  20262. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  20263. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  20264. far !== camera.far || zoom !== camera.zoom;
  20265. if ( needsUpdate ) {
  20266. instance = this;
  20267. focus = camera.focus;
  20268. fov = camera.fov;
  20269. aspect = camera.aspect * this.aspect;
  20270. near = camera.near;
  20271. far = camera.far;
  20272. zoom = camera.zoom;
  20273. // Off-axis stereoscopic effect based on
  20274. // http://paulbourke.net/stereographics/stereorender/
  20275. var projectionMatrix = camera.projectionMatrix.clone();
  20276. var eyeSep = this.eyeSep / 2;
  20277. var eyeSepOnProjection = eyeSep * near / focus;
  20278. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  20279. var xmin, xmax;
  20280. // translate xOffset
  20281. eyeLeft.elements[ 12 ] = - eyeSep;
  20282. eyeRight.elements[ 12 ] = eyeSep;
  20283. // for left eye
  20284. xmin = - ymax * aspect + eyeSepOnProjection;
  20285. xmax = ymax * aspect + eyeSepOnProjection;
  20286. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  20287. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  20288. this.cameraL.projectionMatrix.copy( projectionMatrix );
  20289. // for right eye
  20290. xmin = - ymax * aspect - eyeSepOnProjection;
  20291. xmax = ymax * aspect - eyeSepOnProjection;
  20292. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  20293. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  20294. this.cameraR.projectionMatrix.copy( projectionMatrix );
  20295. }
  20296. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  20297. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  20298. };
  20299. } )()
  20300. } );
  20301. /**
  20302. * @author alteredq / http://alteredqualia.com/
  20303. */
  20304. function Clock( autoStart ) {
  20305. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  20306. this.startTime = 0;
  20307. this.oldTime = 0;
  20308. this.elapsedTime = 0;
  20309. this.running = false;
  20310. }
  20311. Clock.prototype = {
  20312. constructor: Clock,
  20313. start: function () {
  20314. this.startTime = ( performance || Date ).now();
  20315. this.oldTime = this.startTime;
  20316. this.elapsedTime = 0;
  20317. this.running = true;
  20318. },
  20319. stop: function () {
  20320. this.getElapsedTime();
  20321. this.running = false;
  20322. },
  20323. getElapsedTime: function () {
  20324. this.getDelta();
  20325. return this.elapsedTime;
  20326. },
  20327. getDelta: function () {
  20328. var diff = 0;
  20329. if ( this.autoStart && ! this.running ) {
  20330. this.start();
  20331. }
  20332. if ( this.running ) {
  20333. var newTime = ( performance || Date ).now();
  20334. diff = ( newTime - this.oldTime ) / 1000;
  20335. this.oldTime = newTime;
  20336. this.elapsedTime += diff;
  20337. }
  20338. return diff;
  20339. }
  20340. };
  20341. /**
  20342. * @author benaadams / https://twitter.com/ben_a_adams
  20343. */
  20344. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  20345. BufferAttribute.call( this, array, itemSize );
  20346. this.meshPerAttribute = meshPerAttribute || 1;
  20347. }
  20348. InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  20349. InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute;
  20350. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  20351. InstancedBufferAttribute.prototype.copy = function ( source ) {
  20352. BufferAttribute.prototype.copy.call( this, source );
  20353. this.meshPerAttribute = source.meshPerAttribute;
  20354. return this;
  20355. };
  20356. /**
  20357. * @author benaadams / https://twitter.com/ben_a_adams
  20358. */
  20359. function InstancedBufferGeometry() {
  20360. BufferGeometry.call( this );
  20361. this.type = 'InstancedBufferGeometry';
  20362. this.maxInstancedCount = undefined;
  20363. }
  20364. InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20365. InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry;
  20366. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  20367. InstancedBufferGeometry.prototype.addGroup = function ( start, count, materialIndex ) {
  20368. this.groups.push( {
  20369. start: start,
  20370. count: count,
  20371. materialIndex: materialIndex
  20372. } );
  20373. };
  20374. InstancedBufferGeometry.prototype.copy = function ( source ) {
  20375. var index = source.index;
  20376. if ( index !== null ) {
  20377. this.setIndex( index.clone() );
  20378. }
  20379. var attributes = source.attributes;
  20380. for ( var name in attributes ) {
  20381. var attribute = attributes[ name ];
  20382. this.addAttribute( name, attribute.clone() );
  20383. }
  20384. var groups = source.groups;
  20385. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  20386. var group = groups[ i ];
  20387. this.addGroup( group.start, group.count, group.materialIndex );
  20388. }
  20389. return this;
  20390. };
  20391. /**
  20392. * @author benaadams / https://twitter.com/ben_a_adams
  20393. */
  20394. function InterleavedBuffer( array, stride ) {
  20395. this.uuid = _Math.generateUUID();
  20396. this.array = array;
  20397. this.stride = stride;
  20398. this.count = array !== undefined ? array.length / stride : 0;
  20399. this.dynamic = false;
  20400. this.updateRange = { offset: 0, count: - 1 };
  20401. this.onUploadCallback = function () {};
  20402. this.version = 0;
  20403. }
  20404. InterleavedBuffer.prototype = {
  20405. constructor: InterleavedBuffer,
  20406. isInterleavedBuffer: true,
  20407. set needsUpdate( value ) {
  20408. if ( value === true ) this.version ++;
  20409. },
  20410. setArray: function ( array ) {
  20411. if ( Array.isArray( array ) ) {
  20412. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  20413. }
  20414. this.count = array !== undefined ? array.length / this.stride : 0;
  20415. this.array = array;
  20416. },
  20417. setDynamic: function ( value ) {
  20418. this.dynamic = value;
  20419. return this;
  20420. },
  20421. copy: function ( source ) {
  20422. this.array = new source.array.constructor( source.array );
  20423. this.count = source.count;
  20424. this.stride = source.stride;
  20425. this.dynamic = source.dynamic;
  20426. return this;
  20427. },
  20428. copyAt: function ( index1, attribute, index2 ) {
  20429. index1 *= this.stride;
  20430. index2 *= attribute.stride;
  20431. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  20432. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  20433. }
  20434. return this;
  20435. },
  20436. set: function ( value, offset ) {
  20437. if ( offset === undefined ) offset = 0;
  20438. this.array.set( value, offset );
  20439. return this;
  20440. },
  20441. clone: function () {
  20442. return new this.constructor().copy( this );
  20443. },
  20444. onUpload: function ( callback ) {
  20445. this.onUploadCallback = callback;
  20446. return this;
  20447. }
  20448. };
  20449. /**
  20450. * @author benaadams / https://twitter.com/ben_a_adams
  20451. */
  20452. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  20453. InterleavedBuffer.call( this, array, stride );
  20454. this.meshPerAttribute = meshPerAttribute || 1;
  20455. }
  20456. InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype );
  20457. InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer;
  20458. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  20459. InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  20460. InterleavedBuffer.prototype.copy.call( this, source );
  20461. this.meshPerAttribute = source.meshPerAttribute;
  20462. return this;
  20463. };
  20464. /**
  20465. * @author benaadams / https://twitter.com/ben_a_adams
  20466. */
  20467. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  20468. this.uuid = _Math.generateUUID();
  20469. this.data = interleavedBuffer;
  20470. this.itemSize = itemSize;
  20471. this.offset = offset;
  20472. this.normalized = normalized === true;
  20473. }
  20474. InterleavedBufferAttribute.prototype = {
  20475. constructor: InterleavedBufferAttribute,
  20476. isInterleavedBufferAttribute: true,
  20477. get count() {
  20478. return this.data.count;
  20479. },
  20480. get array() {
  20481. return this.data.array;
  20482. },
  20483. setX: function ( index, x ) {
  20484. this.data.array[ index * this.data.stride + this.offset ] = x;
  20485. return this;
  20486. },
  20487. setY: function ( index, y ) {
  20488. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  20489. return this;
  20490. },
  20491. setZ: function ( index, z ) {
  20492. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  20493. return this;
  20494. },
  20495. setW: function ( index, w ) {
  20496. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  20497. return this;
  20498. },
  20499. getX: function ( index ) {
  20500. return this.data.array[ index * this.data.stride + this.offset ];
  20501. },
  20502. getY: function ( index ) {
  20503. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  20504. },
  20505. getZ: function ( index ) {
  20506. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  20507. },
  20508. getW: function ( index ) {
  20509. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  20510. },
  20511. setXY: function ( index, x, y ) {
  20512. index = index * this.data.stride + this.offset;
  20513. this.data.array[ index + 0 ] = x;
  20514. this.data.array[ index + 1 ] = y;
  20515. return this;
  20516. },
  20517. setXYZ: function ( index, x, y, z ) {
  20518. index = index * this.data.stride + this.offset;
  20519. this.data.array[ index + 0 ] = x;
  20520. this.data.array[ index + 1 ] = y;
  20521. this.data.array[ index + 2 ] = z;
  20522. return this;
  20523. },
  20524. setXYZW: function ( index, x, y, z, w ) {
  20525. index = index * this.data.stride + this.offset;
  20526. this.data.array[ index + 0 ] = x;
  20527. this.data.array[ index + 1 ] = y;
  20528. this.data.array[ index + 2 ] = z;
  20529. this.data.array[ index + 3 ] = w;
  20530. return this;
  20531. }
  20532. };
  20533. /**
  20534. * @author mrdoob / http://mrdoob.com/
  20535. * @author bhouston / http://clara.io/
  20536. * @author stephomi / http://stephaneginier.com/
  20537. */
  20538. function Raycaster( origin, direction, near, far ) {
  20539. this.ray = new Ray( origin, direction );
  20540. // direction is assumed to be normalized (for accurate distance calculations)
  20541. this.near = near || 0;
  20542. this.far = far || Infinity;
  20543. this.params = {
  20544. Mesh: {},
  20545. Line: {},
  20546. LOD: {},
  20547. Points: { threshold: 1 },
  20548. Sprite: {}
  20549. };
  20550. Object.defineProperties( this.params, {
  20551. PointCloud: {
  20552. get: function () {
  20553. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  20554. return this.Points;
  20555. }
  20556. }
  20557. } );
  20558. }
  20559. function ascSort( a, b ) {
  20560. return a.distance - b.distance;
  20561. }
  20562. function intersectObject( object, raycaster, intersects, recursive ) {
  20563. if ( object.visible === false ) return;
  20564. object.raycast( raycaster, intersects );
  20565. if ( recursive === true ) {
  20566. var children = object.children;
  20567. for ( var i = 0, l = children.length; i < l; i ++ ) {
  20568. intersectObject( children[ i ], raycaster, intersects, true );
  20569. }
  20570. }
  20571. }
  20572. //
  20573. Raycaster.prototype = {
  20574. constructor: Raycaster,
  20575. linePrecision: 1,
  20576. set: function ( origin, direction ) {
  20577. // direction is assumed to be normalized (for accurate distance calculations)
  20578. this.ray.set( origin, direction );
  20579. },
  20580. setFromCamera: function ( coords, camera ) {
  20581. if ( (camera && camera.isPerspectiveCamera) ) {
  20582. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20583. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20584. } else if ( (camera && camera.isOrthographicCamera) ) {
  20585. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20586. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20587. } else {
  20588. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  20589. }
  20590. },
  20591. intersectObject: function ( object, recursive ) {
  20592. var intersects = [];
  20593. intersectObject( object, this, intersects, recursive );
  20594. intersects.sort( ascSort );
  20595. return intersects;
  20596. },
  20597. intersectObjects: function ( objects, recursive ) {
  20598. var intersects = [];
  20599. if ( Array.isArray( objects ) === false ) {
  20600. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  20601. return intersects;
  20602. }
  20603. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  20604. intersectObject( objects[ i ], this, intersects, recursive );
  20605. }
  20606. intersects.sort( ascSort );
  20607. return intersects;
  20608. }
  20609. };
  20610. /**
  20611. * @author mrdoob / http://mrdoob.com/
  20612. */
  20613. function Group() {
  20614. Object3D.call( this );
  20615. this.type = 'Group';
  20616. }
  20617. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  20618. constructor: Group
  20619. } );
  20620. /**
  20621. * @author alteredq / http://alteredqualia.com/
  20622. */
  20623. var SceneUtils = {
  20624. createMultiMaterialObject: function ( geometry, materials ) {
  20625. var group = new Group();
  20626. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  20627. group.add( new Mesh( geometry, materials[ i ] ) );
  20628. }
  20629. return group;
  20630. },
  20631. detach: function ( child, parent, scene ) {
  20632. child.applyMatrix( parent.matrixWorld );
  20633. parent.remove( child );
  20634. scene.add( child );
  20635. },
  20636. attach: function ( child, scene, parent ) {
  20637. var matrixWorldInverse = new Matrix4();
  20638. matrixWorldInverse.getInverse( parent.matrixWorld );
  20639. child.applyMatrix( matrixWorldInverse );
  20640. scene.remove( child );
  20641. parent.add( child );
  20642. }
  20643. };
  20644. /**
  20645. * @author zz85 / http://www.lab4games.net/zz85/blog
  20646. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  20647. **/
  20648. function ShapePath() {
  20649. this.subPaths = [];
  20650. this.currentPath = null;
  20651. }
  20652. ShapePath.prototype = {
  20653. moveTo: function ( x, y ) {
  20654. this.currentPath = new Path();
  20655. this.subPaths.push( this.currentPath );
  20656. this.currentPath.moveTo( x, y );
  20657. },
  20658. lineTo: function ( x, y ) {
  20659. this.currentPath.lineTo( x, y );
  20660. },
  20661. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  20662. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  20663. },
  20664. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20665. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  20666. },
  20667. splineThru: function ( pts ) {
  20668. this.currentPath.splineThru( pts );
  20669. },
  20670. toShapes: function ( isCCW, noHoles ) {
  20671. function toShapesNoHoles( inSubpaths ) {
  20672. var shapes = [];
  20673. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  20674. var tmpPath = inSubpaths[ i ];
  20675. var tmpShape = new Shape();
  20676. tmpShape.curves = tmpPath.curves;
  20677. shapes.push( tmpShape );
  20678. }
  20679. return shapes;
  20680. }
  20681. function isPointInsidePolygon( inPt, inPolygon ) {
  20682. var polyLen = inPolygon.length;
  20683. // inPt on polygon contour => immediate success or
  20684. // toggling of inside/outside at every single! intersection point of an edge
  20685. // with the horizontal line through inPt, left of inPt
  20686. // not counting lowerY endpoints of edges and whole edges on that line
  20687. var inside = false;
  20688. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  20689. var edgeLowPt = inPolygon[ p ];
  20690. var edgeHighPt = inPolygon[ q ];
  20691. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  20692. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  20693. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  20694. // not parallel
  20695. if ( edgeDy < 0 ) {
  20696. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  20697. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  20698. }
  20699. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  20700. if ( inPt.y === edgeLowPt.y ) {
  20701. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  20702. // continue; // no intersection or edgeLowPt => doesn't count !!!
  20703. } else {
  20704. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  20705. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  20706. if ( perpEdge < 0 ) continue;
  20707. inside = ! inside; // true intersection left of inPt
  20708. }
  20709. } else {
  20710. // parallel or collinear
  20711. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  20712. // edge lies on the same horizontal line as inPt
  20713. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  20714. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  20715. // continue;
  20716. }
  20717. }
  20718. return inside;
  20719. }
  20720. var isClockWise = ShapeUtils.isClockWise;
  20721. var subPaths = this.subPaths;
  20722. if ( subPaths.length === 0 ) return [];
  20723. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  20724. var solid, tmpPath, tmpShape, shapes = [];
  20725. if ( subPaths.length === 1 ) {
  20726. tmpPath = subPaths[ 0 ];
  20727. tmpShape = new Shape();
  20728. tmpShape.curves = tmpPath.curves;
  20729. shapes.push( tmpShape );
  20730. return shapes;
  20731. }
  20732. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  20733. holesFirst = isCCW ? ! holesFirst : holesFirst;
  20734. // console.log("Holes first", holesFirst);
  20735. var betterShapeHoles = [];
  20736. var newShapes = [];
  20737. var newShapeHoles = [];
  20738. var mainIdx = 0;
  20739. var tmpPoints;
  20740. newShapes[ mainIdx ] = undefined;
  20741. newShapeHoles[ mainIdx ] = [];
  20742. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  20743. tmpPath = subPaths[ i ];
  20744. tmpPoints = tmpPath.getPoints();
  20745. solid = isClockWise( tmpPoints );
  20746. solid = isCCW ? ! solid : solid;
  20747. if ( solid ) {
  20748. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  20749. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  20750. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  20751. if ( holesFirst ) mainIdx ++;
  20752. newShapeHoles[ mainIdx ] = [];
  20753. //console.log('cw', i);
  20754. } else {
  20755. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  20756. //console.log('ccw', i);
  20757. }
  20758. }
  20759. // only Holes? -> probably all Shapes with wrong orientation
  20760. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  20761. if ( newShapes.length > 1 ) {
  20762. var ambiguous = false;
  20763. var toChange = [];
  20764. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20765. betterShapeHoles[ sIdx ] = [];
  20766. }
  20767. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20768. var sho = newShapeHoles[ sIdx ];
  20769. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  20770. var ho = sho[ hIdx ];
  20771. var hole_unassigned = true;
  20772. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  20773. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  20774. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  20775. if ( hole_unassigned ) {
  20776. hole_unassigned = false;
  20777. betterShapeHoles[ s2Idx ].push( ho );
  20778. } else {
  20779. ambiguous = true;
  20780. }
  20781. }
  20782. }
  20783. if ( hole_unassigned ) {
  20784. betterShapeHoles[ sIdx ].push( ho );
  20785. }
  20786. }
  20787. }
  20788. // console.log("ambiguous: ", ambiguous);
  20789. if ( toChange.length > 0 ) {
  20790. // console.log("to change: ", toChange);
  20791. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  20792. }
  20793. }
  20794. var tmpHoles;
  20795. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  20796. tmpShape = newShapes[ i ].s;
  20797. shapes.push( tmpShape );
  20798. tmpHoles = newShapeHoles[ i ];
  20799. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  20800. tmpShape.holes.push( tmpHoles[ j ].h );
  20801. }
  20802. }
  20803. //console.log("shape", shapes);
  20804. return shapes;
  20805. }
  20806. };
  20807. /**
  20808. * @author zz85 / http://www.lab4games.net/zz85/blog
  20809. * @author mrdoob / http://mrdoob.com/
  20810. */
  20811. function Font( data ) {
  20812. this.data = data;
  20813. }
  20814. Object.assign( Font.prototype, {
  20815. isFont: true,
  20816. generateShapes: function ( text, size, divisions ) {
  20817. function createPaths( text ) {
  20818. var chars = String( text ).split( '' );
  20819. var scale = size / data.resolution;
  20820. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  20821. var offsetX = 0, offsetY = 0;
  20822. var paths = [];
  20823. for ( var i = 0; i < chars.length; i ++ ) {
  20824. var char = chars[ i ];
  20825. if ( char === '\n' ) {
  20826. offsetX = 0;
  20827. offsetY -= line_height;
  20828. } else {
  20829. var ret = createPath( char, scale, offsetX, offsetY );
  20830. offsetX += ret.offsetX;
  20831. paths.push( ret.path );
  20832. }
  20833. }
  20834. return paths;
  20835. }
  20836. function createPath( c, scale, offsetX, offsetY ) {
  20837. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  20838. if ( ! glyph ) return;
  20839. var path = new ShapePath();
  20840. var pts = [];
  20841. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  20842. if ( glyph.o ) {
  20843. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  20844. for ( var i = 0, l = outline.length; i < l; ) {
  20845. var action = outline[ i ++ ];
  20846. switch ( action ) {
  20847. case 'm': // moveTo
  20848. x = outline[ i ++ ] * scale + offsetX;
  20849. y = outline[ i ++ ] * scale + offsetY;
  20850. path.moveTo( x, y );
  20851. break;
  20852. case 'l': // lineTo
  20853. x = outline[ i ++ ] * scale + offsetX;
  20854. y = outline[ i ++ ] * scale + offsetY;
  20855. path.lineTo( x, y );
  20856. break;
  20857. case 'q': // quadraticCurveTo
  20858. cpx = outline[ i ++ ] * scale + offsetX;
  20859. cpy = outline[ i ++ ] * scale + offsetY;
  20860. cpx1 = outline[ i ++ ] * scale + offsetX;
  20861. cpy1 = outline[ i ++ ] * scale + offsetY;
  20862. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  20863. laste = pts[ pts.length - 1 ];
  20864. if ( laste ) {
  20865. cpx0 = laste.x;
  20866. cpy0 = laste.y;
  20867. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  20868. var t = i2 / divisions;
  20869. QuadraticBezier( t, cpx0, cpx1, cpx );
  20870. QuadraticBezier( t, cpy0, cpy1, cpy );
  20871. }
  20872. }
  20873. break;
  20874. case 'b': // bezierCurveTo
  20875. cpx = outline[ i ++ ] * scale + offsetX;
  20876. cpy = outline[ i ++ ] * scale + offsetY;
  20877. cpx1 = outline[ i ++ ] * scale + offsetX;
  20878. cpy1 = outline[ i ++ ] * scale + offsetY;
  20879. cpx2 = outline[ i ++ ] * scale + offsetX;
  20880. cpy2 = outline[ i ++ ] * scale + offsetY;
  20881. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  20882. laste = pts[ pts.length - 1 ];
  20883. if ( laste ) {
  20884. cpx0 = laste.x;
  20885. cpy0 = laste.y;
  20886. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  20887. var t = i2 / divisions;
  20888. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  20889. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  20890. }
  20891. }
  20892. break;
  20893. }
  20894. }
  20895. }
  20896. return { offsetX: glyph.ha * scale, path: path };
  20897. }
  20898. //
  20899. if ( size === undefined ) size = 100;
  20900. if ( divisions === undefined ) divisions = 4;
  20901. var data = this.data;
  20902. var paths = createPaths( text );
  20903. var shapes = [];
  20904. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  20905. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  20906. }
  20907. return shapes;
  20908. }
  20909. } );
  20910. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20911. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20912. }
  20913. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  20914. ArcCurve.prototype.constructor = ArcCurve;
  20915. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  20916. this.v0 = v0;
  20917. this.v1 = v1;
  20918. this.v2 = v2;
  20919. this.v3 = v3;
  20920. }
  20921. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  20922. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  20923. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  20924. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  20925. return new Vector3(
  20926. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  20927. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  20928. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  20929. );
  20930. };
  20931. function LineCurve3( v1, v2 ) {
  20932. this.v1 = v1;
  20933. this.v2 = v2;
  20934. }
  20935. LineCurve3.prototype = Object.create( Curve.prototype );
  20936. LineCurve3.prototype.constructor = LineCurve3;
  20937. LineCurve3.prototype.getPoint = function ( t ) {
  20938. if ( t === 1 ) {
  20939. return this.v2.clone();
  20940. }
  20941. var vector = new Vector3();
  20942. vector.subVectors( this.v2, this.v1 ); // diff
  20943. vector.multiplyScalar( t );
  20944. vector.add( this.v1 );
  20945. return vector;
  20946. };
  20947. function QuadraticBezierCurve3( v0, v1, v2 ) {
  20948. this.v0 = v0;
  20949. this.v1 = v1;
  20950. this.v2 = v2;
  20951. }
  20952. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  20953. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  20954. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  20955. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  20956. return new Vector3(
  20957. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  20958. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  20959. QuadraticBezier( t, v0.z, v1.z, v2.z )
  20960. );
  20961. };
  20962. /**
  20963. * @author alteredq / http://alteredqualia.com/
  20964. */
  20965. function ImmediateRenderObject( material ) {
  20966. Object3D.call( this );
  20967. this.material = material;
  20968. this.render = function ( renderCallback ) {};
  20969. }
  20970. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  20971. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  20972. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  20973. /**
  20974. * @author alteredq / http://alteredqualia.com/
  20975. */
  20976. function MorphBlendMesh( geometry, material ) {
  20977. Mesh.call( this, geometry, material );
  20978. this.animationsMap = {};
  20979. this.animationsList = [];
  20980. // prepare default animation
  20981. // (all frames played together in 1 second)
  20982. var numFrames = this.geometry.morphTargets.length;
  20983. var name = "__default";
  20984. var startFrame = 0;
  20985. var endFrame = numFrames - 1;
  20986. var fps = numFrames / 1;
  20987. this.createAnimation( name, startFrame, endFrame, fps );
  20988. this.setAnimationWeight( name, 1 );
  20989. }
  20990. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  20991. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  20992. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20993. var animation = {
  20994. start: start,
  20995. end: end,
  20996. length: end - start + 1,
  20997. fps: fps,
  20998. duration: ( end - start ) / fps,
  20999. lastFrame: 0,
  21000. currentFrame: 0,
  21001. active: false,
  21002. time: 0,
  21003. direction: 1,
  21004. weight: 1,
  21005. directionBackwards: false,
  21006. mirroredLoop: false
  21007. };
  21008. this.animationsMap[ name ] = animation;
  21009. this.animationsList.push( animation );
  21010. };
  21011. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21012. var pattern = /([a-z]+)_?(\d+)/i;
  21013. var firstAnimation, frameRanges = {};
  21014. var geometry = this.geometry;
  21015. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21016. var morph = geometry.morphTargets[ i ];
  21017. var chunks = morph.name.match( pattern );
  21018. if ( chunks && chunks.length > 1 ) {
  21019. var name = chunks[ 1 ];
  21020. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  21021. var range = frameRanges[ name ];
  21022. if ( i < range.start ) range.start = i;
  21023. if ( i > range.end ) range.end = i;
  21024. if ( ! firstAnimation ) firstAnimation = name;
  21025. }
  21026. }
  21027. for ( var name in frameRanges ) {
  21028. var range = frameRanges[ name ];
  21029. this.createAnimation( name, range.start, range.end, fps );
  21030. }
  21031. this.firstAnimation = firstAnimation;
  21032. };
  21033. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21034. var animation = this.animationsMap[ name ];
  21035. if ( animation ) {
  21036. animation.direction = 1;
  21037. animation.directionBackwards = false;
  21038. }
  21039. };
  21040. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21041. var animation = this.animationsMap[ name ];
  21042. if ( animation ) {
  21043. animation.direction = - 1;
  21044. animation.directionBackwards = true;
  21045. }
  21046. };
  21047. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21048. var animation = this.animationsMap[ name ];
  21049. if ( animation ) {
  21050. animation.fps = fps;
  21051. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21052. }
  21053. };
  21054. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21055. var animation = this.animationsMap[ name ];
  21056. if ( animation ) {
  21057. animation.duration = duration;
  21058. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21059. }
  21060. };
  21061. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21062. var animation = this.animationsMap[ name ];
  21063. if ( animation ) {
  21064. animation.weight = weight;
  21065. }
  21066. };
  21067. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21068. var animation = this.animationsMap[ name ];
  21069. if ( animation ) {
  21070. animation.time = time;
  21071. }
  21072. };
  21073. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21074. var time = 0;
  21075. var animation = this.animationsMap[ name ];
  21076. if ( animation ) {
  21077. time = animation.time;
  21078. }
  21079. return time;
  21080. };
  21081. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21082. var duration = - 1;
  21083. var animation = this.animationsMap[ name ];
  21084. if ( animation ) {
  21085. duration = animation.duration;
  21086. }
  21087. return duration;
  21088. };
  21089. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21090. var animation = this.animationsMap[ name ];
  21091. if ( animation ) {
  21092. animation.time = 0;
  21093. animation.active = true;
  21094. } else {
  21095. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  21096. }
  21097. };
  21098. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21099. var animation = this.animationsMap[ name ];
  21100. if ( animation ) {
  21101. animation.active = false;
  21102. }
  21103. };
  21104. MorphBlendMesh.prototype.update = function ( delta ) {
  21105. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21106. var animation = this.animationsList[ i ];
  21107. if ( ! animation.active ) continue;
  21108. var frameTime = animation.duration / animation.length;
  21109. animation.time += animation.direction * delta;
  21110. if ( animation.mirroredLoop ) {
  21111. if ( animation.time > animation.duration || animation.time < 0 ) {
  21112. animation.direction *= - 1;
  21113. if ( animation.time > animation.duration ) {
  21114. animation.time = animation.duration;
  21115. animation.directionBackwards = true;
  21116. }
  21117. if ( animation.time < 0 ) {
  21118. animation.time = 0;
  21119. animation.directionBackwards = false;
  21120. }
  21121. }
  21122. } else {
  21123. animation.time = animation.time % animation.duration;
  21124. if ( animation.time < 0 ) animation.time += animation.duration;
  21125. }
  21126. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21127. var weight = animation.weight;
  21128. if ( keyframe !== animation.currentFrame ) {
  21129. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21130. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21131. this.morphTargetInfluences[ keyframe ] = 0;
  21132. animation.lastFrame = animation.currentFrame;
  21133. animation.currentFrame = keyframe;
  21134. }
  21135. var mix = ( animation.time % frameTime ) / frameTime;
  21136. if ( animation.directionBackwards ) mix = 1 - mix;
  21137. if ( animation.currentFrame !== animation.lastFrame ) {
  21138. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21139. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21140. } else {
  21141. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  21142. }
  21143. }
  21144. };
  21145. /**
  21146. * @author zz85 / https://github.com/zz85
  21147. *
  21148. * Parametric Surfaces Geometry
  21149. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  21150. */
  21151. function ParametricGeometry( func, slices, stacks ) {
  21152. Geometry.call( this );
  21153. this.type = 'ParametricGeometry';
  21154. this.parameters = {
  21155. func: func,
  21156. slices: slices,
  21157. stacks: stacks
  21158. };
  21159. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  21160. this.mergeVertices();
  21161. }
  21162. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  21163. ParametricGeometry.prototype.constructor = ParametricGeometry;
  21164. /**
  21165. * @author Mugen87 / https://github.com/Mugen87
  21166. *
  21167. * Parametric Surfaces Geometry
  21168. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  21169. */
  21170. function ParametricBufferGeometry( func, slices, stacks ) {
  21171. BufferGeometry.call( this );
  21172. this.type = 'ParametricBufferGeometry';
  21173. this.parameters = {
  21174. func: func,
  21175. slices: slices,
  21176. stacks: stacks
  21177. };
  21178. // buffers
  21179. var indices = [];
  21180. var vertices = [];
  21181. var uvs = [];
  21182. var i, j;
  21183. // generate vertices and uvs
  21184. var sliceCount = slices + 1;
  21185. for ( i = 0; i <= stacks; i ++ ) {
  21186. var v = i / stacks;
  21187. for ( j = 0; j <= slices; j ++ ) {
  21188. var u = j / slices;
  21189. var p = func( u, v );
  21190. vertices.push( p.x, p.y, p.z );
  21191. uvs.push( u, v );
  21192. }
  21193. }
  21194. // generate indices
  21195. for ( i = 0; i < stacks; i ++ ) {
  21196. for ( j = 0; j < slices; j ++ ) {
  21197. var a = i * sliceCount + j;
  21198. var b = i * sliceCount + j + 1;
  21199. var c = ( i + 1 ) * sliceCount + j + 1;
  21200. var d = ( i + 1 ) * sliceCount + j;
  21201. // faces one and two
  21202. indices.push( a, b, d );
  21203. indices.push( b, c, d );
  21204. }
  21205. }
  21206. // build geometry
  21207. this.setIndex( indices );
  21208. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21209. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21210. // generate normals
  21211. this.computeVertexNormals();
  21212. }
  21213. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21214. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  21215. /**
  21216. * @author clockworkgeek / https://github.com/clockworkgeek
  21217. * @author timothypratley / https://github.com/timothypratley
  21218. * @author WestLangley / http://github.com/WestLangley
  21219. */
  21220. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  21221. Geometry.call( this );
  21222. this.type = 'PolyhedronGeometry';
  21223. this.parameters = {
  21224. vertices: vertices,
  21225. indices: indices,
  21226. radius: radius,
  21227. detail: detail
  21228. };
  21229. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  21230. this.mergeVertices();
  21231. }
  21232. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  21233. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  21234. /**
  21235. * @author Mugen87 / https://github.com/Mugen87
  21236. */
  21237. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  21238. BufferGeometry.call( this );
  21239. this.type = 'PolyhedronBufferGeometry';
  21240. this.parameters = {
  21241. vertices: vertices,
  21242. indices: indices,
  21243. radius: radius,
  21244. detail: detail
  21245. };
  21246. radius = radius || 1;
  21247. detail = detail || 0;
  21248. // default buffer data
  21249. var vertexBuffer = [];
  21250. var uvBuffer = [];
  21251. // the subdivision creates the vertex buffer data
  21252. subdivide( detail );
  21253. // all vertices should lie on a conceptual sphere with a given radius
  21254. appplyRadius( radius );
  21255. // finally, create the uv data
  21256. generateUVs();
  21257. // build non-indexed geometry
  21258. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  21259. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  21260. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  21261. this.normalizeNormals();
  21262. // helper functions
  21263. function subdivide( detail ) {
  21264. var a = new Vector3();
  21265. var b = new Vector3();
  21266. var c = new Vector3();
  21267. // iterate over all faces and apply a subdivison with the given detail value
  21268. for ( var i = 0; i < indices.length; i += 3 ) {
  21269. // get the vertices of the face
  21270. getVertexByIndex( indices[ i + 0 ], a );
  21271. getVertexByIndex( indices[ i + 1 ], b );
  21272. getVertexByIndex( indices[ i + 2 ], c );
  21273. // perform subdivision
  21274. subdivideFace( a, b, c, detail );
  21275. }
  21276. }
  21277. function subdivideFace( a, b, c, detail ) {
  21278. var cols = Math.pow( 2, detail );
  21279. // we use this multidimensional array as a data structure for creating the subdivision
  21280. var v = [];
  21281. var i, j;
  21282. // construct all of the vertices for this subdivision
  21283. for ( i = 0; i <= cols; i ++ ) {
  21284. v[ i ] = [];
  21285. var aj = a.clone().lerp( c, i / cols );
  21286. var bj = b.clone().lerp( c, i / cols );
  21287. var rows = cols - i;
  21288. for ( j = 0; j <= rows; j ++ ) {
  21289. if ( j === 0 && i === cols ) {
  21290. v[ i ][ j ] = aj;
  21291. } else {
  21292. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  21293. }
  21294. }
  21295. }
  21296. // construct all of the faces
  21297. for ( i = 0; i < cols; i ++ ) {
  21298. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  21299. var k = Math.floor( j / 2 );
  21300. if ( j % 2 === 0 ) {
  21301. pushVertex( v[ i ][ k + 1 ] );
  21302. pushVertex( v[ i + 1 ][ k ] );
  21303. pushVertex( v[ i ][ k ] );
  21304. } else {
  21305. pushVertex( v[ i ][ k + 1 ] );
  21306. pushVertex( v[ i + 1 ][ k + 1 ] );
  21307. pushVertex( v[ i + 1 ][ k ] );
  21308. }
  21309. }
  21310. }
  21311. }
  21312. function appplyRadius( radius ) {
  21313. var vertex = new Vector3();
  21314. // iterate over the entire buffer and apply the radius to each vertex
  21315. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  21316. vertex.x = vertexBuffer[ i + 0 ];
  21317. vertex.y = vertexBuffer[ i + 1 ];
  21318. vertex.z = vertexBuffer[ i + 2 ];
  21319. vertex.normalize().multiplyScalar( radius );
  21320. vertexBuffer[ i + 0 ] = vertex.x;
  21321. vertexBuffer[ i + 1 ] = vertex.y;
  21322. vertexBuffer[ i + 2 ] = vertex.z;
  21323. }
  21324. }
  21325. function generateUVs() {
  21326. var vertex = new Vector3();
  21327. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  21328. vertex.x = vertexBuffer[ i + 0 ];
  21329. vertex.y = vertexBuffer[ i + 1 ];
  21330. vertex.z = vertexBuffer[ i + 2 ];
  21331. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  21332. var v = inclination( vertex ) / Math.PI + 0.5;
  21333. uvBuffer.push( u, 1 - v );
  21334. }
  21335. correctUVs();
  21336. correctSeam();
  21337. }
  21338. function correctSeam() {
  21339. // handle case when face straddles the seam, see #3269
  21340. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  21341. // uv data of a single face
  21342. var x0 = uvBuffer[ i + 0 ];
  21343. var x1 = uvBuffer[ i + 2 ];
  21344. var x2 = uvBuffer[ i + 4 ];
  21345. var max = Math.max( x0, x1, x2 );
  21346. var min = Math.min( x0, x1, x2 );
  21347. // 0.9 is somewhat arbitrary
  21348. if ( max > 0.9 && min < 0.1 ) {
  21349. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  21350. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  21351. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  21352. }
  21353. }
  21354. }
  21355. function pushVertex( vertex ) {
  21356. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  21357. }
  21358. function getVertexByIndex( index, vertex ) {
  21359. var stride = index * 3;
  21360. vertex.x = vertices[ stride + 0 ];
  21361. vertex.y = vertices[ stride + 1 ];
  21362. vertex.z = vertices[ stride + 2 ];
  21363. }
  21364. function correctUVs() {
  21365. var a = new Vector3();
  21366. var b = new Vector3();
  21367. var c = new Vector3();
  21368. var centroid = new Vector3();
  21369. var uvA = new Vector2();
  21370. var uvB = new Vector2();
  21371. var uvC = new Vector2();
  21372. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  21373. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  21374. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  21375. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  21376. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  21377. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  21378. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  21379. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  21380. var azi = azimuth( centroid );
  21381. correctUV( uvA, j + 0, a, azi );
  21382. correctUV( uvB, j + 2, b, azi );
  21383. correctUV( uvC, j + 4, c, azi );
  21384. }
  21385. }
  21386. function correctUV( uv, stride, vector, azimuth ) {
  21387. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  21388. uvBuffer[ stride ] = uv.x - 1;
  21389. }
  21390. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  21391. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  21392. }
  21393. }
  21394. // Angle around the Y axis, counter-clockwise when looking from above.
  21395. function azimuth( vector ) {
  21396. return Math.atan2( vector.z, - vector.x );
  21397. }
  21398. // Angle above the XZ plane.
  21399. function inclination( vector ) {
  21400. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  21401. }
  21402. }
  21403. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21404. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  21405. /**
  21406. * @author timothypratley / https://github.com/timothypratley
  21407. */
  21408. function TetrahedronGeometry( radius, detail ) {
  21409. Geometry.call( this );
  21410. this.type = 'TetrahedronGeometry';
  21411. this.parameters = {
  21412. radius: radius,
  21413. detail: detail
  21414. };
  21415. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  21416. this.mergeVertices();
  21417. }
  21418. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  21419. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  21420. /**
  21421. * @author Mugen87 / https://github.com/Mugen87
  21422. */
  21423. function TetrahedronBufferGeometry( radius, detail ) {
  21424. var vertices = [
  21425. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21426. ];
  21427. var indices = [
  21428. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21429. ];
  21430. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  21431. this.type = 'TetrahedronBufferGeometry';
  21432. this.parameters = {
  21433. radius: radius,
  21434. detail: detail
  21435. };
  21436. }
  21437. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  21438. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  21439. /**
  21440. * @author timothypratley / https://github.com/timothypratley
  21441. */
  21442. function OctahedronGeometry( radius, detail ) {
  21443. Geometry.call( this );
  21444. this.type = 'OctahedronGeometry';
  21445. this.parameters = {
  21446. radius: radius,
  21447. detail: detail
  21448. };
  21449. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  21450. this.mergeVertices();
  21451. }
  21452. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  21453. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  21454. /**
  21455. * @author Mugen87 / https://github.com/Mugen87
  21456. */
  21457. function OctahedronBufferGeometry( radius, detail ) {
  21458. var vertices = [
  21459. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21460. ];
  21461. var indices = [
  21462. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  21463. ];
  21464. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  21465. this.type = 'OctahedronBufferGeometry';
  21466. this.parameters = {
  21467. radius: radius,
  21468. detail: detail
  21469. };
  21470. }
  21471. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  21472. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  21473. /**
  21474. * @author timothypratley / https://github.com/timothypratley
  21475. */
  21476. function IcosahedronGeometry( radius, detail ) {
  21477. Geometry.call( this );
  21478. this.type = 'IcosahedronGeometry';
  21479. this.parameters = {
  21480. radius: radius,
  21481. detail: detail
  21482. };
  21483. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  21484. this.mergeVertices();
  21485. }
  21486. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  21487. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  21488. /**
  21489. * @author Mugen87 / https://github.com/Mugen87
  21490. */
  21491. function IcosahedronBufferGeometry( radius, detail ) {
  21492. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21493. var vertices = [
  21494. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21495. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21496. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21497. ];
  21498. var indices = [
  21499. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21500. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21501. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21502. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21503. ];
  21504. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  21505. this.type = 'IcosahedronBufferGeometry';
  21506. this.parameters = {
  21507. radius: radius,
  21508. detail: detail
  21509. };
  21510. }
  21511. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  21512. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  21513. /**
  21514. * @author Abe Pazos / https://hamoid.com
  21515. */
  21516. function DodecahedronGeometry( radius, detail ) {
  21517. Geometry.call( this );
  21518. this.type = 'DodecahedronGeometry';
  21519. this.parameters = {
  21520. radius: radius,
  21521. detail: detail
  21522. };
  21523. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  21524. this.mergeVertices();
  21525. }
  21526. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  21527. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  21528. /**
  21529. * @author Mugen87 / https://github.com/Mugen87
  21530. */
  21531. function DodecahedronBufferGeometry( radius, detail ) {
  21532. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21533. var r = 1 / t;
  21534. var vertices = [
  21535. // (±1, ±1, ±1)
  21536. - 1, - 1, - 1, - 1, - 1, 1,
  21537. - 1, 1, - 1, - 1, 1, 1,
  21538. 1, - 1, - 1, 1, - 1, 1,
  21539. 1, 1, - 1, 1, 1, 1,
  21540. // (0, ±1/φ, ±φ)
  21541. 0, - r, - t, 0, - r, t,
  21542. 0, r, - t, 0, r, t,
  21543. // (±1/φ, ±φ, 0)
  21544. - r, - t, 0, - r, t, 0,
  21545. r, - t, 0, r, t, 0,
  21546. // (±φ, 0, ±1/φ)
  21547. - t, 0, - r, t, 0, - r,
  21548. - t, 0, r, t, 0, r
  21549. ];
  21550. var indices = [
  21551. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  21552. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  21553. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  21554. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  21555. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  21556. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  21557. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  21558. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  21559. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  21560. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  21561. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  21562. 1, 12, 14, 1, 14, 5, 1, 5, 9
  21563. ];
  21564. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  21565. this.type = 'DodecahedronBufferGeometry';
  21566. this.parameters = {
  21567. radius: radius,
  21568. detail: detail
  21569. };
  21570. }
  21571. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  21572. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  21573. /**
  21574. * @author oosmoxiecode / https://github.com/oosmoxiecode
  21575. * @author WestLangley / https://github.com/WestLangley
  21576. * @author zz85 / https://github.com/zz85
  21577. * @author miningold / https://github.com/miningold
  21578. * @author jonobr1 / https://github.com/jonobr1
  21579. *
  21580. * Creates a tube which extrudes along a 3d spline.
  21581. */
  21582. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  21583. Geometry.call( this );
  21584. this.type = 'TubeGeometry';
  21585. this.parameters = {
  21586. path: path,
  21587. tubularSegments: tubularSegments,
  21588. radius: radius,
  21589. radialSegments: radialSegments,
  21590. closed: closed
  21591. };
  21592. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  21593. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  21594. // expose internals
  21595. this.tangents = bufferGeometry.tangents;
  21596. this.normals = bufferGeometry.normals;
  21597. this.binormals = bufferGeometry.binormals;
  21598. // create geometry
  21599. this.fromBufferGeometry( bufferGeometry );
  21600. this.mergeVertices();
  21601. }
  21602. TubeGeometry.prototype = Object.create( Geometry.prototype );
  21603. TubeGeometry.prototype.constructor = TubeGeometry;
  21604. /**
  21605. * @author Mugen87 / https://github.com/Mugen87
  21606. */
  21607. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  21608. BufferGeometry.call( this );
  21609. this.type = 'TubeBufferGeometry';
  21610. this.parameters = {
  21611. path: path,
  21612. tubularSegments: tubularSegments,
  21613. radius: radius,
  21614. radialSegments: radialSegments,
  21615. closed: closed
  21616. };
  21617. tubularSegments = tubularSegments || 64;
  21618. radius = radius || 1;
  21619. radialSegments = radialSegments || 8;
  21620. closed = closed || false;
  21621. var frames = path.computeFrenetFrames( tubularSegments, closed );
  21622. // expose internals
  21623. this.tangents = frames.tangents;
  21624. this.normals = frames.normals;
  21625. this.binormals = frames.binormals;
  21626. // helper variables
  21627. var vertex = new Vector3();
  21628. var normal = new Vector3();
  21629. var uv = new Vector2();
  21630. var i, j;
  21631. // buffer
  21632. var vertices = [];
  21633. var normals = [];
  21634. var uvs = [];
  21635. var indices = [];
  21636. // create buffer data
  21637. generateBufferData();
  21638. // build geometry
  21639. this.setIndex( indices );
  21640. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21641. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21642. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21643. // functions
  21644. function generateBufferData() {
  21645. for ( i = 0; i < tubularSegments; i ++ ) {
  21646. generateSegment( i );
  21647. }
  21648. // if the geometry is not closed, generate the last row of vertices and normals
  21649. // at the regular position on the given path
  21650. //
  21651. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21652. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21653. // uvs are generated in a separate function.
  21654. // this makes it easy compute correct values for closed geometries
  21655. generateUVs();
  21656. // finally create faces
  21657. generateIndices();
  21658. }
  21659. function generateSegment( i ) {
  21660. // we use getPointAt to sample evenly distributed points from the given path
  21661. var P = path.getPointAt( i / tubularSegments );
  21662. // retrieve corresponding normal and binormal
  21663. var N = frames.normals[ i ];
  21664. var B = frames.binormals[ i ];
  21665. // generate normals and vertices for the current segment
  21666. for ( j = 0; j <= radialSegments; j ++ ) {
  21667. var v = j / radialSegments * Math.PI * 2;
  21668. var sin = Math.sin( v );
  21669. var cos = - Math.cos( v );
  21670. // normal
  21671. normal.x = ( cos * N.x + sin * B.x );
  21672. normal.y = ( cos * N.y + sin * B.y );
  21673. normal.z = ( cos * N.z + sin * B.z );
  21674. normal.normalize();
  21675. normals.push( normal.x, normal.y, normal.z );
  21676. // vertex
  21677. vertex.x = P.x + radius * normal.x;
  21678. vertex.y = P.y + radius * normal.y;
  21679. vertex.z = P.z + radius * normal.z;
  21680. vertices.push( vertex.x, vertex.y, vertex.z );
  21681. }
  21682. }
  21683. function generateIndices() {
  21684. for ( j = 1; j <= tubularSegments; j ++ ) {
  21685. for ( i = 1; i <= radialSegments; i ++ ) {
  21686. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21687. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  21688. var c = ( radialSegments + 1 ) * j + i;
  21689. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21690. // faces
  21691. indices.push( a, b, d );
  21692. indices.push( b, c, d );
  21693. }
  21694. }
  21695. }
  21696. function generateUVs() {
  21697. for ( i = 0; i <= tubularSegments; i ++ ) {
  21698. for ( j = 0; j <= radialSegments; j ++ ) {
  21699. uv.x = i / tubularSegments;
  21700. uv.y = j / radialSegments;
  21701. uvs.push( uv.x, uv.y );
  21702. }
  21703. }
  21704. }
  21705. }
  21706. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21707. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  21708. /**
  21709. * @author oosmoxiecode
  21710. */
  21711. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  21712. Geometry.call( this );
  21713. this.type = 'TorusKnotGeometry';
  21714. this.parameters = {
  21715. radius: radius,
  21716. tube: tube,
  21717. tubularSegments: tubularSegments,
  21718. radialSegments: radialSegments,
  21719. p: p,
  21720. q: q
  21721. };
  21722. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  21723. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  21724. this.mergeVertices();
  21725. }
  21726. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  21727. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  21728. /**
  21729. * @author Mugen87 / https://github.com/Mugen87
  21730. * see: http://www.blackpawn.com/texts/pqtorus/
  21731. */
  21732. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  21733. BufferGeometry.call( this );
  21734. this.type = 'TorusKnotBufferGeometry';
  21735. this.parameters = {
  21736. radius: radius,
  21737. tube: tube,
  21738. tubularSegments: tubularSegments,
  21739. radialSegments: radialSegments,
  21740. p: p,
  21741. q: q
  21742. };
  21743. radius = radius || 100;
  21744. tube = tube || 40;
  21745. tubularSegments = Math.floor( tubularSegments ) || 64;
  21746. radialSegments = Math.floor( radialSegments ) || 8;
  21747. p = p || 2;
  21748. q = q || 3;
  21749. // buffers
  21750. var indices = [];
  21751. var vertices = [];
  21752. var normals = [];
  21753. var uvs = [];
  21754. // helper variables
  21755. var i, j;
  21756. var vertex = new Vector3();
  21757. var normal = new Vector3();
  21758. var uv = new Vector2();
  21759. var P1 = new Vector3();
  21760. var P2 = new Vector3();
  21761. var B = new Vector3();
  21762. var T = new Vector3();
  21763. var N = new Vector3();
  21764. // generate vertices, normals and uvs
  21765. for ( i = 0; i <= tubularSegments; ++ i ) {
  21766. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  21767. var u = i / tubularSegments * p * Math.PI * 2;
  21768. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21769. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21770. calculatePositionOnCurve( u, p, q, radius, P1 );
  21771. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21772. // calculate orthonormal basis
  21773. T.subVectors( P2, P1 );
  21774. N.addVectors( P2, P1 );
  21775. B.crossVectors( T, N );
  21776. N.crossVectors( B, T );
  21777. // normalize B, N. T can be ignored, we don't use it
  21778. B.normalize();
  21779. N.normalize();
  21780. for ( j = 0; j <= radialSegments; ++ j ) {
  21781. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21782. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21783. var v = j / radialSegments * Math.PI * 2;
  21784. var cx = - tube * Math.cos( v );
  21785. var cy = tube * Math.sin( v );
  21786. // now calculate the final vertex position.
  21787. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  21788. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21789. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21790. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21791. vertices.push( vertex.x, vertex.y, vertex.z );
  21792. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21793. normal.subVectors( vertex, P1 ).normalize();
  21794. normals.push( normal.x, normal.y, normal.z );
  21795. // uv
  21796. uvs.push( i / tubularSegments );
  21797. uvs.push( j / radialSegments );
  21798. }
  21799. }
  21800. // generate indices
  21801. for ( j = 1; j <= tubularSegments; j ++ ) {
  21802. for ( i = 1; i <= radialSegments; i ++ ) {
  21803. // indices
  21804. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21805. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  21806. var c = ( radialSegments + 1 ) * j + i;
  21807. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21808. // faces
  21809. indices.push( a, b, d );
  21810. indices.push( b, c, d );
  21811. }
  21812. }
  21813. // build geometry
  21814. this.setIndex( indices );
  21815. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21816. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21817. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21818. // this function calculates the current position on the torus curve
  21819. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21820. var cu = Math.cos( u );
  21821. var su = Math.sin( u );
  21822. var quOverP = q / p * u;
  21823. var cs = Math.cos( quOverP );
  21824. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21825. position.y = radius * ( 2 + cs ) * su * 0.5;
  21826. position.z = radius * Math.sin( quOverP ) * 0.5;
  21827. }
  21828. }
  21829. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21830. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  21831. /**
  21832. * @author oosmoxiecode
  21833. * @author mrdoob / http://mrdoob.com/
  21834. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  21835. */
  21836. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  21837. Geometry.call( this );
  21838. this.type = 'TorusGeometry';
  21839. this.parameters = {
  21840. radius: radius,
  21841. tube: tube,
  21842. radialSegments: radialSegments,
  21843. tubularSegments: tubularSegments,
  21844. arc: arc
  21845. };
  21846. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  21847. }
  21848. TorusGeometry.prototype = Object.create( Geometry.prototype );
  21849. TorusGeometry.prototype.constructor = TorusGeometry;
  21850. /**
  21851. * @author Mugen87 / https://github.com/Mugen87
  21852. */
  21853. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  21854. BufferGeometry.call( this );
  21855. this.type = 'TorusBufferGeometry';
  21856. this.parameters = {
  21857. radius: radius,
  21858. tube: tube,
  21859. radialSegments: radialSegments,
  21860. tubularSegments: tubularSegments,
  21861. arc: arc
  21862. };
  21863. radius = radius || 100;
  21864. tube = tube || 40;
  21865. radialSegments = Math.floor( radialSegments ) || 8;
  21866. tubularSegments = Math.floor( tubularSegments ) || 6;
  21867. arc = arc || Math.PI * 2;
  21868. // buffers
  21869. var indices = [];
  21870. var vertices = [];
  21871. var normals = [];
  21872. var uvs = [];
  21873. // helper variables
  21874. var center = new Vector3();
  21875. var vertex = new Vector3();
  21876. var normal = new Vector3();
  21877. var j, i;
  21878. // generate vertices, normals and uvs
  21879. for ( j = 0; j <= radialSegments; j ++ ) {
  21880. for ( i = 0; i <= tubularSegments; i ++ ) {
  21881. var u = i / tubularSegments * arc;
  21882. var v = j / radialSegments * Math.PI * 2;
  21883. // vertex
  21884. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21885. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21886. vertex.z = tube * Math.sin( v );
  21887. vertices.push( vertex.x, vertex.y, vertex.z );
  21888. // normal
  21889. center.x = radius * Math.cos( u );
  21890. center.y = radius * Math.sin( u );
  21891. normal.subVectors( vertex, center ).normalize();
  21892. normals.push( normal.x, normal.y, normal.z );
  21893. // uv
  21894. uvs.push( i / tubularSegments );
  21895. uvs.push( j / radialSegments );
  21896. }
  21897. }
  21898. // generate indices
  21899. for ( j = 1; j <= radialSegments; j ++ ) {
  21900. for ( i = 1; i <= tubularSegments; i ++ ) {
  21901. // indices
  21902. var a = ( tubularSegments + 1 ) * j + i - 1;
  21903. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21904. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21905. var d = ( tubularSegments + 1 ) * j + i;
  21906. // faces
  21907. indices.push( a, b, d );
  21908. indices.push( b, c, d );
  21909. }
  21910. }
  21911. // build geometry
  21912. this.setIndex( indices );
  21913. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21914. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21915. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21916. }
  21917. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21918. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  21919. /**
  21920. * @author zz85 / http://www.lab4games.net/zz85/blog
  21921. * @author alteredq / http://alteredqualia.com/
  21922. *
  21923. * Text = 3D Text
  21924. *
  21925. * parameters = {
  21926. * font: <THREE.Font>, // font
  21927. *
  21928. * size: <float>, // size of the text
  21929. * height: <float>, // thickness to extrude text
  21930. * curveSegments: <int>, // number of points on the curves
  21931. *
  21932. * bevelEnabled: <bool>, // turn on bevel
  21933. * bevelThickness: <float>, // how deep into text bevel goes
  21934. * bevelSize: <float> // how far from text outline is bevel
  21935. * }
  21936. */
  21937. function TextGeometry( text, parameters ) {
  21938. parameters = parameters || {};
  21939. var font = parameters.font;
  21940. if ( ( font && font.isFont ) === false ) {
  21941. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  21942. return new Geometry();
  21943. }
  21944. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  21945. // translate parameters to ExtrudeGeometry API
  21946. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  21947. // defaults
  21948. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  21949. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  21950. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  21951. ExtrudeGeometry.call( this, shapes, parameters );
  21952. this.type = 'TextGeometry';
  21953. }
  21954. TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype );
  21955. TextGeometry.prototype.constructor = TextGeometry;
  21956. /**
  21957. * @author mrdoob / http://mrdoob.com/
  21958. */
  21959. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21960. Geometry.call( this );
  21961. this.type = 'SphereGeometry';
  21962. this.parameters = {
  21963. radius: radius,
  21964. widthSegments: widthSegments,
  21965. heightSegments: heightSegments,
  21966. phiStart: phiStart,
  21967. phiLength: phiLength,
  21968. thetaStart: thetaStart,
  21969. thetaLength: thetaLength
  21970. };
  21971. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  21972. }
  21973. SphereGeometry.prototype = Object.create( Geometry.prototype );
  21974. SphereGeometry.prototype.constructor = SphereGeometry;
  21975. /**
  21976. * @author benaadams / https://twitter.com/ben_a_adams
  21977. * @author Mugen87 / https://github.com/Mugen87
  21978. */
  21979. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21980. BufferGeometry.call( this );
  21981. this.type = 'SphereBufferGeometry';
  21982. this.parameters = {
  21983. radius: radius,
  21984. widthSegments: widthSegments,
  21985. heightSegments: heightSegments,
  21986. phiStart: phiStart,
  21987. phiLength: phiLength,
  21988. thetaStart: thetaStart,
  21989. thetaLength: thetaLength
  21990. };
  21991. radius = radius || 50;
  21992. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  21993. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  21994. phiStart = phiStart !== undefined ? phiStart : 0;
  21995. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  21996. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21997. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  21998. var thetaEnd = thetaStart + thetaLength;
  21999. var ix, iy;
  22000. var index = 0;
  22001. var grid = [];
  22002. var vertex = new Vector3();
  22003. var normal = new Vector3();
  22004. // buffers
  22005. var indices = [];
  22006. var vertices = [];
  22007. var normals = [];
  22008. var uvs = [];
  22009. // generate vertices, normals and uvs
  22010. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  22011. var verticesRow = [];
  22012. var v = iy / heightSegments;
  22013. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  22014. var u = ix / widthSegments;
  22015. // vertex
  22016. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22017. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22018. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22019. vertices.push( vertex.x, vertex.y, vertex.z );
  22020. // normal
  22021. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  22022. normals.push( normal.x, normal.y, normal.z );
  22023. // uv
  22024. uvs.push( u, 1 - v );
  22025. verticesRow.push( index ++ );
  22026. }
  22027. grid.push( verticesRow );
  22028. }
  22029. // indices
  22030. for ( iy = 0; iy < heightSegments; iy ++ ) {
  22031. for ( ix = 0; ix < widthSegments; ix ++ ) {
  22032. var a = grid[ iy ][ ix + 1 ];
  22033. var b = grid[ iy ][ ix ];
  22034. var c = grid[ iy + 1 ][ ix ];
  22035. var d = grid[ iy + 1 ][ ix + 1 ];
  22036. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22037. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  22038. }
  22039. }
  22040. // build geometry
  22041. this.setIndex( indices );
  22042. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22043. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22044. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22045. }
  22046. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22047. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  22048. /**
  22049. * @author Kaleb Murphy
  22050. */
  22051. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  22052. Geometry.call( this );
  22053. this.type = 'RingGeometry';
  22054. this.parameters = {
  22055. innerRadius: innerRadius,
  22056. outerRadius: outerRadius,
  22057. thetaSegments: thetaSegments,
  22058. phiSegments: phiSegments,
  22059. thetaStart: thetaStart,
  22060. thetaLength: thetaLength
  22061. };
  22062. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  22063. }
  22064. RingGeometry.prototype = Object.create( Geometry.prototype );
  22065. RingGeometry.prototype.constructor = RingGeometry;
  22066. /**
  22067. * @author Mugen87 / https://github.com/Mugen87
  22068. */
  22069. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  22070. BufferGeometry.call( this );
  22071. this.type = 'RingBufferGeometry';
  22072. this.parameters = {
  22073. innerRadius: innerRadius,
  22074. outerRadius: outerRadius,
  22075. thetaSegments: thetaSegments,
  22076. phiSegments: phiSegments,
  22077. thetaStart: thetaStart,
  22078. thetaLength: thetaLength
  22079. };
  22080. innerRadius = innerRadius || 20;
  22081. outerRadius = outerRadius || 50;
  22082. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22083. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22084. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  22085. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  22086. // buffers
  22087. var indices = [];
  22088. var vertices = [];
  22089. var normals = [];
  22090. var uvs = [];
  22091. // some helper variables
  22092. var segment;
  22093. var radius = innerRadius;
  22094. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  22095. var vertex = new Vector3();
  22096. var uv = new Vector2();
  22097. var j, i;
  22098. // generate vertices, normals and uvs
  22099. for ( j = 0; j <= phiSegments; j ++ ) {
  22100. for ( i = 0; i <= thetaSegments; i ++ ) {
  22101. // values are generate from the inside of the ring to the outside
  22102. segment = thetaStart + i / thetaSegments * thetaLength;
  22103. // vertex
  22104. vertex.x = radius * Math.cos( segment );
  22105. vertex.y = radius * Math.sin( segment );
  22106. vertices.push( vertex.x, vertex.y, vertex.z );
  22107. // normal
  22108. normals.push( 0, 0, 1 );
  22109. // uv
  22110. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  22111. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  22112. uvs.push( uv.x, uv.y );
  22113. }
  22114. // increase the radius for next row of vertices
  22115. radius += radiusStep;
  22116. }
  22117. // indices
  22118. for ( j = 0; j < phiSegments; j ++ ) {
  22119. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  22120. for ( i = 0; i < thetaSegments; i ++ ) {
  22121. segment = i + thetaSegmentLevel;
  22122. var a = segment;
  22123. var b = segment + thetaSegments + 1;
  22124. var c = segment + thetaSegments + 2;
  22125. var d = segment + 1;
  22126. // faces
  22127. indices.push( a, b, d );
  22128. indices.push( b, c, d );
  22129. }
  22130. }
  22131. // build geometry
  22132. this.setIndex( indices );
  22133. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22134. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22135. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22136. }
  22137. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22138. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  22139. /**
  22140. * @author astrodud / http://astrodud.isgreat.org/
  22141. * @author zz85 / https://github.com/zz85
  22142. * @author bhouston / http://clara.io
  22143. */
  22144. // points - to create a closed torus, one must use a set of points
  22145. // like so: [ a, b, c, d, a ], see first is the same as last.
  22146. // segments - the number of circumference segments to create
  22147. // phiStart - the starting radian
  22148. // phiLength - the radian (0 to 2PI) range of the lathed section
  22149. // 2PI is a closed lathe, less than 2PI is a portion.
  22150. function LatheGeometry( points, segments, phiStart, phiLength ) {
  22151. Geometry.call( this );
  22152. this.type = 'LatheGeometry';
  22153. this.parameters = {
  22154. points: points,
  22155. segments: segments,
  22156. phiStart: phiStart,
  22157. phiLength: phiLength
  22158. };
  22159. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  22160. this.mergeVertices();
  22161. }
  22162. LatheGeometry.prototype = Object.create( Geometry.prototype );
  22163. LatheGeometry.prototype.constructor = LatheGeometry;
  22164. /**
  22165. * @author Mugen87 / https://github.com/Mugen87
  22166. */
  22167. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  22168. BufferGeometry.call( this );
  22169. this.type = 'LatheBufferGeometry';
  22170. this.parameters = {
  22171. points: points,
  22172. segments: segments,
  22173. phiStart: phiStart,
  22174. phiLength: phiLength
  22175. };
  22176. segments = Math.floor( segments ) || 12;
  22177. phiStart = phiStart || 0;
  22178. phiLength = phiLength || Math.PI * 2;
  22179. // clamp phiLength so it's in range of [ 0, 2PI ]
  22180. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  22181. // buffers
  22182. var indices = [];
  22183. var vertices = [];
  22184. var uvs = [];
  22185. // helper variables
  22186. var base;
  22187. var inverseSegments = 1.0 / segments;
  22188. var vertex = new Vector3();
  22189. var uv = new Vector2();
  22190. var i, j;
  22191. // generate vertices and uvs
  22192. for ( i = 0; i <= segments; i ++ ) {
  22193. var phi = phiStart + i * inverseSegments * phiLength;
  22194. var sin = Math.sin( phi );
  22195. var cos = Math.cos( phi );
  22196. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  22197. // vertex
  22198. vertex.x = points[ j ].x * sin;
  22199. vertex.y = points[ j ].y;
  22200. vertex.z = points[ j ].x * cos;
  22201. vertices.push( vertex.x, vertex.y, vertex.z );
  22202. // uv
  22203. uv.x = i / segments;
  22204. uv.y = j / ( points.length - 1 );
  22205. uvs.push( uv.x, uv.y );
  22206. }
  22207. }
  22208. // indices
  22209. for ( i = 0; i < segments; i ++ ) {
  22210. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  22211. base = j + i * points.length;
  22212. var a = base;
  22213. var b = base + points.length;
  22214. var c = base + points.length + 1;
  22215. var d = base + 1;
  22216. // faces
  22217. indices.push( a, b, d );
  22218. indices.push( b, c, d );
  22219. }
  22220. }
  22221. // build geometry
  22222. this.setIndex( indices );
  22223. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22224. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22225. // generate normals
  22226. this.computeVertexNormals();
  22227. // if the geometry is closed, we need to average the normals along the seam.
  22228. // because the corresponding vertices are identical (but still have different UVs).
  22229. if ( phiLength === Math.PI * 2 ) {
  22230. var normals = this.attributes.normal.array;
  22231. var n1 = new Vector3();
  22232. var n2 = new Vector3();
  22233. var n = new Vector3();
  22234. // this is the buffer offset for the last line of vertices
  22235. base = segments * points.length * 3;
  22236. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  22237. // select the normal of the vertex in the first line
  22238. n1.x = normals[ j + 0 ];
  22239. n1.y = normals[ j + 1 ];
  22240. n1.z = normals[ j + 2 ];
  22241. // select the normal of the vertex in the last line
  22242. n2.x = normals[ base + j + 0 ];
  22243. n2.y = normals[ base + j + 1 ];
  22244. n2.z = normals[ base + j + 2 ];
  22245. // average normals
  22246. n.addVectors( n1, n2 ).normalize();
  22247. // assign the new values to both normals
  22248. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  22249. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  22250. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  22251. }
  22252. }
  22253. }
  22254. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22255. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  22256. /**
  22257. * @author mrdoob / http://mrdoob.com/
  22258. */
  22259. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22260. Geometry.call( this );
  22261. this.type = 'CylinderGeometry';
  22262. this.parameters = {
  22263. radiusTop: radiusTop,
  22264. radiusBottom: radiusBottom,
  22265. height: height,
  22266. radialSegments: radialSegments,
  22267. heightSegments: heightSegments,
  22268. openEnded: openEnded,
  22269. thetaStart: thetaStart,
  22270. thetaLength: thetaLength
  22271. };
  22272. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  22273. this.mergeVertices();
  22274. }
  22275. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  22276. CylinderGeometry.prototype.constructor = CylinderGeometry;
  22277. /**
  22278. * @author Mugen87 / https://github.com/Mugen87
  22279. */
  22280. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22281. BufferGeometry.call( this );
  22282. this.type = 'CylinderBufferGeometry';
  22283. this.parameters = {
  22284. radiusTop: radiusTop,
  22285. radiusBottom: radiusBottom,
  22286. height: height,
  22287. radialSegments: radialSegments,
  22288. heightSegments: heightSegments,
  22289. openEnded: openEnded,
  22290. thetaStart: thetaStart,
  22291. thetaLength: thetaLength
  22292. };
  22293. var scope = this;
  22294. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  22295. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  22296. height = height !== undefined ? height : 100;
  22297. radialSegments = Math.floor( radialSegments ) || 8;
  22298. heightSegments = Math.floor( heightSegments ) || 1;
  22299. openEnded = openEnded !== undefined ? openEnded : false;
  22300. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  22301. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  22302. // buffers
  22303. var indices = [];
  22304. var vertices = [];
  22305. var normals = [];
  22306. var uvs = [];
  22307. // helper variables
  22308. var index = 0;
  22309. var indexOffset = 0;
  22310. var indexArray = [];
  22311. var halfHeight = height / 2;
  22312. var groupStart = 0;
  22313. // generate geometry
  22314. generateTorso();
  22315. if ( openEnded === false ) {
  22316. if ( radiusTop > 0 ) generateCap( true );
  22317. if ( radiusBottom > 0 ) generateCap( false );
  22318. }
  22319. // build geometry
  22320. this.setIndex( indices );
  22321. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22322. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22323. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22324. function generateTorso() {
  22325. var x, y;
  22326. var normal = new Vector3();
  22327. var vertex = new Vector3();
  22328. var groupCount = 0;
  22329. // this will be used to calculate the normal
  22330. var slope = ( radiusBottom - radiusTop ) / height;
  22331. // generate vertices, normals and uvs
  22332. for ( y = 0; y <= heightSegments; y ++ ) {
  22333. var indexRow = [];
  22334. var v = y / heightSegments;
  22335. // calculate the radius of the current row
  22336. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22337. for ( x = 0; x <= radialSegments; x ++ ) {
  22338. var u = x / radialSegments;
  22339. var theta = u * thetaLength + thetaStart;
  22340. var sinTheta = Math.sin( theta );
  22341. var cosTheta = Math.cos( theta );
  22342. // vertex
  22343. vertex.x = radius * sinTheta;
  22344. vertex.y = - v * height + halfHeight;
  22345. vertex.z = radius * cosTheta;
  22346. vertices.push( vertex.x, vertex.y, vertex.z );
  22347. // normal
  22348. normal.set( sinTheta, slope, cosTheta ).normalize();
  22349. normals.push( normal.x, normal.y, normal.z );
  22350. // uv
  22351. uvs.push( u, 1 - v );
  22352. // save index of vertex in respective row
  22353. indexRow.push( index ++ );
  22354. }
  22355. // now save vertices of the row in our index array
  22356. indexArray.push( indexRow );
  22357. }
  22358. // generate indices
  22359. for ( x = 0; x < radialSegments; x ++ ) {
  22360. for ( y = 0; y < heightSegments; y ++ ) {
  22361. // we use the index array to access the correct indices
  22362. var a = indexArray[ y ][ x ];
  22363. var b = indexArray[ y + 1 ][ x ];
  22364. var c = indexArray[ y + 1 ][ x + 1 ];
  22365. var d = indexArray[ y ][ x + 1 ];
  22366. // faces
  22367. indices.push( a, b, d );
  22368. indices.push( b, c, d );
  22369. // update group counter
  22370. groupCount += 6;
  22371. }
  22372. }
  22373. // add a group to the geometry. this will ensure multi material support
  22374. scope.addGroup( groupStart, groupCount, 0 );
  22375. // calculate new start value for groups
  22376. groupStart += groupCount;
  22377. }
  22378. function generateCap( top ) {
  22379. var x, centerIndexStart, centerIndexEnd;
  22380. var uv = new Vector2();
  22381. var vertex = new Vector3();
  22382. var groupCount = 0;
  22383. var radius = ( top === true ) ? radiusTop : radiusBottom;
  22384. var sign = ( top === true ) ? 1 : - 1;
  22385. // save the index of the first center vertex
  22386. centerIndexStart = index;
  22387. // first we generate the center vertex data of the cap.
  22388. // because the geometry needs one set of uvs per face,
  22389. // we must generate a center vertex per face/segment
  22390. for ( x = 1; x <= radialSegments; x ++ ) {
  22391. // vertex
  22392. vertices.push( 0, halfHeight * sign, 0 );
  22393. // normal
  22394. normals.push( 0, sign, 0 );
  22395. // uv
  22396. uvs.push( 0.5, 0.5 );
  22397. // increase index
  22398. index ++;
  22399. }
  22400. // save the index of the last center vertex
  22401. centerIndexEnd = index;
  22402. // now we generate the surrounding vertices, normals and uvs
  22403. for ( x = 0; x <= radialSegments; x ++ ) {
  22404. var u = x / radialSegments;
  22405. var theta = u * thetaLength + thetaStart;
  22406. var cosTheta = Math.cos( theta );
  22407. var sinTheta = Math.sin( theta );
  22408. // vertex
  22409. vertex.x = radius * sinTheta;
  22410. vertex.y = halfHeight * sign;
  22411. vertex.z = radius * cosTheta;
  22412. vertices.push( vertex.x, vertex.y, vertex.z );
  22413. // normal
  22414. normals.push( 0, sign, 0 );
  22415. // uv
  22416. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22417. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22418. uvs.push( uv.x, uv.y );
  22419. // increase index
  22420. index ++;
  22421. }
  22422. // generate indices
  22423. for ( x = 0; x < radialSegments; x ++ ) {
  22424. var c = centerIndexStart + x;
  22425. var i = centerIndexEnd + x;
  22426. if ( top === true ) {
  22427. // face top
  22428. indices.push( i, i + 1, c );
  22429. } else {
  22430. // face bottom
  22431. indices.push( i + 1, i, c );
  22432. }
  22433. groupCount += 3;
  22434. }
  22435. // add a group to the geometry. this will ensure multi material support
  22436. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22437. // calculate new start value for groups
  22438. groupStart += groupCount;
  22439. }
  22440. }
  22441. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22442. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  22443. /**
  22444. * @author abelnation / http://github.com/abelnation
  22445. */
  22446. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22447. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22448. this.type = 'ConeGeometry';
  22449. this.parameters = {
  22450. radius: radius,
  22451. height: height,
  22452. radialSegments: radialSegments,
  22453. heightSegments: heightSegments,
  22454. openEnded: openEnded,
  22455. thetaStart: thetaStart,
  22456. thetaLength: thetaLength
  22457. };
  22458. }
  22459. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  22460. ConeGeometry.prototype.constructor = ConeGeometry;
  22461. /**
  22462. * @author: abelnation / http://github.com/abelnation
  22463. */
  22464. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22465. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22466. this.type = 'ConeBufferGeometry';
  22467. this.parameters = {
  22468. radius: radius,
  22469. height: height,
  22470. radialSegments: radialSegments,
  22471. heightSegments: heightSegments,
  22472. openEnded: openEnded,
  22473. thetaStart: thetaStart,
  22474. thetaLength: thetaLength
  22475. };
  22476. }
  22477. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  22478. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  22479. /**
  22480. * @author hughes
  22481. */
  22482. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  22483. Geometry.call( this );
  22484. this.type = 'CircleGeometry';
  22485. this.parameters = {
  22486. radius: radius,
  22487. segments: segments,
  22488. thetaStart: thetaStart,
  22489. thetaLength: thetaLength
  22490. };
  22491. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  22492. }
  22493. CircleGeometry.prototype = Object.create( Geometry.prototype );
  22494. CircleGeometry.prototype.constructor = CircleGeometry;
  22495. /**
  22496. * @author benaadams / https://twitter.com/ben_a_adams
  22497. * @author Mugen87 / https://github.com/Mugen87
  22498. */
  22499. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  22500. BufferGeometry.call( this );
  22501. this.type = 'CircleBufferGeometry';
  22502. this.parameters = {
  22503. radius: radius,
  22504. segments: segments,
  22505. thetaStart: thetaStart,
  22506. thetaLength: thetaLength
  22507. };
  22508. radius = radius || 50;
  22509. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  22510. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22511. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22512. // buffers
  22513. var indices = [];
  22514. var vertices = [];
  22515. var normals = [];
  22516. var uvs = [];
  22517. // helper variables
  22518. var i, s;
  22519. var vertex = new Vector3();
  22520. var uv = new Vector2();
  22521. // center point
  22522. vertices.push( 0, 0, 0 );
  22523. normals.push( 0, 0, 1 );
  22524. uvs.push( 0.5, 0.5 );
  22525. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22526. var segment = thetaStart + s / segments * thetaLength;
  22527. // vertex
  22528. vertex.x = radius * Math.cos( segment );
  22529. vertex.y = radius * Math.sin( segment );
  22530. vertices.push( vertex.x, vertex.y, vertex.z );
  22531. // normal
  22532. normals.push( 0, 0, 1 );
  22533. // uvs
  22534. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22535. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22536. uvs.push( uv.x, uv.y );
  22537. }
  22538. // indices
  22539. for ( i = 1; i <= segments; i ++ ) {
  22540. indices.push( i, i + 1, 0 );
  22541. }
  22542. // build geometry
  22543. this.setIndex( indices );
  22544. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22545. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22546. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22547. }
  22548. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22549. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  22550. var Geometries = Object.freeze({
  22551. WireframeGeometry: WireframeGeometry,
  22552. ParametricGeometry: ParametricGeometry,
  22553. ParametricBufferGeometry: ParametricBufferGeometry,
  22554. TetrahedronGeometry: TetrahedronGeometry,
  22555. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  22556. OctahedronGeometry: OctahedronGeometry,
  22557. OctahedronBufferGeometry: OctahedronBufferGeometry,
  22558. IcosahedronGeometry: IcosahedronGeometry,
  22559. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  22560. DodecahedronGeometry: DodecahedronGeometry,
  22561. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  22562. PolyhedronGeometry: PolyhedronGeometry,
  22563. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  22564. TubeGeometry: TubeGeometry,
  22565. TubeBufferGeometry: TubeBufferGeometry,
  22566. TorusKnotGeometry: TorusKnotGeometry,
  22567. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  22568. TorusGeometry: TorusGeometry,
  22569. TorusBufferGeometry: TorusBufferGeometry,
  22570. TextGeometry: TextGeometry,
  22571. SphereGeometry: SphereGeometry,
  22572. SphereBufferGeometry: SphereBufferGeometry,
  22573. RingGeometry: RingGeometry,
  22574. RingBufferGeometry: RingBufferGeometry,
  22575. PlaneGeometry: PlaneGeometry,
  22576. PlaneBufferGeometry: PlaneBufferGeometry,
  22577. LatheGeometry: LatheGeometry,
  22578. LatheBufferGeometry: LatheBufferGeometry,
  22579. ShapeGeometry: ShapeGeometry,
  22580. ShapeBufferGeometry: ShapeBufferGeometry,
  22581. ExtrudeGeometry: ExtrudeGeometry,
  22582. EdgesGeometry: EdgesGeometry,
  22583. ConeGeometry: ConeGeometry,
  22584. ConeBufferGeometry: ConeBufferGeometry,
  22585. CylinderGeometry: CylinderGeometry,
  22586. CylinderBufferGeometry: CylinderBufferGeometry,
  22587. CircleGeometry: CircleGeometry,
  22588. CircleBufferGeometry: CircleBufferGeometry,
  22589. BoxGeometry: BoxGeometry,
  22590. BoxBufferGeometry: BoxBufferGeometry
  22591. });
  22592. /**
  22593. * @author WestLangley / http://github.com/WestLangley
  22594. * @author zz85 / http://github.com/zz85
  22595. * @author bhouston / http://clara.io
  22596. *
  22597. * Creates an arrow for visualizing directions
  22598. *
  22599. * Parameters:
  22600. * dir - Vector3
  22601. * origin - Vector3
  22602. * length - Number
  22603. * color - color in hex value
  22604. * headLength - Number
  22605. * headWidth - Number
  22606. */
  22607. var lineGeometry;
  22608. var coneGeometry;
  22609. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  22610. // dir is assumed to be normalized
  22611. Object3D.call( this );
  22612. if ( color === undefined ) color = 0xffff00;
  22613. if ( length === undefined ) length = 1;
  22614. if ( headLength === undefined ) headLength = 0.2 * length;
  22615. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  22616. if ( lineGeometry === undefined ) {
  22617. lineGeometry = new BufferGeometry();
  22618. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  22619. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  22620. coneGeometry.translate( 0, - 0.5, 0 );
  22621. }
  22622. this.position.copy( origin );
  22623. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  22624. this.line.matrixAutoUpdate = false;
  22625. this.add( this.line );
  22626. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  22627. this.cone.matrixAutoUpdate = false;
  22628. this.add( this.cone );
  22629. this.setDirection( dir );
  22630. this.setLength( length, headLength, headWidth );
  22631. }
  22632. ArrowHelper.prototype = Object.create( Object3D.prototype );
  22633. ArrowHelper.prototype.constructor = ArrowHelper;
  22634. ArrowHelper.prototype.setDirection = ( function () {
  22635. var axis = new Vector3();
  22636. var radians;
  22637. return function setDirection( dir ) {
  22638. // dir is assumed to be normalized
  22639. if ( dir.y > 0.99999 ) {
  22640. this.quaternion.set( 0, 0, 0, 1 );
  22641. } else if ( dir.y < - 0.99999 ) {
  22642. this.quaternion.set( 1, 0, 0, 0 );
  22643. } else {
  22644. axis.set( dir.z, 0, - dir.x ).normalize();
  22645. radians = Math.acos( dir.y );
  22646. this.quaternion.setFromAxisAngle( axis, radians );
  22647. }
  22648. };
  22649. }() );
  22650. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  22651. if ( headLength === undefined ) headLength = 0.2 * length;
  22652. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  22653. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  22654. this.line.updateMatrix();
  22655. this.cone.scale.set( headWidth, headLength, headWidth );
  22656. this.cone.position.y = length;
  22657. this.cone.updateMatrix();
  22658. };
  22659. ArrowHelper.prototype.setColor = function ( color ) {
  22660. this.line.material.color.copy( color );
  22661. this.cone.material.color.copy( color );
  22662. };
  22663. /**
  22664. * @author sroucheray / http://sroucheray.org/
  22665. * @author mrdoob / http://mrdoob.com/
  22666. */
  22667. function AxisHelper( size ) {
  22668. size = size || 1;
  22669. var vertices = [
  22670. 0, 0, 0, size, 0, 0,
  22671. 0, 0, 0, 0, size, 0,
  22672. 0, 0, 0, 0, 0, size
  22673. ];
  22674. var colors = [
  22675. 1, 0, 0, 1, 0.6, 0,
  22676. 0, 1, 0, 0.6, 1, 0,
  22677. 0, 0, 1, 0, 0.6, 1
  22678. ];
  22679. var geometry = new BufferGeometry();
  22680. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22681. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  22682. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  22683. LineSegments.call( this, geometry, material );
  22684. }
  22685. AxisHelper.prototype = Object.create( LineSegments.prototype );
  22686. AxisHelper.prototype.constructor = AxisHelper;
  22687. /**
  22688. * @author alteredq / http://alteredqualia.com/
  22689. * @author Mugen87 / https://github.com/Mugen87
  22690. *
  22691. * - shows frustum, line of sight and up of the camera
  22692. * - suitable for fast updates
  22693. * - based on frustum visualization in lightgl.js shadowmap example
  22694. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  22695. */
  22696. function CameraHelper( camera ) {
  22697. var geometry = new BufferGeometry();
  22698. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  22699. var vertices = [];
  22700. var colors = [];
  22701. var pointMap = {};
  22702. // colors
  22703. var colorFrustum = new Color( 0xffaa00 );
  22704. var colorCone = new Color( 0xff0000 );
  22705. var colorUp = new Color( 0x00aaff );
  22706. var colorTarget = new Color( 0xffffff );
  22707. var colorCross = new Color( 0x333333 );
  22708. // near
  22709. addLine( "n1", "n2", colorFrustum );
  22710. addLine( "n2", "n4", colorFrustum );
  22711. addLine( "n4", "n3", colorFrustum );
  22712. addLine( "n3", "n1", colorFrustum );
  22713. // far
  22714. addLine( "f1", "f2", colorFrustum );
  22715. addLine( "f2", "f4", colorFrustum );
  22716. addLine( "f4", "f3", colorFrustum );
  22717. addLine( "f3", "f1", colorFrustum );
  22718. // sides
  22719. addLine( "n1", "f1", colorFrustum );
  22720. addLine( "n2", "f2", colorFrustum );
  22721. addLine( "n3", "f3", colorFrustum );
  22722. addLine( "n4", "f4", colorFrustum );
  22723. // cone
  22724. addLine( "p", "n1", colorCone );
  22725. addLine( "p", "n2", colorCone );
  22726. addLine( "p", "n3", colorCone );
  22727. addLine( "p", "n4", colorCone );
  22728. // up
  22729. addLine( "u1", "u2", colorUp );
  22730. addLine( "u2", "u3", colorUp );
  22731. addLine( "u3", "u1", colorUp );
  22732. // target
  22733. addLine( "c", "t", colorTarget );
  22734. addLine( "p", "c", colorCross );
  22735. // cross
  22736. addLine( "cn1", "cn2", colorCross );
  22737. addLine( "cn3", "cn4", colorCross );
  22738. addLine( "cf1", "cf2", colorCross );
  22739. addLine( "cf3", "cf4", colorCross );
  22740. function addLine( a, b, color ) {
  22741. addPoint( a, color );
  22742. addPoint( b, color );
  22743. }
  22744. function addPoint( id, color ) {
  22745. vertices.push( 0, 0, 0 );
  22746. colors.push( color.r, color.g, color.b );
  22747. if ( pointMap[ id ] === undefined ) {
  22748. pointMap[ id ] = [];
  22749. }
  22750. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  22751. }
  22752. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22753. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  22754. LineSegments.call( this, geometry, material );
  22755. this.camera = camera;
  22756. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  22757. this.matrix = camera.matrixWorld;
  22758. this.matrixAutoUpdate = false;
  22759. this.pointMap = pointMap;
  22760. this.update();
  22761. }
  22762. CameraHelper.prototype = Object.create( LineSegments.prototype );
  22763. CameraHelper.prototype.constructor = CameraHelper;
  22764. CameraHelper.prototype.update = function () {
  22765. var geometry, pointMap;
  22766. var vector = new Vector3();
  22767. var camera = new Camera();
  22768. function setPoint( point, x, y, z ) {
  22769. vector.set( x, y, z ).unproject( camera );
  22770. var points = pointMap[ point ];
  22771. if ( points !== undefined ) {
  22772. var position = geometry.getAttribute( 'position' );
  22773. for ( var i = 0, l = points.length; i < l; i ++ ) {
  22774. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  22775. }
  22776. }
  22777. }
  22778. return function update() {
  22779. geometry = this.geometry;
  22780. pointMap = this.pointMap;
  22781. var w = 1, h = 1;
  22782. // we need just camera projection matrix
  22783. // world matrix must be identity
  22784. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  22785. // center / target
  22786. setPoint( "c", 0, 0, - 1 );
  22787. setPoint( "t", 0, 0, 1 );
  22788. // near
  22789. setPoint( "n1", - w, - h, - 1 );
  22790. setPoint( "n2", w, - h, - 1 );
  22791. setPoint( "n3", - w, h, - 1 );
  22792. setPoint( "n4", w, h, - 1 );
  22793. // far
  22794. setPoint( "f1", - w, - h, 1 );
  22795. setPoint( "f2", w, - h, 1 );
  22796. setPoint( "f3", - w, h, 1 );
  22797. setPoint( "f4", w, h, 1 );
  22798. // up
  22799. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  22800. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  22801. setPoint( "u3", 0, h * 2, - 1 );
  22802. // cross
  22803. setPoint( "cf1", - w, 0, 1 );
  22804. setPoint( "cf2", w, 0, 1 );
  22805. setPoint( "cf3", 0, - h, 1 );
  22806. setPoint( "cf4", 0, h, 1 );
  22807. setPoint( "cn1", - w, 0, - 1 );
  22808. setPoint( "cn2", w, 0, - 1 );
  22809. setPoint( "cn3", 0, - h, - 1 );
  22810. setPoint( "cn4", 0, h, - 1 );
  22811. geometry.getAttribute( 'position' ).needsUpdate = true;
  22812. };
  22813. }();
  22814. /**
  22815. * @author alteredq / http://alteredqualia.com/
  22816. * @author mrdoob / http://mrdoob.com/
  22817. * @author WestLangley / http://github.com/WestLangley
  22818. */
  22819. function DirectionalLightHelper( light, size ) {
  22820. Object3D.call( this );
  22821. this.light = light;
  22822. this.light.updateMatrixWorld();
  22823. this.matrix = light.matrixWorld;
  22824. this.matrixAutoUpdate = false;
  22825. if ( size === undefined ) size = 1;
  22826. var geometry = new BufferGeometry();
  22827. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  22828. - size, size, 0,
  22829. size, size, 0,
  22830. size, - size, 0,
  22831. - size, - size, 0,
  22832. - size, size, 0
  22833. ], 3 ) );
  22834. var material = new LineBasicMaterial( { fog: false } );
  22835. this.add( new Line( geometry, material ) );
  22836. geometry = new BufferGeometry();
  22837. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  22838. this.add( new Line( geometry, material ));
  22839. this.update();
  22840. }
  22841. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  22842. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  22843. DirectionalLightHelper.prototype.dispose = function () {
  22844. var lightPlane = this.children[ 0 ];
  22845. var targetLine = this.children[ 1 ];
  22846. lightPlane.geometry.dispose();
  22847. lightPlane.material.dispose();
  22848. targetLine.geometry.dispose();
  22849. targetLine.material.dispose();
  22850. };
  22851. DirectionalLightHelper.prototype.update = function () {
  22852. var v1 = new Vector3();
  22853. var v2 = new Vector3();
  22854. var v3 = new Vector3();
  22855. return function update() {
  22856. v1.setFromMatrixPosition( this.light.matrixWorld );
  22857. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  22858. v3.subVectors( v2, v1 );
  22859. var lightPlane = this.children[ 0 ];
  22860. var targetLine = this.children[ 1 ];
  22861. lightPlane.lookAt( v3 );
  22862. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22863. targetLine.lookAt( v3 );
  22864. targetLine.scale.z = v3.length();
  22865. };
  22866. }();
  22867. /**
  22868. * @author mrdoob / http://mrdoob.com/
  22869. * @author WestLangley / http://github.com/WestLangley
  22870. */
  22871. function FaceNormalsHelper( object, size, hex, linewidth ) {
  22872. // FaceNormalsHelper only supports THREE.Geometry
  22873. this.object = object;
  22874. this.size = ( size !== undefined ) ? size : 1;
  22875. var color = ( hex !== undefined ) ? hex : 0xffff00;
  22876. var width = ( linewidth !== undefined ) ? linewidth : 1;
  22877. //
  22878. var nNormals = 0;
  22879. var objGeometry = this.object.geometry;
  22880. if ( objGeometry && objGeometry.isGeometry ) {
  22881. nNormals = objGeometry.faces.length;
  22882. } else {
  22883. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  22884. }
  22885. //
  22886. var geometry = new BufferGeometry();
  22887. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  22888. geometry.addAttribute( 'position', positions );
  22889. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  22890. //
  22891. this.matrixAutoUpdate = false;
  22892. this.update();
  22893. }
  22894. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  22895. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  22896. FaceNormalsHelper.prototype.update = ( function () {
  22897. var v1 = new Vector3();
  22898. var v2 = new Vector3();
  22899. var normalMatrix = new Matrix3();
  22900. return function update() {
  22901. this.object.updateMatrixWorld( true );
  22902. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  22903. var matrixWorld = this.object.matrixWorld;
  22904. var position = this.geometry.attributes.position;
  22905. //
  22906. var objGeometry = this.object.geometry;
  22907. var vertices = objGeometry.vertices;
  22908. var faces = objGeometry.faces;
  22909. var idx = 0;
  22910. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22911. var face = faces[ i ];
  22912. var normal = face.normal;
  22913. v1.copy( vertices[ face.a ] )
  22914. .add( vertices[ face.b ] )
  22915. .add( vertices[ face.c ] )
  22916. .divideScalar( 3 )
  22917. .applyMatrix4( matrixWorld );
  22918. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  22919. position.setXYZ( idx, v1.x, v1.y, v1.z );
  22920. idx = idx + 1;
  22921. position.setXYZ( idx, v2.x, v2.y, v2.z );
  22922. idx = idx + 1;
  22923. }
  22924. position.needsUpdate = true;
  22925. return this;
  22926. };
  22927. }() );
  22928. /**
  22929. * @author alteredq / http://alteredqualia.com/
  22930. * @author mrdoob / http://mrdoob.com/
  22931. * @author Mugen87 / https://github.com/Mugen87
  22932. */
  22933. function HemisphereLightHelper( light, size ) {
  22934. Object3D.call( this );
  22935. this.light = light;
  22936. this.light.updateMatrixWorld();
  22937. this.matrix = light.matrixWorld;
  22938. this.matrixAutoUpdate = false;
  22939. var geometry = new OctahedronBufferGeometry( size );
  22940. geometry.rotateY( Math.PI * 0.5 );
  22941. var material = new MeshBasicMaterial( { vertexColors: VertexColors, wireframe: true } );
  22942. var position = geometry.getAttribute( 'position' );
  22943. var colors = new Float32Array( position.count * 3 );
  22944. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  22945. this.add( new Mesh( geometry, material ) );
  22946. this.update();
  22947. }
  22948. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  22949. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  22950. HemisphereLightHelper.prototype.dispose = function () {
  22951. this.children[ 0 ].geometry.dispose();
  22952. this.children[ 0 ].material.dispose();
  22953. };
  22954. HemisphereLightHelper.prototype.update = function () {
  22955. var vector = new Vector3();
  22956. var color1 = new Color();
  22957. var color2 = new Color();
  22958. return function update() {
  22959. var mesh = this.children[ 0 ];
  22960. var colors = mesh.geometry.getAttribute( 'color' );
  22961. color1.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22962. color2.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  22963. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  22964. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  22965. colors.setXYZ( i, color.r, color.g, color.b );
  22966. }
  22967. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  22968. colors.needsUpdate = true;
  22969. };
  22970. }();
  22971. /**
  22972. * @author alteredq / http://alteredqualia.com/
  22973. * @author mrdoob / http://mrdoob.com/
  22974. */
  22975. function PointLightHelper( light, sphereSize ) {
  22976. this.light = light;
  22977. this.light.updateMatrixWorld();
  22978. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  22979. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  22980. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22981. Mesh.call( this, geometry, material );
  22982. this.matrix = this.light.matrixWorld;
  22983. this.matrixAutoUpdate = false;
  22984. /*
  22985. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  22986. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  22987. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  22988. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  22989. var d = light.distance;
  22990. if ( d === 0.0 ) {
  22991. this.lightDistance.visible = false;
  22992. } else {
  22993. this.lightDistance.scale.set( d, d, d );
  22994. }
  22995. this.add( this.lightDistance );
  22996. */
  22997. }
  22998. PointLightHelper.prototype = Object.create( Mesh.prototype );
  22999. PointLightHelper.prototype.constructor = PointLightHelper;
  23000. PointLightHelper.prototype.dispose = function () {
  23001. this.geometry.dispose();
  23002. this.material.dispose();
  23003. };
  23004. PointLightHelper.prototype.update = function () {
  23005. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23006. /*
  23007. var d = this.light.distance;
  23008. if ( d === 0.0 ) {
  23009. this.lightDistance.visible = false;
  23010. } else {
  23011. this.lightDistance.visible = true;
  23012. this.lightDistance.scale.set( d, d, d );
  23013. }
  23014. */
  23015. };
  23016. /**
  23017. * @author mrdoob / http://mrdoob.com/
  23018. * @author Mugen87 / http://github.com/Mugen87
  23019. * @author Hectate / http://www.github.com/Hectate
  23020. */
  23021. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  23022. radius = radius || 10;
  23023. radials = radials || 16;
  23024. circles = circles || 8;
  23025. divisions = divisions || 64;
  23026. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  23027. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  23028. var vertices = [];
  23029. var colors = [];
  23030. var x, z;
  23031. var v, i, j, r, color;
  23032. // create the radials
  23033. for ( i = 0; i <= radials; i ++ ) {
  23034. v = ( i / radials ) * ( Math.PI * 2 );
  23035. x = Math.sin( v ) * radius;
  23036. z = Math.cos( v ) * radius;
  23037. vertices.push( 0, 0, 0 );
  23038. vertices.push( x, 0, z );
  23039. color = ( i & 1 ) ? color1 : color2;
  23040. colors.push( color.r, color.g, color.b );
  23041. colors.push( color.r, color.g, color.b );
  23042. }
  23043. // create the circles
  23044. for ( i = 0; i <= circles; i ++ ) {
  23045. color = ( i & 1 ) ? color1 : color2;
  23046. r = radius - ( radius / circles * i );
  23047. for ( j = 0; j < divisions; j ++ ) {
  23048. // first vertex
  23049. v = ( j / divisions ) * ( Math.PI * 2 );
  23050. x = Math.sin( v ) * r;
  23051. z = Math.cos( v ) * r;
  23052. vertices.push( x, 0, z );
  23053. colors.push( color.r, color.g, color.b );
  23054. // second vertex
  23055. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  23056. x = Math.sin( v ) * r;
  23057. z = Math.cos( v ) * r;
  23058. vertices.push( x, 0, z );
  23059. colors.push( color.r, color.g, color.b );
  23060. }
  23061. }
  23062. var geometry = new BufferGeometry();
  23063. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23064. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  23065. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  23066. LineSegments.call( this, geometry, material );
  23067. }
  23068. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  23069. PolarGridHelper.prototype.constructor = PolarGridHelper;
  23070. /**
  23071. * @author abelnation / http://github.com/abelnation
  23072. * @author Mugen87 / http://github.com/Mugen87
  23073. */
  23074. function RectAreaLightHelper( light ) {
  23075. Object3D.call( this );
  23076. this.light = light;
  23077. this.light.updateMatrixWorld();
  23078. var materialFront = new MeshBasicMaterial( {
  23079. color: light.color,
  23080. fog: false
  23081. } );
  23082. var materialBack = new MeshBasicMaterial( {
  23083. color: light.color,
  23084. fog: false,
  23085. wireframe: true
  23086. } );
  23087. var geometry = new BufferGeometry();
  23088. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 6 * 3 ), 3 ) );
  23089. // shows the "front" of the light, e.g. where light comes from
  23090. this.add( new Mesh( geometry, materialFront ) );
  23091. // shows the "back" of the light, which does not emit light
  23092. this.add( new Mesh( geometry, materialBack ) );
  23093. this.update();
  23094. }
  23095. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  23096. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  23097. RectAreaLightHelper.prototype.dispose = function () {
  23098. this.children[ 0 ].geometry.dispose();
  23099. this.children[ 0 ].material.dispose();
  23100. this.children[ 1 ].geometry.dispose();
  23101. this.children[ 1 ].material.dispose();
  23102. };
  23103. RectAreaLightHelper.prototype.update = function () {
  23104. var vector1 = new Vector3();
  23105. var vector2 = new Vector3();
  23106. return function update() {
  23107. var mesh1 = this.children[ 0 ];
  23108. var mesh2 = this.children[ 1 ];
  23109. if ( this.light.target ) {
  23110. vector1.setFromMatrixPosition( this.light.matrixWorld );
  23111. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  23112. var lookVec = vector2.clone().sub( vector1 );
  23113. mesh1.lookAt( lookVec );
  23114. mesh2.lookAt( lookVec );
  23115. }
  23116. // update materials
  23117. mesh1.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23118. mesh2.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23119. // calculate new dimensions of the helper
  23120. var hx = this.light.width * 0.5;
  23121. var hy = this.light.height * 0.5;
  23122. // because the buffer attribute is shared over both geometries, we only have to update once
  23123. var position = mesh1.geometry.getAttribute( 'position' );
  23124. var array = position.array;
  23125. // first face
  23126. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  23127. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  23128. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  23129. // second face
  23130. array[ 9 ] = - hx; array[ 10 ] = hy; array[ 11 ] = 0;
  23131. array[ 12 ] = - hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  23132. array[ 15 ] = hx; array[ 16 ] = - hy; array[ 17 ] = 0;
  23133. position.needsUpdate = true;
  23134. };
  23135. }();
  23136. /**
  23137. * @author Sean Griffin / http://twitter.com/sgrif
  23138. * @author Michael Guerrero / http://realitymeltdown.com
  23139. * @author mrdoob / http://mrdoob.com/
  23140. * @author ikerr / http://verold.com
  23141. * @author Mugen87 / https://github.com/Mugen87
  23142. */
  23143. function SkeletonHelper( object ) {
  23144. this.bones = this.getBoneList( object );
  23145. var geometry = new BufferGeometry();
  23146. var vertices = [];
  23147. var colors = [];
  23148. var color1 = new Color( 0, 0, 1 );
  23149. var color2 = new Color( 0, 1, 0 );
  23150. for ( var i = 0; i < this.bones.length; i ++ ) {
  23151. var bone = this.bones[ i ];
  23152. if ( bone.parent && bone.parent.isBone ) {
  23153. vertices.push( 0, 0, 0 );
  23154. vertices.push( 0, 0, 0 );
  23155. colors.push( color1.r, color1.g, color1.b );
  23156. colors.push( color2.r, color2.g, color2.b );
  23157. }
  23158. }
  23159. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23160. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  23161. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  23162. LineSegments.call( this, geometry, material );
  23163. this.root = object;
  23164. this.matrix = object.matrixWorld;
  23165. this.matrixAutoUpdate = false;
  23166. this.update();
  23167. }
  23168. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  23169. SkeletonHelper.prototype.constructor = SkeletonHelper;
  23170. SkeletonHelper.prototype.getBoneList = function( object ) {
  23171. var boneList = [];
  23172. if ( object && object.isBone ) {
  23173. boneList.push( object );
  23174. }
  23175. for ( var i = 0; i < object.children.length; i ++ ) {
  23176. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  23177. }
  23178. return boneList;
  23179. };
  23180. SkeletonHelper.prototype.update = function () {
  23181. var vector = new Vector3();
  23182. var boneMatrix = new Matrix4();
  23183. var matrixWorldInv = new Matrix4();
  23184. return function update() {
  23185. var geometry = this.geometry;
  23186. var position = geometry.getAttribute( 'position' );
  23187. matrixWorldInv.getInverse( this.root.matrixWorld );
  23188. for ( var i = 0, j = 0; i < this.bones.length; i ++ ) {
  23189. var bone = this.bones[ i ];
  23190. if ( bone.parent && bone.parent.isBone ) {
  23191. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  23192. vector.setFromMatrixPosition( boneMatrix );
  23193. position.setXYZ( j, vector.x, vector.y, vector.z );
  23194. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  23195. vector.setFromMatrixPosition( boneMatrix );
  23196. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  23197. j += 2;
  23198. }
  23199. }
  23200. geometry.getAttribute( 'position' ).needsUpdate = true;
  23201. };
  23202. }();
  23203. /**
  23204. * @author alteredq / http://alteredqualia.com/
  23205. * @author mrdoob / http://mrdoob.com/
  23206. * @author WestLangley / http://github.com/WestLangley
  23207. */
  23208. function SpotLightHelper( light ) {
  23209. Object3D.call( this );
  23210. this.light = light;
  23211. this.light.updateMatrixWorld();
  23212. this.matrix = light.matrixWorld;
  23213. this.matrixAutoUpdate = false;
  23214. var geometry = new BufferGeometry();
  23215. var positions = [
  23216. 0, 0, 0, 0, 0, 1,
  23217. 0, 0, 0, 1, 0, 1,
  23218. 0, 0, 0, - 1, 0, 1,
  23219. 0, 0, 0, 0, 1, 1,
  23220. 0, 0, 0, 0, - 1, 1
  23221. ];
  23222. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  23223. var p1 = ( i / l ) * Math.PI * 2;
  23224. var p2 = ( j / l ) * Math.PI * 2;
  23225. positions.push(
  23226. Math.cos( p1 ), Math.sin( p1 ), 1,
  23227. Math.cos( p2 ), Math.sin( p2 ), 1
  23228. );
  23229. }
  23230. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  23231. var material = new LineBasicMaterial( { fog: false } );
  23232. this.cone = new LineSegments( geometry, material );
  23233. this.add( this.cone );
  23234. this.update();
  23235. }
  23236. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  23237. SpotLightHelper.prototype.constructor = SpotLightHelper;
  23238. SpotLightHelper.prototype.dispose = function () {
  23239. this.cone.geometry.dispose();
  23240. this.cone.material.dispose();
  23241. };
  23242. SpotLightHelper.prototype.update = function () {
  23243. var vector = new Vector3();
  23244. var vector2 = new Vector3();
  23245. return function update() {
  23246. var coneLength = this.light.distance ? this.light.distance : 1000;
  23247. var coneWidth = coneLength * Math.tan( this.light.angle );
  23248. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  23249. vector.setFromMatrixPosition( this.light.matrixWorld );
  23250. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  23251. this.cone.lookAt( vector2.sub( vector ) );
  23252. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23253. };
  23254. }();
  23255. /**
  23256. * @author mrdoob / http://mrdoob.com/
  23257. * @author WestLangley / http://github.com/WestLangley
  23258. */
  23259. function VertexNormalsHelper( object, size, hex, linewidth ) {
  23260. this.object = object;
  23261. this.size = ( size !== undefined ) ? size : 1;
  23262. var color = ( hex !== undefined ) ? hex : 0xff0000;
  23263. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23264. //
  23265. var nNormals = 0;
  23266. var objGeometry = this.object.geometry;
  23267. if ( objGeometry && objGeometry.isGeometry ) {
  23268. nNormals = objGeometry.faces.length * 3;
  23269. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  23270. nNormals = objGeometry.attributes.normal.count;
  23271. }
  23272. //
  23273. var geometry = new BufferGeometry();
  23274. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  23275. geometry.addAttribute( 'position', positions );
  23276. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  23277. //
  23278. this.matrixAutoUpdate = false;
  23279. this.update();
  23280. }
  23281. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  23282. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  23283. VertexNormalsHelper.prototype.update = ( function () {
  23284. var v1 = new Vector3();
  23285. var v2 = new Vector3();
  23286. var normalMatrix = new Matrix3();
  23287. return function update() {
  23288. var keys = [ 'a', 'b', 'c' ];
  23289. this.object.updateMatrixWorld( true );
  23290. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23291. var matrixWorld = this.object.matrixWorld;
  23292. var position = this.geometry.attributes.position;
  23293. //
  23294. var objGeometry = this.object.geometry;
  23295. if ( objGeometry && objGeometry.isGeometry ) {
  23296. var vertices = objGeometry.vertices;
  23297. var faces = objGeometry.faces;
  23298. var idx = 0;
  23299. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23300. var face = faces[ i ];
  23301. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  23302. var vertex = vertices[ face[ keys[ j ] ] ];
  23303. var normal = face.vertexNormals[ j ];
  23304. v1.copy( vertex ).applyMatrix4( matrixWorld );
  23305. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23306. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23307. idx = idx + 1;
  23308. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23309. idx = idx + 1;
  23310. }
  23311. }
  23312. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  23313. var objPos = objGeometry.attributes.position;
  23314. var objNorm = objGeometry.attributes.normal;
  23315. var idx = 0;
  23316. // for simplicity, ignore index and drawcalls, and render every normal
  23317. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  23318. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  23319. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  23320. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23321. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23322. idx = idx + 1;
  23323. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23324. idx = idx + 1;
  23325. }
  23326. }
  23327. position.needsUpdate = true;
  23328. return this;
  23329. };
  23330. }() );
  23331. /**
  23332. * @author mrdoob / http://mrdoob.com/
  23333. */
  23334. function AmbientLight( color, intensity ) {
  23335. Light.call( this, color, intensity );
  23336. this.type = 'AmbientLight';
  23337. this.castShadow = undefined;
  23338. }
  23339. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23340. constructor: AmbientLight,
  23341. isAmbientLight: true
  23342. } );
  23343. /**
  23344. * @author mrdoob / http://mrdoob.com/
  23345. */
  23346. function LightShadow( camera ) {
  23347. this.camera = camera;
  23348. this.bias = 0;
  23349. this.radius = 1;
  23350. this.mapSize = new Vector2( 512, 512 );
  23351. this.map = null;
  23352. this.matrix = new Matrix4();
  23353. }
  23354. Object.assign( LightShadow.prototype, {
  23355. copy: function ( source ) {
  23356. this.camera = source.camera.clone();
  23357. this.bias = source.bias;
  23358. this.radius = source.radius;
  23359. this.mapSize.copy( source.mapSize );
  23360. return this;
  23361. },
  23362. clone: function () {
  23363. return new this.constructor().copy( this );
  23364. },
  23365. toJSON: function () {
  23366. var object = {};
  23367. if ( this.bias !== 0 ) object.bias = this.bias;
  23368. if ( this.radius !== 1 ) object.radius = this.radius;
  23369. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  23370. object.camera = this.camera.toJSON( false ).object;
  23371. delete object.camera.matrix;
  23372. return object;
  23373. }
  23374. } );
  23375. /**
  23376. * @author mrdoob / http://mrdoob.com/
  23377. */
  23378. function DirectionalLightShadow( ) {
  23379. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  23380. }
  23381. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  23382. constructor: DirectionalLightShadow
  23383. } );
  23384. /**
  23385. * @author mrdoob / http://mrdoob.com/
  23386. * @author alteredq / http://alteredqualia.com/
  23387. */
  23388. function DirectionalLight( color, intensity ) {
  23389. Light.call( this, color, intensity );
  23390. this.type = 'DirectionalLight';
  23391. this.position.copy( Object3D.DefaultUp );
  23392. this.updateMatrix();
  23393. this.target = new Object3D();
  23394. this.shadow = new DirectionalLightShadow();
  23395. }
  23396. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23397. constructor: DirectionalLight,
  23398. isDirectionalLight: true,
  23399. copy: function ( source ) {
  23400. Light.prototype.copy.call( this, source );
  23401. this.target = source.target.clone();
  23402. this.shadow = source.shadow.clone();
  23403. return this;
  23404. }
  23405. } );
  23406. /**
  23407. * @author alteredq / http://alteredqualia.com/
  23408. */
  23409. function HemisphereLight( skyColor, groundColor, intensity ) {
  23410. Light.call( this, skyColor, intensity );
  23411. this.type = 'HemisphereLight';
  23412. this.castShadow = undefined;
  23413. this.position.copy( Object3D.DefaultUp );
  23414. this.updateMatrix();
  23415. this.groundColor = new Color( groundColor );
  23416. }
  23417. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23418. constructor: HemisphereLight,
  23419. isHemisphereLight: true,
  23420. copy: function ( source ) {
  23421. Light.prototype.copy.call( this, source );
  23422. this.groundColor.copy( source.groundColor );
  23423. return this;
  23424. }
  23425. } );
  23426. /**
  23427. * @author mrdoob / http://mrdoob.com/
  23428. */
  23429. function PointLight( color, intensity, distance, decay ) {
  23430. Light.call( this, color, intensity );
  23431. this.type = 'PointLight';
  23432. Object.defineProperty( this, 'power', {
  23433. get: function () {
  23434. // intensity = power per solid angle.
  23435. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  23436. return this.intensity * 4 * Math.PI;
  23437. },
  23438. set: function ( power ) {
  23439. // intensity = power per solid angle.
  23440. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  23441. this.intensity = power / ( 4 * Math.PI );
  23442. }
  23443. } );
  23444. this.distance = ( distance !== undefined ) ? distance : 0;
  23445. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  23446. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  23447. }
  23448. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23449. constructor: PointLight,
  23450. isPointLight: true,
  23451. copy: function ( source ) {
  23452. Light.prototype.copy.call( this, source );
  23453. this.distance = source.distance;
  23454. this.decay = source.decay;
  23455. this.shadow = source.shadow.clone();
  23456. return this;
  23457. }
  23458. } );
  23459. /**
  23460. * @author abelnation / http://github.com/abelnation
  23461. */
  23462. function RectAreaLight ( color, intensity, width, height ) {
  23463. Light.call( this, color, intensity );
  23464. this.type = 'RectAreaLight';
  23465. this.position.set( 0, 1, 0 );
  23466. this.updateMatrix();
  23467. this.width = ( width !== undefined ) ? width : 10;
  23468. this.height = ( height !== undefined ) ? height : 10;
  23469. // TODO (abelnation): distance/decay
  23470. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  23471. // TODO (abelnation): shadows
  23472. // this.shadow = new THREE.RectAreaLightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) );
  23473. }
  23474. // TODO (abelnation): RectAreaLight update when light shape is changed
  23475. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23476. constructor: RectAreaLight,
  23477. isRectAreaLight: true,
  23478. copy: function ( source ) {
  23479. Light.prototype.copy.call( this, source );
  23480. this.width = source.width;
  23481. this.height = source.height;
  23482. // this.shadow = source.shadow.clone();
  23483. return this;
  23484. }
  23485. } );
  23486. /**
  23487. * @author mrdoob / http://mrdoob.com/
  23488. */
  23489. function SpotLightShadow() {
  23490. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  23491. }
  23492. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  23493. constructor: SpotLightShadow,
  23494. isSpotLightShadow: true,
  23495. update: function ( light ) {
  23496. var fov = _Math.RAD2DEG * 2 * light.angle;
  23497. var aspect = this.mapSize.width / this.mapSize.height;
  23498. var far = light.distance || 500;
  23499. var camera = this.camera;
  23500. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  23501. camera.fov = fov;
  23502. camera.aspect = aspect;
  23503. camera.far = far;
  23504. camera.updateProjectionMatrix();
  23505. }
  23506. }
  23507. } );
  23508. /**
  23509. * @author alteredq / http://alteredqualia.com/
  23510. */
  23511. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  23512. Light.call( this, color, intensity );
  23513. this.type = 'SpotLight';
  23514. this.position.copy( Object3D.DefaultUp );
  23515. this.updateMatrix();
  23516. this.target = new Object3D();
  23517. Object.defineProperty( this, 'power', {
  23518. get: function () {
  23519. // intensity = power per solid angle.
  23520. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  23521. return this.intensity * Math.PI;
  23522. },
  23523. set: function ( power ) {
  23524. // intensity = power per solid angle.
  23525. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  23526. this.intensity = power / Math.PI;
  23527. }
  23528. } );
  23529. this.distance = ( distance !== undefined ) ? distance : 0;
  23530. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  23531. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  23532. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  23533. this.shadow = new SpotLightShadow();
  23534. }
  23535. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23536. constructor: SpotLight,
  23537. isSpotLight: true,
  23538. copy: function ( source ) {
  23539. Light.prototype.copy.call( this, source );
  23540. this.distance = source.distance;
  23541. this.angle = source.angle;
  23542. this.penumbra = source.penumbra;
  23543. this.decay = source.decay;
  23544. this.target = source.target.clone();
  23545. this.shadow = source.shadow.clone();
  23546. return this;
  23547. }
  23548. } );
  23549. /**
  23550. * @author bhouston / http://clara.io/
  23551. */
  23552. function AnimationLoader( manager ) {
  23553. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23554. }
  23555. Object.assign( AnimationLoader.prototype, {
  23556. load: function ( url, onLoad, onProgress, onError ) {
  23557. var scope = this;
  23558. var loader = new FileLoader( scope.manager );
  23559. loader.load( url, function ( text ) {
  23560. onLoad( scope.parse( JSON.parse( text ) ) );
  23561. }, onProgress, onError );
  23562. },
  23563. parse: function ( json, onLoad ) {
  23564. var animations = [];
  23565. for ( var i = 0; i < json.length; i ++ ) {
  23566. var clip = AnimationClip.parse( json[ i ] );
  23567. animations.push( clip );
  23568. }
  23569. onLoad( animations );
  23570. }
  23571. } );
  23572. /**
  23573. * @author mrdoob / http://mrdoob.com/
  23574. */
  23575. function BufferGeometryLoader( manager ) {
  23576. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23577. }
  23578. Object.assign( BufferGeometryLoader.prototype, {
  23579. load: function ( url, onLoad, onProgress, onError ) {
  23580. var scope = this;
  23581. var loader = new FileLoader( scope.manager );
  23582. loader.load( url, function ( text ) {
  23583. onLoad( scope.parse( JSON.parse( text ) ) );
  23584. }, onProgress, onError );
  23585. },
  23586. parse: function ( json ) {
  23587. var geometry = new BufferGeometry();
  23588. var index = json.data.index;
  23589. var TYPED_ARRAYS = {
  23590. 'Int8Array': Int8Array,
  23591. 'Uint8Array': Uint8Array,
  23592. 'Uint8ClampedArray': Uint8ClampedArray,
  23593. 'Int16Array': Int16Array,
  23594. 'Uint16Array': Uint16Array,
  23595. 'Int32Array': Int32Array,
  23596. 'Uint32Array': Uint32Array,
  23597. 'Float32Array': Float32Array,
  23598. 'Float64Array': Float64Array
  23599. };
  23600. if ( index !== undefined ) {
  23601. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  23602. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  23603. }
  23604. var attributes = json.data.attributes;
  23605. for ( var key in attributes ) {
  23606. var attribute = attributes[ key ];
  23607. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  23608. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  23609. }
  23610. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23611. if ( groups !== undefined ) {
  23612. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  23613. var group = groups[ i ];
  23614. geometry.addGroup( group.start, group.count, group.materialIndex );
  23615. }
  23616. }
  23617. var boundingSphere = json.data.boundingSphere;
  23618. if ( boundingSphere !== undefined ) {
  23619. var center = new Vector3();
  23620. if ( boundingSphere.center !== undefined ) {
  23621. center.fromArray( boundingSphere.center );
  23622. }
  23623. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  23624. }
  23625. return geometry;
  23626. }
  23627. } );
  23628. /**
  23629. * @author alteredq / http://alteredqualia.com/
  23630. */
  23631. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  23632. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  23633. this.image = { width: width, height: height };
  23634. this.mipmaps = mipmaps;
  23635. // no flipping for cube textures
  23636. // (also flipping doesn't work for compressed textures )
  23637. this.flipY = false;
  23638. // can't generate mipmaps for compressed textures
  23639. // mips must be embedded in DDS files
  23640. this.generateMipmaps = false;
  23641. }
  23642. CompressedTexture.prototype = Object.create( Texture.prototype );
  23643. CompressedTexture.prototype.constructor = CompressedTexture;
  23644. CompressedTexture.prototype.isCompressedTexture = true;
  23645. /**
  23646. * @author mrdoob / http://mrdoob.com/
  23647. *
  23648. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23649. */
  23650. function CompressedTextureLoader( manager ) {
  23651. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23652. // override in sub classes
  23653. this._parser = null;
  23654. }
  23655. Object.assign( CompressedTextureLoader.prototype, {
  23656. load: function ( url, onLoad, onProgress, onError ) {
  23657. var scope = this;
  23658. var images = [];
  23659. var texture = new CompressedTexture();
  23660. texture.image = images;
  23661. var loader = new FileLoader( this.manager );
  23662. loader.setPath( this.path );
  23663. loader.setResponseType( 'arraybuffer' );
  23664. function loadTexture( i ) {
  23665. loader.load( url[ i ], function ( buffer ) {
  23666. var texDatas = scope._parser( buffer, true );
  23667. images[ i ] = {
  23668. width: texDatas.width,
  23669. height: texDatas.height,
  23670. format: texDatas.format,
  23671. mipmaps: texDatas.mipmaps
  23672. };
  23673. loaded += 1;
  23674. if ( loaded === 6 ) {
  23675. if ( texDatas.mipmapCount === 1 )
  23676. texture.minFilter = LinearFilter;
  23677. texture.format = texDatas.format;
  23678. texture.needsUpdate = true;
  23679. if ( onLoad ) onLoad( texture );
  23680. }
  23681. }, onProgress, onError );
  23682. }
  23683. if ( Array.isArray( url ) ) {
  23684. var loaded = 0;
  23685. for ( var i = 0, il = url.length; i < il; ++ i ) {
  23686. loadTexture( i );
  23687. }
  23688. } else {
  23689. // compressed cubemap texture stored in a single DDS file
  23690. loader.load( url, function ( buffer ) {
  23691. var texDatas = scope._parser( buffer, true );
  23692. if ( texDatas.isCubemap ) {
  23693. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23694. for ( var f = 0; f < faces; f ++ ) {
  23695. images[ f ] = { mipmaps : [] };
  23696. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  23697. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  23698. images[ f ].format = texDatas.format;
  23699. images[ f ].width = texDatas.width;
  23700. images[ f ].height = texDatas.height;
  23701. }
  23702. }
  23703. } else {
  23704. texture.image.width = texDatas.width;
  23705. texture.image.height = texDatas.height;
  23706. texture.mipmaps = texDatas.mipmaps;
  23707. }
  23708. if ( texDatas.mipmapCount === 1 ) {
  23709. texture.minFilter = LinearFilter;
  23710. }
  23711. texture.format = texDatas.format;
  23712. texture.needsUpdate = true;
  23713. if ( onLoad ) onLoad( texture );
  23714. }, onProgress, onError );
  23715. }
  23716. return texture;
  23717. },
  23718. setPath: function ( value ) {
  23719. this.path = value;
  23720. return this;
  23721. }
  23722. } );
  23723. /**
  23724. * @author mrdoob / http://mrdoob.com/
  23725. */
  23726. function FontLoader( manager ) {
  23727. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23728. }
  23729. Object.assign( FontLoader.prototype, {
  23730. load: function ( url, onLoad, onProgress, onError ) {
  23731. var scope = this;
  23732. var loader = new FileLoader( this.manager );
  23733. loader.load( url, function ( text ) {
  23734. var json;
  23735. try {
  23736. json = JSON.parse( text );
  23737. } catch ( e ) {
  23738. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  23739. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  23740. }
  23741. var font = scope.parse( json );
  23742. if ( onLoad ) onLoad( font );
  23743. }, onProgress, onError );
  23744. },
  23745. parse: function ( json ) {
  23746. return new Font( json );
  23747. }
  23748. } );
  23749. /**
  23750. * @author mrdoob / http://mrdoob.com/
  23751. */
  23752. function ShadowMaterial() {
  23753. ShaderMaterial.call( this, {
  23754. uniforms: UniformsUtils.merge( [
  23755. UniformsLib.lights,
  23756. {
  23757. opacity: { value: 1.0 }
  23758. }
  23759. ] ),
  23760. vertexShader: ShaderChunk[ 'shadow_vert' ],
  23761. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  23762. } );
  23763. this.lights = true;
  23764. this.transparent = true;
  23765. Object.defineProperties( this, {
  23766. opacity: {
  23767. enumerable: true,
  23768. get: function () {
  23769. return this.uniforms.opacity.value;
  23770. },
  23771. set: function ( value ) {
  23772. this.uniforms.opacity.value = value;
  23773. }
  23774. }
  23775. } );
  23776. }
  23777. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  23778. ShadowMaterial.prototype.constructor = ShadowMaterial;
  23779. ShadowMaterial.prototype.isShadowMaterial = true;
  23780. /**
  23781. * @author mrdoob / http://mrdoob.com/
  23782. */
  23783. function RawShaderMaterial( parameters ) {
  23784. ShaderMaterial.call( this, parameters );
  23785. this.type = 'RawShaderMaterial';
  23786. }
  23787. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  23788. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  23789. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  23790. /**
  23791. * @author WestLangley / http://github.com/WestLangley
  23792. *
  23793. * parameters = {
  23794. * color: <hex>,
  23795. * roughness: <float>,
  23796. * metalness: <float>,
  23797. * opacity: <float>,
  23798. *
  23799. * map: new THREE.Texture( <Image> ),
  23800. *
  23801. * lightMap: new THREE.Texture( <Image> ),
  23802. * lightMapIntensity: <float>
  23803. *
  23804. * aoMap: new THREE.Texture( <Image> ),
  23805. * aoMapIntensity: <float>
  23806. *
  23807. * emissive: <hex>,
  23808. * emissiveIntensity: <float>
  23809. * emissiveMap: new THREE.Texture( <Image> ),
  23810. *
  23811. * bumpMap: new THREE.Texture( <Image> ),
  23812. * bumpScale: <float>,
  23813. *
  23814. * normalMap: new THREE.Texture( <Image> ),
  23815. * normalScale: <Vector2>,
  23816. *
  23817. * displacementMap: new THREE.Texture( <Image> ),
  23818. * displacementScale: <float>,
  23819. * displacementBias: <float>,
  23820. *
  23821. * roughnessMap: new THREE.Texture( <Image> ),
  23822. *
  23823. * metalnessMap: new THREE.Texture( <Image> ),
  23824. *
  23825. * alphaMap: new THREE.Texture( <Image> ),
  23826. *
  23827. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  23828. * envMapIntensity: <float>
  23829. *
  23830. * refractionRatio: <float>,
  23831. *
  23832. * wireframe: <boolean>,
  23833. * wireframeLinewidth: <float>,
  23834. *
  23835. * skinning: <bool>,
  23836. * morphTargets: <bool>,
  23837. * morphNormals: <bool>
  23838. * }
  23839. */
  23840. function MeshStandardMaterial( parameters ) {
  23841. Material.call( this );
  23842. this.defines = { 'STANDARD': '' };
  23843. this.type = 'MeshStandardMaterial';
  23844. this.color = new Color( 0xffffff ); // diffuse
  23845. this.roughness = 0.5;
  23846. this.metalness = 0.5;
  23847. this.map = null;
  23848. this.lightMap = null;
  23849. this.lightMapIntensity = 1.0;
  23850. this.aoMap = null;
  23851. this.aoMapIntensity = 1.0;
  23852. this.emissive = new Color( 0x000000 );
  23853. this.emissiveIntensity = 1.0;
  23854. this.emissiveMap = null;
  23855. this.bumpMap = null;
  23856. this.bumpScale = 1;
  23857. this.normalMap = null;
  23858. this.normalScale = new Vector2( 1, 1 );
  23859. this.displacementMap = null;
  23860. this.displacementScale = 1;
  23861. this.displacementBias = 0;
  23862. this.roughnessMap = null;
  23863. this.metalnessMap = null;
  23864. this.alphaMap = null;
  23865. this.envMap = null;
  23866. this.envMapIntensity = 1.0;
  23867. this.refractionRatio = 0.98;
  23868. this.wireframe = false;
  23869. this.wireframeLinewidth = 1;
  23870. this.wireframeLinecap = 'round';
  23871. this.wireframeLinejoin = 'round';
  23872. this.skinning = false;
  23873. this.morphTargets = false;
  23874. this.morphNormals = false;
  23875. this.setValues( parameters );
  23876. }
  23877. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  23878. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  23879. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  23880. MeshStandardMaterial.prototype.copy = function ( source ) {
  23881. Material.prototype.copy.call( this, source );
  23882. this.defines = { 'STANDARD': '' };
  23883. this.color.copy( source.color );
  23884. this.roughness = source.roughness;
  23885. this.metalness = source.metalness;
  23886. this.map = source.map;
  23887. this.lightMap = source.lightMap;
  23888. this.lightMapIntensity = source.lightMapIntensity;
  23889. this.aoMap = source.aoMap;
  23890. this.aoMapIntensity = source.aoMapIntensity;
  23891. this.emissive.copy( source.emissive );
  23892. this.emissiveMap = source.emissiveMap;
  23893. this.emissiveIntensity = source.emissiveIntensity;
  23894. this.bumpMap = source.bumpMap;
  23895. this.bumpScale = source.bumpScale;
  23896. this.normalMap = source.normalMap;
  23897. this.normalScale.copy( source.normalScale );
  23898. this.displacementMap = source.displacementMap;
  23899. this.displacementScale = source.displacementScale;
  23900. this.displacementBias = source.displacementBias;
  23901. this.roughnessMap = source.roughnessMap;
  23902. this.metalnessMap = source.metalnessMap;
  23903. this.alphaMap = source.alphaMap;
  23904. this.envMap = source.envMap;
  23905. this.envMapIntensity = source.envMapIntensity;
  23906. this.refractionRatio = source.refractionRatio;
  23907. this.wireframe = source.wireframe;
  23908. this.wireframeLinewidth = source.wireframeLinewidth;
  23909. this.wireframeLinecap = source.wireframeLinecap;
  23910. this.wireframeLinejoin = source.wireframeLinejoin;
  23911. this.skinning = source.skinning;
  23912. this.morphTargets = source.morphTargets;
  23913. this.morphNormals = source.morphNormals;
  23914. return this;
  23915. };
  23916. /**
  23917. * @author WestLangley / http://github.com/WestLangley
  23918. *
  23919. * parameters = {
  23920. * reflectivity: <float>
  23921. * }
  23922. */
  23923. function MeshPhysicalMaterial( parameters ) {
  23924. MeshStandardMaterial.call( this );
  23925. this.defines = { 'PHYSICAL': '' };
  23926. this.type = 'MeshPhysicalMaterial';
  23927. this.reflectivity = 0.5; // maps to F0 = 0.04
  23928. this.clearCoat = 0.0;
  23929. this.clearCoatRoughness = 0.0;
  23930. this.setValues( parameters );
  23931. }
  23932. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  23933. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  23934. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  23935. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  23936. MeshStandardMaterial.prototype.copy.call( this, source );
  23937. this.defines = { 'PHYSICAL': '' };
  23938. this.reflectivity = source.reflectivity;
  23939. this.clearCoat = source.clearCoat;
  23940. this.clearCoatRoughness = source.clearCoatRoughness;
  23941. return this;
  23942. };
  23943. /**
  23944. * @author takahirox / http://github.com/takahirox
  23945. *
  23946. * parameters = {
  23947. * gradientMap: new THREE.Texture( <Image> )
  23948. * }
  23949. */
  23950. function MeshToonMaterial( parameters ) {
  23951. MeshPhongMaterial.call( this );
  23952. this.defines = { 'TOON': '' };
  23953. this.type = 'MeshToonMaterial';
  23954. this.gradientMap = null;
  23955. this.setValues( parameters );
  23956. }
  23957. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  23958. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  23959. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  23960. MeshToonMaterial.prototype.copy = function ( source ) {
  23961. MeshPhongMaterial.prototype.copy.call( this, source );
  23962. this.gradientMap = source.gradientMap;
  23963. return this;
  23964. };
  23965. /**
  23966. * @author mrdoob / http://mrdoob.com/
  23967. * @author WestLangley / http://github.com/WestLangley
  23968. *
  23969. * parameters = {
  23970. * opacity: <float>,
  23971. *
  23972. * bumpMap: new THREE.Texture( <Image> ),
  23973. * bumpScale: <float>,
  23974. *
  23975. * normalMap: new THREE.Texture( <Image> ),
  23976. * normalScale: <Vector2>,
  23977. *
  23978. * displacementMap: new THREE.Texture( <Image> ),
  23979. * displacementScale: <float>,
  23980. * displacementBias: <float>,
  23981. *
  23982. * wireframe: <boolean>,
  23983. * wireframeLinewidth: <float>
  23984. *
  23985. * skinning: <bool>,
  23986. * morphTargets: <bool>,
  23987. * morphNormals: <bool>
  23988. * }
  23989. */
  23990. function MeshNormalMaterial( parameters ) {
  23991. Material.call( this, parameters );
  23992. this.type = 'MeshNormalMaterial';
  23993. this.bumpMap = null;
  23994. this.bumpScale = 1;
  23995. this.normalMap = null;
  23996. this.normalScale = new Vector2( 1, 1 );
  23997. this.displacementMap = null;
  23998. this.displacementScale = 1;
  23999. this.displacementBias = 0;
  24000. this.wireframe = false;
  24001. this.wireframeLinewidth = 1;
  24002. this.fog = false;
  24003. this.lights = false;
  24004. this.skinning = false;
  24005. this.morphTargets = false;
  24006. this.morphNormals = false;
  24007. this.setValues( parameters );
  24008. }
  24009. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  24010. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  24011. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  24012. MeshNormalMaterial.prototype.copy = function ( source ) {
  24013. Material.prototype.copy.call( this, source );
  24014. this.bumpMap = source.bumpMap;
  24015. this.bumpScale = source.bumpScale;
  24016. this.normalMap = source.normalMap;
  24017. this.normalScale.copy( source.normalScale );
  24018. this.displacementMap = source.displacementMap;
  24019. this.displacementScale = source.displacementScale;
  24020. this.displacementBias = source.displacementBias;
  24021. this.wireframe = source.wireframe;
  24022. this.wireframeLinewidth = source.wireframeLinewidth;
  24023. this.skinning = source.skinning;
  24024. this.morphTargets = source.morphTargets;
  24025. this.morphNormals = source.morphNormals;
  24026. return this;
  24027. };
  24028. /**
  24029. * @author mrdoob / http://mrdoob.com/
  24030. * @author alteredq / http://alteredqualia.com/
  24031. *
  24032. * parameters = {
  24033. * color: <hex>,
  24034. * opacity: <float>,
  24035. *
  24036. * map: new THREE.Texture( <Image> ),
  24037. *
  24038. * lightMap: new THREE.Texture( <Image> ),
  24039. * lightMapIntensity: <float>
  24040. *
  24041. * aoMap: new THREE.Texture( <Image> ),
  24042. * aoMapIntensity: <float>
  24043. *
  24044. * emissive: <hex>,
  24045. * emissiveIntensity: <float>
  24046. * emissiveMap: new THREE.Texture( <Image> ),
  24047. *
  24048. * specularMap: new THREE.Texture( <Image> ),
  24049. *
  24050. * alphaMap: new THREE.Texture( <Image> ),
  24051. *
  24052. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  24053. * combine: THREE.Multiply,
  24054. * reflectivity: <float>,
  24055. * refractionRatio: <float>,
  24056. *
  24057. * wireframe: <boolean>,
  24058. * wireframeLinewidth: <float>,
  24059. *
  24060. * skinning: <bool>,
  24061. * morphTargets: <bool>,
  24062. * morphNormals: <bool>
  24063. * }
  24064. */
  24065. function MeshLambertMaterial( parameters ) {
  24066. Material.call( this );
  24067. this.type = 'MeshLambertMaterial';
  24068. this.color = new Color( 0xffffff ); // diffuse
  24069. this.map = null;
  24070. this.lightMap = null;
  24071. this.lightMapIntensity = 1.0;
  24072. this.aoMap = null;
  24073. this.aoMapIntensity = 1.0;
  24074. this.emissive = new Color( 0x000000 );
  24075. this.emissiveIntensity = 1.0;
  24076. this.emissiveMap = null;
  24077. this.specularMap = null;
  24078. this.alphaMap = null;
  24079. this.envMap = null;
  24080. this.combine = MultiplyOperation;
  24081. this.reflectivity = 1;
  24082. this.refractionRatio = 0.98;
  24083. this.wireframe = false;
  24084. this.wireframeLinewidth = 1;
  24085. this.wireframeLinecap = 'round';
  24086. this.wireframeLinejoin = 'round';
  24087. this.skinning = false;
  24088. this.morphTargets = false;
  24089. this.morphNormals = false;
  24090. this.setValues( parameters );
  24091. }
  24092. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  24093. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  24094. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  24095. MeshLambertMaterial.prototype.copy = function ( source ) {
  24096. Material.prototype.copy.call( this, source );
  24097. this.color.copy( source.color );
  24098. this.map = source.map;
  24099. this.lightMap = source.lightMap;
  24100. this.lightMapIntensity = source.lightMapIntensity;
  24101. this.aoMap = source.aoMap;
  24102. this.aoMapIntensity = source.aoMapIntensity;
  24103. this.emissive.copy( source.emissive );
  24104. this.emissiveMap = source.emissiveMap;
  24105. this.emissiveIntensity = source.emissiveIntensity;
  24106. this.specularMap = source.specularMap;
  24107. this.alphaMap = source.alphaMap;
  24108. this.envMap = source.envMap;
  24109. this.combine = source.combine;
  24110. this.reflectivity = source.reflectivity;
  24111. this.refractionRatio = source.refractionRatio;
  24112. this.wireframe = source.wireframe;
  24113. this.wireframeLinewidth = source.wireframeLinewidth;
  24114. this.wireframeLinecap = source.wireframeLinecap;
  24115. this.wireframeLinejoin = source.wireframeLinejoin;
  24116. this.skinning = source.skinning;
  24117. this.morphTargets = source.morphTargets;
  24118. this.morphNormals = source.morphNormals;
  24119. return this;
  24120. };
  24121. /**
  24122. * @author alteredq / http://alteredqualia.com/
  24123. *
  24124. * parameters = {
  24125. * color: <hex>,
  24126. * opacity: <float>,
  24127. *
  24128. * linewidth: <float>,
  24129. *
  24130. * scale: <float>,
  24131. * dashSize: <float>,
  24132. * gapSize: <float>
  24133. * }
  24134. */
  24135. function LineDashedMaterial( parameters ) {
  24136. Material.call( this );
  24137. this.type = 'LineDashedMaterial';
  24138. this.color = new Color( 0xffffff );
  24139. this.linewidth = 1;
  24140. this.scale = 1;
  24141. this.dashSize = 3;
  24142. this.gapSize = 1;
  24143. this.lights = false;
  24144. this.setValues( parameters );
  24145. }
  24146. LineDashedMaterial.prototype = Object.create( Material.prototype );
  24147. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  24148. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  24149. LineDashedMaterial.prototype.copy = function ( source ) {
  24150. Material.prototype.copy.call( this, source );
  24151. this.color.copy( source.color );
  24152. this.linewidth = source.linewidth;
  24153. this.scale = source.scale;
  24154. this.dashSize = source.dashSize;
  24155. this.gapSize = source.gapSize;
  24156. return this;
  24157. };
  24158. var Materials = Object.freeze({
  24159. ShadowMaterial: ShadowMaterial,
  24160. SpriteMaterial: SpriteMaterial,
  24161. RawShaderMaterial: RawShaderMaterial,
  24162. ShaderMaterial: ShaderMaterial,
  24163. PointsMaterial: PointsMaterial,
  24164. MultiMaterial: MultiMaterial,
  24165. MeshPhysicalMaterial: MeshPhysicalMaterial,
  24166. MeshStandardMaterial: MeshStandardMaterial,
  24167. MeshPhongMaterial: MeshPhongMaterial,
  24168. MeshToonMaterial: MeshToonMaterial,
  24169. MeshNormalMaterial: MeshNormalMaterial,
  24170. MeshLambertMaterial: MeshLambertMaterial,
  24171. MeshDepthMaterial: MeshDepthMaterial,
  24172. MeshBasicMaterial: MeshBasicMaterial,
  24173. LineDashedMaterial: LineDashedMaterial,
  24174. LineBasicMaterial: LineBasicMaterial,
  24175. Material: Material
  24176. });
  24177. /**
  24178. * @author mrdoob / http://mrdoob.com/
  24179. */
  24180. function MaterialLoader( manager ) {
  24181. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24182. this.textures = {};
  24183. }
  24184. Object.assign( MaterialLoader.prototype, {
  24185. load: function ( url, onLoad, onProgress, onError ) {
  24186. var scope = this;
  24187. var loader = new FileLoader( scope.manager );
  24188. loader.load( url, function ( text ) {
  24189. onLoad( scope.parse( JSON.parse( text ) ) );
  24190. }, onProgress, onError );
  24191. },
  24192. setTextures: function ( value ) {
  24193. this.textures = value;
  24194. },
  24195. parse: function ( json ) {
  24196. var textures = this.textures;
  24197. function getTexture( name ) {
  24198. if ( textures[ name ] === undefined ) {
  24199. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24200. }
  24201. return textures[ name ];
  24202. }
  24203. var material = new Materials[ json.type ]();
  24204. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24205. if ( json.name !== undefined ) material.name = json.name;
  24206. if ( json.color !== undefined ) material.color.setHex( json.color );
  24207. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24208. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24209. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24210. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  24211. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24212. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  24213. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  24214. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  24215. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24216. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24217. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  24218. if ( json.fog !== undefined ) material.fog = json.fog;
  24219. if ( json.shading !== undefined ) material.shading = json.shading;
  24220. if ( json.blending !== undefined ) material.blending = json.blending;
  24221. if ( json.side !== undefined ) material.side = json.side;
  24222. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24223. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24224. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24225. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24226. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24227. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24228. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24229. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24230. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24231. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24232. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  24233. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  24234. // for PointsMaterial
  24235. if ( json.size !== undefined ) material.size = json.size;
  24236. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24237. // maps
  24238. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24239. if ( json.alphaMap !== undefined ) {
  24240. material.alphaMap = getTexture( json.alphaMap );
  24241. material.transparent = true;
  24242. }
  24243. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24244. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24245. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24246. if ( json.normalScale !== undefined ) {
  24247. var normalScale = json.normalScale;
  24248. if ( Array.isArray( normalScale ) === false ) {
  24249. // Blender exporter used to export a scalar. See #7459
  24250. normalScale = [ normalScale, normalScale ];
  24251. }
  24252. material.normalScale = new Vector2().fromArray( normalScale );
  24253. }
  24254. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24255. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24256. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24257. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24258. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24259. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24260. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24261. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24262. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24263. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24264. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24265. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24266. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24267. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24268. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24269. // MultiMaterial
  24270. if ( json.materials !== undefined ) {
  24271. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  24272. material.materials.push( this.parse( json.materials[ i ] ) );
  24273. }
  24274. }
  24275. return material;
  24276. }
  24277. } );
  24278. /**
  24279. * @author alteredq / http://alteredqualia.com/
  24280. */
  24281. function Loader() {
  24282. this.onLoadStart = function () {};
  24283. this.onLoadProgress = function () {};
  24284. this.onLoadComplete = function () {};
  24285. }
  24286. Loader.prototype = {
  24287. constructor: Loader,
  24288. crossOrigin: undefined,
  24289. extractUrlBase: function ( url ) {
  24290. var parts = url.split( '/' );
  24291. if ( parts.length === 1 ) return './';
  24292. parts.pop();
  24293. return parts.join( '/' ) + '/';
  24294. },
  24295. initMaterials: function ( materials, texturePath, crossOrigin ) {
  24296. var array = [];
  24297. for ( var i = 0; i < materials.length; ++ i ) {
  24298. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  24299. }
  24300. return array;
  24301. },
  24302. createMaterial: ( function () {
  24303. var BlendingMode = {
  24304. NoBlending: NoBlending,
  24305. NormalBlending: NormalBlending,
  24306. AdditiveBlending: AdditiveBlending,
  24307. SubtractiveBlending: SubtractiveBlending,
  24308. MultiplyBlending: MultiplyBlending,
  24309. CustomBlending: CustomBlending
  24310. };
  24311. var color, textureLoader, materialLoader;
  24312. return function createMaterial( m, texturePath, crossOrigin ) {
  24313. if ( color === undefined ) color = new Color();
  24314. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  24315. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  24316. // convert from old material format
  24317. var textures = {};
  24318. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  24319. var fullPath = texturePath + path;
  24320. var loader = Loader.Handlers.get( fullPath );
  24321. var texture;
  24322. if ( loader !== null ) {
  24323. texture = loader.load( fullPath );
  24324. } else {
  24325. textureLoader.setCrossOrigin( crossOrigin );
  24326. texture = textureLoader.load( fullPath );
  24327. }
  24328. if ( repeat !== undefined ) {
  24329. texture.repeat.fromArray( repeat );
  24330. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  24331. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  24332. }
  24333. if ( offset !== undefined ) {
  24334. texture.offset.fromArray( offset );
  24335. }
  24336. if ( wrap !== undefined ) {
  24337. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  24338. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  24339. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  24340. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  24341. }
  24342. if ( anisotropy !== undefined ) {
  24343. texture.anisotropy = anisotropy;
  24344. }
  24345. var uuid = _Math.generateUUID();
  24346. textures[ uuid ] = texture;
  24347. return uuid;
  24348. }
  24349. //
  24350. var json = {
  24351. uuid: _Math.generateUUID(),
  24352. type: 'MeshLambertMaterial'
  24353. };
  24354. for ( var name in m ) {
  24355. var value = m[ name ];
  24356. switch ( name ) {
  24357. case 'DbgColor':
  24358. case 'DbgIndex':
  24359. case 'opticalDensity':
  24360. case 'illumination':
  24361. break;
  24362. case 'DbgName':
  24363. json.name = value;
  24364. break;
  24365. case 'blending':
  24366. json.blending = BlendingMode[ value ];
  24367. break;
  24368. case 'colorAmbient':
  24369. case 'mapAmbient':
  24370. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  24371. break;
  24372. case 'colorDiffuse':
  24373. json.color = color.fromArray( value ).getHex();
  24374. break;
  24375. case 'colorSpecular':
  24376. json.specular = color.fromArray( value ).getHex();
  24377. break;
  24378. case 'colorEmissive':
  24379. json.emissive = color.fromArray( value ).getHex();
  24380. break;
  24381. case 'specularCoef':
  24382. json.shininess = value;
  24383. break;
  24384. case 'shading':
  24385. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  24386. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  24387. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  24388. break;
  24389. case 'mapDiffuse':
  24390. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  24391. break;
  24392. case 'mapDiffuseRepeat':
  24393. case 'mapDiffuseOffset':
  24394. case 'mapDiffuseWrap':
  24395. case 'mapDiffuseAnisotropy':
  24396. break;
  24397. case 'mapEmissive':
  24398. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  24399. break;
  24400. case 'mapEmissiveRepeat':
  24401. case 'mapEmissiveOffset':
  24402. case 'mapEmissiveWrap':
  24403. case 'mapEmissiveAnisotropy':
  24404. break;
  24405. case 'mapLight':
  24406. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  24407. break;
  24408. case 'mapLightRepeat':
  24409. case 'mapLightOffset':
  24410. case 'mapLightWrap':
  24411. case 'mapLightAnisotropy':
  24412. break;
  24413. case 'mapAO':
  24414. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  24415. break;
  24416. case 'mapAORepeat':
  24417. case 'mapAOOffset':
  24418. case 'mapAOWrap':
  24419. case 'mapAOAnisotropy':
  24420. break;
  24421. case 'mapBump':
  24422. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  24423. break;
  24424. case 'mapBumpScale':
  24425. json.bumpScale = value;
  24426. break;
  24427. case 'mapBumpRepeat':
  24428. case 'mapBumpOffset':
  24429. case 'mapBumpWrap':
  24430. case 'mapBumpAnisotropy':
  24431. break;
  24432. case 'mapNormal':
  24433. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  24434. break;
  24435. case 'mapNormalFactor':
  24436. json.normalScale = [ value, value ];
  24437. break;
  24438. case 'mapNormalRepeat':
  24439. case 'mapNormalOffset':
  24440. case 'mapNormalWrap':
  24441. case 'mapNormalAnisotropy':
  24442. break;
  24443. case 'mapSpecular':
  24444. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  24445. break;
  24446. case 'mapSpecularRepeat':
  24447. case 'mapSpecularOffset':
  24448. case 'mapSpecularWrap':
  24449. case 'mapSpecularAnisotropy':
  24450. break;
  24451. case 'mapMetalness':
  24452. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  24453. break;
  24454. case 'mapMetalnessRepeat':
  24455. case 'mapMetalnessOffset':
  24456. case 'mapMetalnessWrap':
  24457. case 'mapMetalnessAnisotropy':
  24458. break;
  24459. case 'mapRoughness':
  24460. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  24461. break;
  24462. case 'mapRoughnessRepeat':
  24463. case 'mapRoughnessOffset':
  24464. case 'mapRoughnessWrap':
  24465. case 'mapRoughnessAnisotropy':
  24466. break;
  24467. case 'mapAlpha':
  24468. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  24469. break;
  24470. case 'mapAlphaRepeat':
  24471. case 'mapAlphaOffset':
  24472. case 'mapAlphaWrap':
  24473. case 'mapAlphaAnisotropy':
  24474. break;
  24475. case 'flipSided':
  24476. json.side = BackSide;
  24477. break;
  24478. case 'doubleSided':
  24479. json.side = DoubleSide;
  24480. break;
  24481. case 'transparency':
  24482. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  24483. json.opacity = value;
  24484. break;
  24485. case 'depthTest':
  24486. case 'depthWrite':
  24487. case 'colorWrite':
  24488. case 'opacity':
  24489. case 'reflectivity':
  24490. case 'transparent':
  24491. case 'visible':
  24492. case 'wireframe':
  24493. json[ name ] = value;
  24494. break;
  24495. case 'vertexColors':
  24496. if ( value === true ) json.vertexColors = VertexColors;
  24497. if ( value === 'face' ) json.vertexColors = FaceColors;
  24498. break;
  24499. default:
  24500. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  24501. break;
  24502. }
  24503. }
  24504. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  24505. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  24506. if ( json.opacity < 1 ) json.transparent = true;
  24507. materialLoader.setTextures( textures );
  24508. return materialLoader.parse( json );
  24509. };
  24510. } )()
  24511. };
  24512. Loader.Handlers = {
  24513. handlers: [],
  24514. add: function ( regex, loader ) {
  24515. this.handlers.push( regex, loader );
  24516. },
  24517. get: function ( file ) {
  24518. var handlers = this.handlers;
  24519. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  24520. var regex = handlers[ i ];
  24521. var loader = handlers[ i + 1 ];
  24522. if ( regex.test( file ) ) {
  24523. return loader;
  24524. }
  24525. }
  24526. return null;
  24527. }
  24528. };
  24529. /**
  24530. * @author mrdoob / http://mrdoob.com/
  24531. * @author alteredq / http://alteredqualia.com/
  24532. */
  24533. function JSONLoader( manager ) {
  24534. if ( typeof manager === 'boolean' ) {
  24535. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  24536. manager = undefined;
  24537. }
  24538. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24539. this.withCredentials = false;
  24540. }
  24541. Object.assign( JSONLoader.prototype, {
  24542. load: function( url, onLoad, onProgress, onError ) {
  24543. var scope = this;
  24544. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  24545. var loader = new FileLoader( this.manager );
  24546. loader.setWithCredentials( this.withCredentials );
  24547. loader.load( url, function ( text ) {
  24548. var json = JSON.parse( text );
  24549. var metadata = json.metadata;
  24550. if ( metadata !== undefined ) {
  24551. var type = metadata.type;
  24552. if ( type !== undefined ) {
  24553. if ( type.toLowerCase() === 'object' ) {
  24554. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  24555. return;
  24556. }
  24557. if ( type.toLowerCase() === 'scene' ) {
  24558. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  24559. return;
  24560. }
  24561. }
  24562. }
  24563. var object = scope.parse( json, texturePath );
  24564. onLoad( object.geometry, object.materials );
  24565. }, onProgress, onError );
  24566. },
  24567. setTexturePath: function ( value ) {
  24568. this.texturePath = value;
  24569. },
  24570. parse: function ( json, texturePath ) {
  24571. var geometry = new Geometry(),
  24572. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  24573. parseModel( scale );
  24574. parseSkin();
  24575. parseMorphing( scale );
  24576. parseAnimations();
  24577. geometry.computeFaceNormals();
  24578. geometry.computeBoundingSphere();
  24579. function parseModel( scale ) {
  24580. function isBitSet( value, position ) {
  24581. return value & ( 1 << position );
  24582. }
  24583. var i, j, fi,
  24584. offset, zLength,
  24585. colorIndex, normalIndex, uvIndex, materialIndex,
  24586. type,
  24587. isQuad,
  24588. hasMaterial,
  24589. hasFaceVertexUv,
  24590. hasFaceNormal, hasFaceVertexNormal,
  24591. hasFaceColor, hasFaceVertexColor,
  24592. vertex, face, faceA, faceB, hex, normal,
  24593. uvLayer, uv, u, v,
  24594. faces = json.faces,
  24595. vertices = json.vertices,
  24596. normals = json.normals,
  24597. colors = json.colors,
  24598. nUvLayers = 0;
  24599. if ( json.uvs !== undefined ) {
  24600. // disregard empty arrays
  24601. for ( i = 0; i < json.uvs.length; i ++ ) {
  24602. if ( json.uvs[ i ].length ) nUvLayers ++;
  24603. }
  24604. for ( i = 0; i < nUvLayers; i ++ ) {
  24605. geometry.faceVertexUvs[ i ] = [];
  24606. }
  24607. }
  24608. offset = 0;
  24609. zLength = vertices.length;
  24610. while ( offset < zLength ) {
  24611. vertex = new Vector3();
  24612. vertex.x = vertices[ offset ++ ] * scale;
  24613. vertex.y = vertices[ offset ++ ] * scale;
  24614. vertex.z = vertices[ offset ++ ] * scale;
  24615. geometry.vertices.push( vertex );
  24616. }
  24617. offset = 0;
  24618. zLength = faces.length;
  24619. while ( offset < zLength ) {
  24620. type = faces[ offset ++ ];
  24621. isQuad = isBitSet( type, 0 );
  24622. hasMaterial = isBitSet( type, 1 );
  24623. hasFaceVertexUv = isBitSet( type, 3 );
  24624. hasFaceNormal = isBitSet( type, 4 );
  24625. hasFaceVertexNormal = isBitSet( type, 5 );
  24626. hasFaceColor = isBitSet( type, 6 );
  24627. hasFaceVertexColor = isBitSet( type, 7 );
  24628. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  24629. if ( isQuad ) {
  24630. faceA = new Face3();
  24631. faceA.a = faces[ offset ];
  24632. faceA.b = faces[ offset + 1 ];
  24633. faceA.c = faces[ offset + 3 ];
  24634. faceB = new Face3();
  24635. faceB.a = faces[ offset + 1 ];
  24636. faceB.b = faces[ offset + 2 ];
  24637. faceB.c = faces[ offset + 3 ];
  24638. offset += 4;
  24639. if ( hasMaterial ) {
  24640. materialIndex = faces[ offset ++ ];
  24641. faceA.materialIndex = materialIndex;
  24642. faceB.materialIndex = materialIndex;
  24643. }
  24644. // to get face <=> uv index correspondence
  24645. fi = geometry.faces.length;
  24646. if ( hasFaceVertexUv ) {
  24647. for ( i = 0; i < nUvLayers; i ++ ) {
  24648. uvLayer = json.uvs[ i ];
  24649. geometry.faceVertexUvs[ i ][ fi ] = [];
  24650. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  24651. for ( j = 0; j < 4; j ++ ) {
  24652. uvIndex = faces[ offset ++ ];
  24653. u = uvLayer[ uvIndex * 2 ];
  24654. v = uvLayer[ uvIndex * 2 + 1 ];
  24655. uv = new Vector2( u, v );
  24656. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  24657. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  24658. }
  24659. }
  24660. }
  24661. if ( hasFaceNormal ) {
  24662. normalIndex = faces[ offset ++ ] * 3;
  24663. faceA.normal.set(
  24664. normals[ normalIndex ++ ],
  24665. normals[ normalIndex ++ ],
  24666. normals[ normalIndex ]
  24667. );
  24668. faceB.normal.copy( faceA.normal );
  24669. }
  24670. if ( hasFaceVertexNormal ) {
  24671. for ( i = 0; i < 4; i ++ ) {
  24672. normalIndex = faces[ offset ++ ] * 3;
  24673. normal = new Vector3(
  24674. normals[ normalIndex ++ ],
  24675. normals[ normalIndex ++ ],
  24676. normals[ normalIndex ]
  24677. );
  24678. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  24679. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  24680. }
  24681. }
  24682. if ( hasFaceColor ) {
  24683. colorIndex = faces[ offset ++ ];
  24684. hex = colors[ colorIndex ];
  24685. faceA.color.setHex( hex );
  24686. faceB.color.setHex( hex );
  24687. }
  24688. if ( hasFaceVertexColor ) {
  24689. for ( i = 0; i < 4; i ++ ) {
  24690. colorIndex = faces[ offset ++ ];
  24691. hex = colors[ colorIndex ];
  24692. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  24693. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  24694. }
  24695. }
  24696. geometry.faces.push( faceA );
  24697. geometry.faces.push( faceB );
  24698. } else {
  24699. face = new Face3();
  24700. face.a = faces[ offset ++ ];
  24701. face.b = faces[ offset ++ ];
  24702. face.c = faces[ offset ++ ];
  24703. if ( hasMaterial ) {
  24704. materialIndex = faces[ offset ++ ];
  24705. face.materialIndex = materialIndex;
  24706. }
  24707. // to get face <=> uv index correspondence
  24708. fi = geometry.faces.length;
  24709. if ( hasFaceVertexUv ) {
  24710. for ( i = 0; i < nUvLayers; i ++ ) {
  24711. uvLayer = json.uvs[ i ];
  24712. geometry.faceVertexUvs[ i ][ fi ] = [];
  24713. for ( j = 0; j < 3; j ++ ) {
  24714. uvIndex = faces[ offset ++ ];
  24715. u = uvLayer[ uvIndex * 2 ];
  24716. v = uvLayer[ uvIndex * 2 + 1 ];
  24717. uv = new Vector2( u, v );
  24718. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  24719. }
  24720. }
  24721. }
  24722. if ( hasFaceNormal ) {
  24723. normalIndex = faces[ offset ++ ] * 3;
  24724. face.normal.set(
  24725. normals[ normalIndex ++ ],
  24726. normals[ normalIndex ++ ],
  24727. normals[ normalIndex ]
  24728. );
  24729. }
  24730. if ( hasFaceVertexNormal ) {
  24731. for ( i = 0; i < 3; i ++ ) {
  24732. normalIndex = faces[ offset ++ ] * 3;
  24733. normal = new Vector3(
  24734. normals[ normalIndex ++ ],
  24735. normals[ normalIndex ++ ],
  24736. normals[ normalIndex ]
  24737. );
  24738. face.vertexNormals.push( normal );
  24739. }
  24740. }
  24741. if ( hasFaceColor ) {
  24742. colorIndex = faces[ offset ++ ];
  24743. face.color.setHex( colors[ colorIndex ] );
  24744. }
  24745. if ( hasFaceVertexColor ) {
  24746. for ( i = 0; i < 3; i ++ ) {
  24747. colorIndex = faces[ offset ++ ];
  24748. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  24749. }
  24750. }
  24751. geometry.faces.push( face );
  24752. }
  24753. }
  24754. }
  24755. function parseSkin() {
  24756. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  24757. if ( json.skinWeights ) {
  24758. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  24759. var x = json.skinWeights[ i ];
  24760. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  24761. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  24762. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  24763. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  24764. }
  24765. }
  24766. if ( json.skinIndices ) {
  24767. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  24768. var a = json.skinIndices[ i ];
  24769. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  24770. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  24771. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  24772. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  24773. }
  24774. }
  24775. geometry.bones = json.bones;
  24776. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  24777. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  24778. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  24779. }
  24780. }
  24781. function parseMorphing( scale ) {
  24782. if ( json.morphTargets !== undefined ) {
  24783. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  24784. geometry.morphTargets[ i ] = {};
  24785. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  24786. geometry.morphTargets[ i ].vertices = [];
  24787. var dstVertices = geometry.morphTargets[ i ].vertices;
  24788. var srcVertices = json.morphTargets[ i ].vertices;
  24789. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  24790. var vertex = new Vector3();
  24791. vertex.x = srcVertices[ v ] * scale;
  24792. vertex.y = srcVertices[ v + 1 ] * scale;
  24793. vertex.z = srcVertices[ v + 2 ] * scale;
  24794. dstVertices.push( vertex );
  24795. }
  24796. }
  24797. }
  24798. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  24799. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  24800. var faces = geometry.faces;
  24801. var morphColors = json.morphColors[ 0 ].colors;
  24802. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24803. faces[ i ].color.fromArray( morphColors, i * 3 );
  24804. }
  24805. }
  24806. }
  24807. function parseAnimations() {
  24808. var outputAnimations = [];
  24809. // parse old style Bone/Hierarchy animations
  24810. var animations = [];
  24811. if ( json.animation !== undefined ) {
  24812. animations.push( json.animation );
  24813. }
  24814. if ( json.animations !== undefined ) {
  24815. if ( json.animations.length ) {
  24816. animations = animations.concat( json.animations );
  24817. } else {
  24818. animations.push( json.animations );
  24819. }
  24820. }
  24821. for ( var i = 0; i < animations.length; i ++ ) {
  24822. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  24823. if ( clip ) outputAnimations.push( clip );
  24824. }
  24825. // parse implicit morph animations
  24826. if ( geometry.morphTargets ) {
  24827. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  24828. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  24829. outputAnimations = outputAnimations.concat( morphAnimationClips );
  24830. }
  24831. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  24832. }
  24833. if ( json.materials === undefined || json.materials.length === 0 ) {
  24834. return { geometry: geometry };
  24835. } else {
  24836. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  24837. return { geometry: geometry, materials: materials };
  24838. }
  24839. }
  24840. } );
  24841. /**
  24842. * @author mikael emtinger / http://gomo.se/
  24843. * @author alteredq / http://alteredqualia.com/
  24844. * @author michael guerrero / http://realitymeltdown.com
  24845. * @author ikerr / http://verold.com
  24846. */
  24847. function Skeleton( bones, boneInverses, useVertexTexture ) {
  24848. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  24849. this.identityMatrix = new Matrix4();
  24850. // copy the bone array
  24851. bones = bones || [];
  24852. this.bones = bones.slice( 0 );
  24853. // create a bone texture or an array of floats
  24854. if ( this.useVertexTexture ) {
  24855. // layout (1 matrix = 4 pixels)
  24856. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  24857. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  24858. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  24859. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  24860. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  24861. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  24862. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  24863. size = Math.max( size, 4 );
  24864. this.boneTextureWidth = size;
  24865. this.boneTextureHeight = size;
  24866. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  24867. this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType );
  24868. } else {
  24869. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  24870. }
  24871. // use the supplied bone inverses or calculate the inverses
  24872. if ( boneInverses === undefined ) {
  24873. this.calculateInverses();
  24874. } else {
  24875. if ( this.bones.length === boneInverses.length ) {
  24876. this.boneInverses = boneInverses.slice( 0 );
  24877. } else {
  24878. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  24879. this.boneInverses = [];
  24880. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  24881. this.boneInverses.push( new Matrix4() );
  24882. }
  24883. }
  24884. }
  24885. }
  24886. Object.assign( Skeleton.prototype, {
  24887. calculateInverses: function () {
  24888. this.boneInverses = [];
  24889. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  24890. var inverse = new Matrix4();
  24891. if ( this.bones[ b ] ) {
  24892. inverse.getInverse( this.bones[ b ].matrixWorld );
  24893. }
  24894. this.boneInverses.push( inverse );
  24895. }
  24896. },
  24897. pose: function () {
  24898. var bone;
  24899. // recover the bind-time world matrices
  24900. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  24901. bone = this.bones[ b ];
  24902. if ( bone ) {
  24903. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  24904. }
  24905. }
  24906. // compute the local matrices, positions, rotations and scales
  24907. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  24908. bone = this.bones[ b ];
  24909. if ( bone ) {
  24910. if ( bone.parent && bone.parent.isBone ) {
  24911. bone.matrix.getInverse( bone.parent.matrixWorld );
  24912. bone.matrix.multiply( bone.matrixWorld );
  24913. } else {
  24914. bone.matrix.copy( bone.matrixWorld );
  24915. }
  24916. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  24917. }
  24918. }
  24919. },
  24920. update: ( function () {
  24921. var offsetMatrix = new Matrix4();
  24922. return function update() {
  24923. // flatten bone matrices to array
  24924. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  24925. // compute the offset between the current and the original transform
  24926. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  24927. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  24928. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  24929. }
  24930. if ( this.useVertexTexture ) {
  24931. this.boneTexture.needsUpdate = true;
  24932. }
  24933. };
  24934. } )(),
  24935. clone: function () {
  24936. return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  24937. }
  24938. } );
  24939. /**
  24940. * @author mikael emtinger / http://gomo.se/
  24941. * @author alteredq / http://alteredqualia.com/
  24942. * @author ikerr / http://verold.com
  24943. */
  24944. function Bone() {
  24945. Object3D.call( this );
  24946. this.type = 'Bone';
  24947. }
  24948. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  24949. constructor: Bone,
  24950. isBone: true
  24951. } );
  24952. /**
  24953. * @author mikael emtinger / http://gomo.se/
  24954. * @author alteredq / http://alteredqualia.com/
  24955. * @author ikerr / http://verold.com
  24956. */
  24957. function SkinnedMesh( geometry, material, useVertexTexture ) {
  24958. Mesh.call( this, geometry, material );
  24959. this.type = 'SkinnedMesh';
  24960. this.bindMode = "attached";
  24961. this.bindMatrix = new Matrix4();
  24962. this.bindMatrixInverse = new Matrix4();
  24963. // init bones
  24964. // TODO: remove bone creation as there is no reason (other than
  24965. // convenience) for THREE.SkinnedMesh to do this.
  24966. var bones = [];
  24967. if ( this.geometry && this.geometry.bones !== undefined ) {
  24968. var bone, gbone;
  24969. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  24970. gbone = this.geometry.bones[ b ];
  24971. bone = new Bone();
  24972. bones.push( bone );
  24973. bone.name = gbone.name;
  24974. bone.position.fromArray( gbone.pos );
  24975. bone.quaternion.fromArray( gbone.rotq );
  24976. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  24977. }
  24978. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  24979. gbone = this.geometry.bones[ b ];
  24980. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  24981. bones[ gbone.parent ] !== undefined ) {
  24982. bones[ gbone.parent ].add( bones[ b ] );
  24983. } else {
  24984. this.add( bones[ b ] );
  24985. }
  24986. }
  24987. }
  24988. this.normalizeSkinWeights();
  24989. this.updateMatrixWorld( true );
  24990. this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  24991. }
  24992. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  24993. constructor: SkinnedMesh,
  24994. isSkinnedMesh: true,
  24995. bind: function( skeleton, bindMatrix ) {
  24996. this.skeleton = skeleton;
  24997. if ( bindMatrix === undefined ) {
  24998. this.updateMatrixWorld( true );
  24999. this.skeleton.calculateInverses();
  25000. bindMatrix = this.matrixWorld;
  25001. }
  25002. this.bindMatrix.copy( bindMatrix );
  25003. this.bindMatrixInverse.getInverse( bindMatrix );
  25004. },
  25005. pose: function () {
  25006. this.skeleton.pose();
  25007. },
  25008. normalizeSkinWeights: function () {
  25009. if ( this.geometry && this.geometry.isGeometry ) {
  25010. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  25011. var sw = this.geometry.skinWeights[ i ];
  25012. var scale = 1.0 / sw.lengthManhattan();
  25013. if ( scale !== Infinity ) {
  25014. sw.multiplyScalar( scale );
  25015. } else {
  25016. sw.set( 1, 0, 0, 0 ); // do something reasonable
  25017. }
  25018. }
  25019. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  25020. var vec = new Vector4();
  25021. var skinWeight = this.geometry.attributes.skinWeight;
  25022. for ( var i = 0; i < skinWeight.count; i ++ ) {
  25023. vec.x = skinWeight.getX( i );
  25024. vec.y = skinWeight.getY( i );
  25025. vec.z = skinWeight.getZ( i );
  25026. vec.w = skinWeight.getW( i );
  25027. var scale = 1.0 / vec.lengthManhattan();
  25028. if ( scale !== Infinity ) {
  25029. vec.multiplyScalar( scale );
  25030. } else {
  25031. vec.set( 1, 0, 0, 0 ); // do something reasonable
  25032. }
  25033. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  25034. }
  25035. }
  25036. },
  25037. updateMatrixWorld: function( force ) {
  25038. Mesh.prototype.updateMatrixWorld.call( this, true );
  25039. if ( this.bindMode === "attached" ) {
  25040. this.bindMatrixInverse.getInverse( this.matrixWorld );
  25041. } else if ( this.bindMode === "detached" ) {
  25042. this.bindMatrixInverse.getInverse( this.bindMatrix );
  25043. } else {
  25044. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  25045. }
  25046. },
  25047. clone: function() {
  25048. return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this );
  25049. }
  25050. } );
  25051. /**
  25052. * @author mrdoob / http://mrdoob.com/
  25053. * @author alteredq / http://alteredqualia.com/
  25054. */
  25055. function Fog ( color, near, far ) {
  25056. this.name = '';
  25057. this.color = new Color( color );
  25058. this.near = ( near !== undefined ) ? near : 1;
  25059. this.far = ( far !== undefined ) ? far : 1000;
  25060. }
  25061. Fog.prototype.isFog = true;
  25062. Fog.prototype.clone = function () {
  25063. return new Fog( this.color.getHex(), this.near, this.far );
  25064. };
  25065. Fog.prototype.toJSON = function ( meta ) {
  25066. return {
  25067. type: 'Fog',
  25068. color: this.color.getHex(),
  25069. near: this.near,
  25070. far: this.far
  25071. };
  25072. };
  25073. /**
  25074. * @author mrdoob / http://mrdoob.com/
  25075. * @author alteredq / http://alteredqualia.com/
  25076. */
  25077. function FogExp2 ( color, density ) {
  25078. this.name = '';
  25079. this.color = new Color( color );
  25080. this.density = ( density !== undefined ) ? density : 0.00025;
  25081. }
  25082. FogExp2.prototype.isFogExp2 = true;
  25083. FogExp2.prototype.clone = function () {
  25084. return new FogExp2( this.color.getHex(), this.density );
  25085. };
  25086. FogExp2.prototype.toJSON = function ( meta ) {
  25087. return {
  25088. type: 'FogExp2',
  25089. color: this.color.getHex(),
  25090. density: this.density
  25091. };
  25092. };
  25093. /**
  25094. * @author mrdoob / http://mrdoob.com/
  25095. */
  25096. function Scene () {
  25097. Object3D.call( this );
  25098. this.type = 'Scene';
  25099. this.background = null;
  25100. this.fog = null;
  25101. this.overrideMaterial = null;
  25102. this.autoUpdate = true; // checked by the renderer
  25103. }
  25104. Scene.prototype = Object.create( Object3D.prototype );
  25105. Scene.prototype.constructor = Scene;
  25106. Scene.prototype.copy = function ( source, recursive ) {
  25107. Object3D.prototype.copy.call( this, source, recursive );
  25108. if ( source.background !== null ) this.background = source.background.clone();
  25109. if ( source.fog !== null ) this.fog = source.fog.clone();
  25110. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  25111. this.autoUpdate = source.autoUpdate;
  25112. this.matrixAutoUpdate = source.matrixAutoUpdate;
  25113. return this;
  25114. };
  25115. Scene.prototype.toJSON = function ( meta ) {
  25116. var data = Object3D.prototype.toJSON.call( this, meta );
  25117. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  25118. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  25119. return data;
  25120. };
  25121. /**
  25122. * @author mrdoob / http://mrdoob.com/
  25123. */
  25124. function ObjectLoader( manager ) {
  25125. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25126. this.texturePath = '';
  25127. }
  25128. Object.assign( ObjectLoader.prototype, {
  25129. load: function ( url, onLoad, onProgress, onError ) {
  25130. if ( this.texturePath === '' ) {
  25131. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  25132. }
  25133. var scope = this;
  25134. var loader = new FileLoader( scope.manager );
  25135. loader.load( url, function ( text ) {
  25136. var json = null;
  25137. try {
  25138. json = JSON.parse( text );
  25139. } catch ( error ) {
  25140. if ( onError !== undefined ) onError( error );
  25141. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25142. return;
  25143. }
  25144. var metadata = json.metadata;
  25145. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25146. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  25147. return;
  25148. }
  25149. scope.parse( json, onLoad );
  25150. }, onProgress, onError );
  25151. },
  25152. setTexturePath: function ( value ) {
  25153. this.texturePath = value;
  25154. },
  25155. setCrossOrigin: function ( value ) {
  25156. this.crossOrigin = value;
  25157. },
  25158. parse: function ( json, onLoad ) {
  25159. var geometries = this.parseGeometries( json.geometries );
  25160. var images = this.parseImages( json.images, function () {
  25161. if ( onLoad !== undefined ) onLoad( object );
  25162. } );
  25163. var textures = this.parseTextures( json.textures, images );
  25164. var materials = this.parseMaterials( json.materials, textures );
  25165. var object = this.parseObject( json.object, geometries, materials );
  25166. if ( json.animations ) {
  25167. object.animations = this.parseAnimations( json.animations );
  25168. }
  25169. if ( json.images === undefined || json.images.length === 0 ) {
  25170. if ( onLoad !== undefined ) onLoad( object );
  25171. }
  25172. return object;
  25173. },
  25174. parseGeometries: function ( json ) {
  25175. var geometries = {};
  25176. if ( json !== undefined ) {
  25177. var geometryLoader = new JSONLoader();
  25178. var bufferGeometryLoader = new BufferGeometryLoader();
  25179. for ( var i = 0, l = json.length; i < l; i ++ ) {
  25180. var geometry;
  25181. var data = json[ i ];
  25182. switch ( data.type ) {
  25183. case 'PlaneGeometry':
  25184. case 'PlaneBufferGeometry':
  25185. geometry = new Geometries[ data.type ](
  25186. data.width,
  25187. data.height,
  25188. data.widthSegments,
  25189. data.heightSegments
  25190. );
  25191. break;
  25192. case 'BoxGeometry':
  25193. case 'BoxBufferGeometry':
  25194. case 'CubeGeometry': // backwards compatible
  25195. geometry = new Geometries[ data.type ](
  25196. data.width,
  25197. data.height,
  25198. data.depth,
  25199. data.widthSegments,
  25200. data.heightSegments,
  25201. data.depthSegments
  25202. );
  25203. break;
  25204. case 'CircleGeometry':
  25205. case 'CircleBufferGeometry':
  25206. geometry = new Geometries[ data.type ](
  25207. data.radius,
  25208. data.segments,
  25209. data.thetaStart,
  25210. data.thetaLength
  25211. );
  25212. break;
  25213. case 'CylinderGeometry':
  25214. case 'CylinderBufferGeometry':
  25215. geometry = new Geometries[ data.type ](
  25216. data.radiusTop,
  25217. data.radiusBottom,
  25218. data.height,
  25219. data.radialSegments,
  25220. data.heightSegments,
  25221. data.openEnded,
  25222. data.thetaStart,
  25223. data.thetaLength
  25224. );
  25225. break;
  25226. case 'ConeGeometry':
  25227. case 'ConeBufferGeometry':
  25228. geometry = new Geometries[ data.type ](
  25229. data.radius,
  25230. data.height,
  25231. data.radialSegments,
  25232. data.heightSegments,
  25233. data.openEnded,
  25234. data.thetaStart,
  25235. data.thetaLength
  25236. );
  25237. break;
  25238. case 'SphereGeometry':
  25239. case 'SphereBufferGeometry':
  25240. geometry = new Geometries[ data.type ](
  25241. data.radius,
  25242. data.widthSegments,
  25243. data.heightSegments,
  25244. data.phiStart,
  25245. data.phiLength,
  25246. data.thetaStart,
  25247. data.thetaLength
  25248. );
  25249. break;
  25250. case 'DodecahedronGeometry':
  25251. case 'IcosahedronGeometry':
  25252. case 'OctahedronGeometry':
  25253. case 'TetrahedronGeometry':
  25254. geometry = new Geometries[ data.type ](
  25255. data.radius,
  25256. data.detail
  25257. );
  25258. break;
  25259. case 'RingGeometry':
  25260. case 'RingBufferGeometry':
  25261. geometry = new Geometries[ data.type ](
  25262. data.innerRadius,
  25263. data.outerRadius,
  25264. data.thetaSegments,
  25265. data.phiSegments,
  25266. data.thetaStart,
  25267. data.thetaLength
  25268. );
  25269. break;
  25270. case 'TorusGeometry':
  25271. case 'TorusBufferGeometry':
  25272. geometry = new Geometries[ data.type ](
  25273. data.radius,
  25274. data.tube,
  25275. data.radialSegments,
  25276. data.tubularSegments,
  25277. data.arc
  25278. );
  25279. break;
  25280. case 'TorusKnotGeometry':
  25281. case 'TorusKnotBufferGeometry':
  25282. geometry = new Geometries[ data.type ](
  25283. data.radius,
  25284. data.tube,
  25285. data.tubularSegments,
  25286. data.radialSegments,
  25287. data.p,
  25288. data.q
  25289. );
  25290. break;
  25291. case 'LatheGeometry':
  25292. case 'LatheBufferGeometry':
  25293. geometry = new Geometries[ data.type ](
  25294. data.points,
  25295. data.segments,
  25296. data.phiStart,
  25297. data.phiLength
  25298. );
  25299. break;
  25300. case 'BufferGeometry':
  25301. geometry = bufferGeometryLoader.parse( data );
  25302. break;
  25303. case 'Geometry':
  25304. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  25305. break;
  25306. default:
  25307. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  25308. continue;
  25309. }
  25310. geometry.uuid = data.uuid;
  25311. if ( data.name !== undefined ) geometry.name = data.name;
  25312. geometries[ data.uuid ] = geometry;
  25313. }
  25314. }
  25315. return geometries;
  25316. },
  25317. parseMaterials: function ( json, textures ) {
  25318. var materials = {};
  25319. if ( json !== undefined ) {
  25320. var loader = new MaterialLoader();
  25321. loader.setTextures( textures );
  25322. for ( var i = 0, l = json.length; i < l; i ++ ) {
  25323. var material = loader.parse( json[ i ] );
  25324. materials[ material.uuid ] = material;
  25325. }
  25326. }
  25327. return materials;
  25328. },
  25329. parseAnimations: function ( json ) {
  25330. var animations = [];
  25331. for ( var i = 0; i < json.length; i ++ ) {
  25332. var clip = AnimationClip.parse( json[ i ] );
  25333. animations.push( clip );
  25334. }
  25335. return animations;
  25336. },
  25337. parseImages: function ( json, onLoad ) {
  25338. var scope = this;
  25339. var images = {};
  25340. function loadImage( url ) {
  25341. scope.manager.itemStart( url );
  25342. return loader.load( url, function () {
  25343. scope.manager.itemEnd( url );
  25344. }, undefined, function () {
  25345. scope.manager.itemError( url );
  25346. } );
  25347. }
  25348. if ( json !== undefined && json.length > 0 ) {
  25349. var manager = new LoadingManager( onLoad );
  25350. var loader = new ImageLoader( manager );
  25351. loader.setCrossOrigin( this.crossOrigin );
  25352. for ( var i = 0, l = json.length; i < l; i ++ ) {
  25353. var image = json[ i ];
  25354. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  25355. images[ image.uuid ] = loadImage( path );
  25356. }
  25357. }
  25358. return images;
  25359. },
  25360. parseTextures: function ( json, images ) {
  25361. var TextureMapping = {
  25362. UVMapping: UVMapping,
  25363. CubeReflectionMapping: CubeReflectionMapping,
  25364. CubeRefractionMapping: CubeRefractionMapping,
  25365. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25366. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25367. SphericalReflectionMapping: SphericalReflectionMapping,
  25368. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25369. CubeUVRefractionMapping: CubeUVRefractionMapping
  25370. };
  25371. var TextureWrapping = {
  25372. RepeatWrapping: RepeatWrapping,
  25373. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25374. MirroredRepeatWrapping: MirroredRepeatWrapping
  25375. };
  25376. var TextureFilter = {
  25377. NearestFilter: NearestFilter,
  25378. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  25379. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  25380. LinearFilter: LinearFilter,
  25381. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  25382. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  25383. };
  25384. function parseConstant( value, type ) {
  25385. if ( typeof( value ) === 'number' ) return value;
  25386. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25387. return type[ value ];
  25388. }
  25389. var textures = {};
  25390. if ( json !== undefined ) {
  25391. for ( var i = 0, l = json.length; i < l; i ++ ) {
  25392. var data = json[ i ];
  25393. if ( data.image === undefined ) {
  25394. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25395. }
  25396. if ( images[ data.image ] === undefined ) {
  25397. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25398. }
  25399. var texture = new Texture( images[ data.image ] );
  25400. texture.needsUpdate = true;
  25401. texture.uuid = data.uuid;
  25402. if ( data.name !== undefined ) texture.name = data.name;
  25403. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TextureMapping );
  25404. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25405. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25406. if ( data.wrap !== undefined ) {
  25407. texture.wrapS = parseConstant( data.wrap[ 0 ], TextureWrapping );
  25408. texture.wrapT = parseConstant( data.wrap[ 1 ], TextureWrapping );
  25409. }
  25410. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TextureFilter );
  25411. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TextureFilter );
  25412. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25413. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25414. textures[ data.uuid ] = texture;
  25415. }
  25416. }
  25417. return textures;
  25418. },
  25419. parseObject: function () {
  25420. var matrix = new Matrix4();
  25421. return function parseObject( data, geometries, materials ) {
  25422. var object;
  25423. function getGeometry( name ) {
  25424. if ( geometries[ name ] === undefined ) {
  25425. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25426. }
  25427. return geometries[ name ];
  25428. }
  25429. function getMaterial( name ) {
  25430. if ( name === undefined ) return undefined;
  25431. if ( materials[ name ] === undefined ) {
  25432. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25433. }
  25434. return materials[ name ];
  25435. }
  25436. switch ( data.type ) {
  25437. case 'Scene':
  25438. object = new Scene();
  25439. if ( data.background !== undefined ) {
  25440. if ( Number.isInteger( data.background ) ) {
  25441. object.background = new Color( data.background );
  25442. }
  25443. }
  25444. if ( data.fog !== undefined ) {
  25445. if ( data.fog.type === 'Fog' ) {
  25446. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25447. } else if ( data.fog.type === 'FogExp2' ) {
  25448. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25449. }
  25450. }
  25451. break;
  25452. case 'PerspectiveCamera':
  25453. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25454. if ( data.focus !== undefined ) object.focus = data.focus;
  25455. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25456. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25457. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25458. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25459. break;
  25460. case 'OrthographicCamera':
  25461. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25462. break;
  25463. case 'AmbientLight':
  25464. object = new AmbientLight( data.color, data.intensity );
  25465. break;
  25466. case 'DirectionalLight':
  25467. object = new DirectionalLight( data.color, data.intensity );
  25468. break;
  25469. case 'PointLight':
  25470. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25471. break;
  25472. case 'SpotLight':
  25473. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25474. break;
  25475. case 'HemisphereLight':
  25476. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25477. break;
  25478. case 'Mesh':
  25479. var geometry = getGeometry( data.geometry );
  25480. var material = getMaterial( data.material );
  25481. if ( geometry.bones && geometry.bones.length > 0 ) {
  25482. object = new SkinnedMesh( geometry, material );
  25483. } else {
  25484. object = new Mesh( geometry, material );
  25485. }
  25486. break;
  25487. case 'LOD':
  25488. object = new LOD();
  25489. break;
  25490. case 'Line':
  25491. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  25492. break;
  25493. case 'LineSegments':
  25494. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25495. break;
  25496. case 'PointCloud':
  25497. case 'Points':
  25498. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25499. break;
  25500. case 'Sprite':
  25501. object = new Sprite( getMaterial( data.material ) );
  25502. break;
  25503. case 'Group':
  25504. object = new Group();
  25505. break;
  25506. case 'SkinnedMesh':
  25507. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh type. Instantiates Object3D instead.' );
  25508. default:
  25509. object = new Object3D();
  25510. }
  25511. object.uuid = data.uuid;
  25512. if ( data.name !== undefined ) object.name = data.name;
  25513. if ( data.matrix !== undefined ) {
  25514. matrix.fromArray( data.matrix );
  25515. matrix.decompose( object.position, object.quaternion, object.scale );
  25516. } else {
  25517. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25518. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25519. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25520. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25521. }
  25522. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25523. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25524. if ( data.shadow ) {
  25525. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25526. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25527. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25528. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25529. }
  25530. if ( data.visible !== undefined ) object.visible = data.visible;
  25531. if ( data.userData !== undefined ) object.userData = data.userData;
  25532. if ( data.children !== undefined ) {
  25533. for ( var child in data.children ) {
  25534. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  25535. }
  25536. }
  25537. if ( data.type === 'LOD' ) {
  25538. var levels = data.levels;
  25539. for ( var l = 0; l < levels.length; l ++ ) {
  25540. var level = levels[ l ];
  25541. var child = object.getObjectByProperty( 'uuid', level.object );
  25542. if ( child !== undefined ) {
  25543. object.addLevel( child, level.distance );
  25544. }
  25545. }
  25546. }
  25547. return object;
  25548. };
  25549. }()
  25550. } );
  25551. /**
  25552. * @author Mugen87 / https://github.com/Mugen87
  25553. *
  25554. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  25555. *
  25556. */
  25557. function Cylindrical( radius, theta, y ) {
  25558. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  25559. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  25560. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  25561. return this;
  25562. }
  25563. Cylindrical.prototype = {
  25564. constructor: Cylindrical,
  25565. set: function ( radius, theta, y ) {
  25566. this.radius = radius;
  25567. this.theta = theta;
  25568. this.y = y;
  25569. return this;
  25570. },
  25571. clone: function () {
  25572. return new this.constructor().copy( this );
  25573. },
  25574. copy: function ( other ) {
  25575. this.radius = other.radius;
  25576. this.theta = other.theta;
  25577. this.y = other.y;
  25578. return this;
  25579. },
  25580. setFromVector3: function( vec3 ) {
  25581. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  25582. this.theta = Math.atan2( vec3.x, vec3.z );
  25583. this.y = vec3.y;
  25584. return this;
  25585. }
  25586. };
  25587. /**
  25588. * @author bhouston / http://clara.io
  25589. * @author WestLangley / http://github.com/WestLangley
  25590. *
  25591. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  25592. *
  25593. * The poles (phi) are at the positive and negative y axis.
  25594. * The equator starts at positive z.
  25595. */
  25596. function Spherical( radius, phi, theta ) {
  25597. this.radius = ( radius !== undefined ) ? radius : 1.0;
  25598. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  25599. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  25600. return this;
  25601. }
  25602. Spherical.prototype = {
  25603. constructor: Spherical,
  25604. set: function ( radius, phi, theta ) {
  25605. this.radius = radius;
  25606. this.phi = phi;
  25607. this.theta = theta;
  25608. return this;
  25609. },
  25610. clone: function () {
  25611. return new this.constructor().copy( this );
  25612. },
  25613. copy: function ( other ) {
  25614. this.radius = other.radius;
  25615. this.phi = other.phi;
  25616. this.theta = other.theta;
  25617. return this;
  25618. },
  25619. // restrict phi to be betwee EPS and PI-EPS
  25620. makeSafe: function() {
  25621. var EPS = 0.000001;
  25622. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  25623. return this;
  25624. },
  25625. setFromVector3: function( vec3 ) {
  25626. this.radius = vec3.length();
  25627. if ( this.radius === 0 ) {
  25628. this.theta = 0;
  25629. this.phi = 0;
  25630. } else {
  25631. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  25632. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  25633. }
  25634. return this;
  25635. }
  25636. };
  25637. /**
  25638. * @author mikael emtinger / http://gomo.se/
  25639. * @author alteredq / http://alteredqualia.com/
  25640. */
  25641. function LensFlare( texture, size, distance, blending, color ) {
  25642. Object3D.call( this );
  25643. this.lensFlares = [];
  25644. this.positionScreen = new Vector3();
  25645. this.customUpdateCallback = undefined;
  25646. if ( texture !== undefined ) {
  25647. this.add( texture, size, distance, blending, color );
  25648. }
  25649. }
  25650. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  25651. constructor: LensFlare,
  25652. isLensFlare: true,
  25653. copy: function ( source ) {
  25654. Object3D.prototype.copy.call( this, source );
  25655. this.positionScreen.copy( source.positionScreen );
  25656. this.customUpdateCallback = source.customUpdateCallback;
  25657. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  25658. this.lensFlares.push( source.lensFlares[ i ] );
  25659. }
  25660. return this;
  25661. },
  25662. add: function ( texture, size, distance, blending, color, opacity ) {
  25663. if ( size === undefined ) size = - 1;
  25664. if ( distance === undefined ) distance = 0;
  25665. if ( opacity === undefined ) opacity = 1;
  25666. if ( color === undefined ) color = new Color( 0xffffff );
  25667. if ( blending === undefined ) blending = NormalBlending;
  25668. distance = Math.min( distance, Math.max( 0, distance ) );
  25669. this.lensFlares.push( {
  25670. texture: texture, // THREE.Texture
  25671. size: size, // size in pixels (-1 = use texture.width)
  25672. distance: distance, // distance (0-1) from light source (0=at light source)
  25673. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  25674. scale: 1, // scale
  25675. rotation: 0, // rotation
  25676. opacity: opacity, // opacity
  25677. color: color, // color
  25678. blending: blending // blending
  25679. } );
  25680. },
  25681. /*
  25682. * Update lens flares update positions on all flares based on the screen position
  25683. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  25684. */
  25685. updateLensFlares: function () {
  25686. var f, fl = this.lensFlares.length;
  25687. var flare;
  25688. var vecX = - this.positionScreen.x * 2;
  25689. var vecY = - this.positionScreen.y * 2;
  25690. for ( f = 0; f < fl; f ++ ) {
  25691. flare = this.lensFlares[ f ];
  25692. flare.x = this.positionScreen.x + vecX * flare.distance;
  25693. flare.y = this.positionScreen.y + vecY * flare.distance;
  25694. flare.wantedRotation = flare.x * Math.PI * 0.25;
  25695. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  25696. }
  25697. }
  25698. } );
  25699. /**
  25700. * @author mrdoob / http://mrdoob.com/
  25701. */
  25702. function WebGL2Renderer( parameters ) {
  25703. console.log( 'THREE.WebGL2Renderer', REVISION );
  25704. parameters = parameters || {};
  25705. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  25706. _context = parameters.context !== undefined ? parameters.context : null,
  25707. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  25708. _depth = parameters.depth !== undefined ? parameters.depth : true,
  25709. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  25710. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  25711. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  25712. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  25713. // initialize
  25714. var gl;
  25715. try {
  25716. var attributes = {
  25717. alpha: _alpha,
  25718. depth: _depth,
  25719. stencil: _stencil,
  25720. antialias: _antialias,
  25721. premultipliedAlpha: _premultipliedAlpha,
  25722. preserveDrawingBuffer: _preserveDrawingBuffer
  25723. };
  25724. gl = _context || _canvas.getContext( 'webgl2', attributes );
  25725. if ( gl === null ) {
  25726. if ( _canvas.getContext( 'webgl2' ) !== null ) {
  25727. throw 'Error creating WebGL2 context with your selected attributes.';
  25728. } else {
  25729. throw 'Error creating WebGL2 context.';
  25730. }
  25731. }
  25732. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  25733. } catch ( error ) {
  25734. console.error( 'THREE.WebGL2Renderer: ' + error );
  25735. }
  25736. //
  25737. var _this = this,
  25738. _autoClear = true,
  25739. _autoClearColor = true,
  25740. _autoClearDepth = true,
  25741. _autoClearStencil = true,
  25742. _clearColor = new Color( 0x000000 ),
  25743. _clearAlpha = 0,
  25744. _width = _canvas.width,
  25745. _height = _canvas.height,
  25746. _pixelRatio = 1,
  25747. _viewport = new Vector4( 0, 0, _width, _height );
  25748. var extensions = new WebGLExtensions( gl );
  25749. var state = new WebGLState( gl, extensions, function () {} );
  25750. //
  25751. function clear( color, depth, stencil ) {
  25752. var bits = 0;
  25753. if ( color === undefined || color ) bits |= gl.COLOR_BUFFER_BIT;
  25754. if ( depth === undefined || depth ) bits |= gl.DEPTH_BUFFER_BIT;
  25755. if ( stencil === undefined || stencil ) bits |= gl.STENCIL_BUFFER_BIT;
  25756. gl.clear( bits );
  25757. }
  25758. function setPixelRatio( value ) {
  25759. if ( value === undefined ) return;
  25760. _pixelRatio = value;
  25761. setSize( _viewport.z, _viewport.w, false );
  25762. }
  25763. function setSize( width, height, updateStyle ) {
  25764. _width = width;
  25765. _height = height;
  25766. _canvas.width = width * _pixelRatio;
  25767. _canvas.height = height * _pixelRatio;
  25768. if ( updateStyle !== false ) {
  25769. _canvas.style.width = width + 'px';
  25770. _canvas.style.height = height + 'px';
  25771. }
  25772. setViewport( 0, 0, width, height );
  25773. }
  25774. function setViewport( x, y, width, height ) {
  25775. state.viewport( _viewport.set( x, y, width, height ) );
  25776. }
  25777. function render( scene, camera ) {
  25778. if ( camera !== undefined && camera.isCamera !== true ) {
  25779. console.error( 'THREE.WebGL2Renderer.render: camera is not an instance of THREE.Camera.' );
  25780. return;
  25781. }
  25782. var background = scene.background;
  25783. var forceClear = false;
  25784. if ( background === null ) {
  25785. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  25786. } else if ( background && background.isColor ) {
  25787. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  25788. forceClear = true;
  25789. }
  25790. if ( _autoClear || forceClear ) {
  25791. this.clear( _autoClearColor, _autoClearDepth, _autoClearStencil );
  25792. }
  25793. }
  25794. function onContextLost( event ) {
  25795. event.preventDefault();
  25796. }
  25797. return {
  25798. domElement: _canvas,
  25799. clear: clear,
  25800. setPixelRatio: setPixelRatio,
  25801. setSize: setSize,
  25802. render: render
  25803. }
  25804. }
  25805. /**
  25806. * @author mrdoob / http://mrdoob.com/
  25807. */
  25808. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  25809. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  25810. this.needsUpdate = true;
  25811. }
  25812. CanvasTexture.prototype = Object.create( Texture.prototype );
  25813. CanvasTexture.prototype.constructor = CanvasTexture;
  25814. /**
  25815. * @author Matt DesLauriers / @mattdesl
  25816. * @author atix / arthursilber.de
  25817. */
  25818. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  25819. format = format !== undefined ? format : DepthFormat;
  25820. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  25821. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  25822. }
  25823. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  25824. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  25825. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  25826. this.image = { width: width, height: height };
  25827. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  25828. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  25829. this.flipY = false;
  25830. this.generateMipmaps = false;
  25831. }
  25832. DepthTexture.prototype = Object.create( Texture.prototype );
  25833. DepthTexture.prototype.constructor = DepthTexture;
  25834. DepthTexture.prototype.isDepthTexture = true;
  25835. /**
  25836. * @author mrdoob / http://mrdoob.com/
  25837. */
  25838. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  25839. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  25840. this.generateMipmaps = false;
  25841. var scope = this;
  25842. function update() {
  25843. requestAnimationFrame( update );
  25844. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  25845. scope.needsUpdate = true;
  25846. }
  25847. }
  25848. update();
  25849. }
  25850. VideoTexture.prototype = Object.create( Texture.prototype );
  25851. VideoTexture.prototype.constructor = VideoTexture;
  25852. //src
  25853. exports.AnimationAction = AnimationAction;
  25854. exports.AnimationClip = AnimationClip;
  25855. exports.AnimationMixer = AnimationMixer;
  25856. exports.AnimationObjectGroup = AnimationObjectGroup;
  25857. exports.AnimationUtils = AnimationUtils;
  25858. exports.KeyframeTrack = KeyframeTrack;
  25859. exports.KeyframeTrackConstructor = KeyframeTrackConstructor;
  25860. exports.PropertyBinding = PropertyBinding;
  25861. exports.PropertyMixer = PropertyMixer;
  25862. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  25863. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  25864. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  25865. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  25866. exports.StringKeyframeTrack = StringKeyframeTrack;
  25867. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  25868. exports.Audio = Audio;
  25869. exports.AudioAnalyser = AudioAnalyser;
  25870. exports.AudioContext = AudioContext;
  25871. exports.AudioListener = AudioListener;
  25872. exports.PositionalAudio = PositionalAudio;
  25873. exports.Camera = Camera;
  25874. exports.CubeCamera = CubeCamera;
  25875. exports.OrthographicCamera = OrthographicCamera;
  25876. exports.PerspectiveCamera = PerspectiveCamera;
  25877. exports.StereoCamera = StereoCamera;
  25878. exports.BufferGeometry = BufferGeometry;
  25879. exports.Clock = Clock;
  25880. exports.DirectGeometry = DirectGeometry;
  25881. exports.EventDispatcher = EventDispatcher;
  25882. exports.Face3 = Face3;
  25883. exports.GeometryIdCount = GeometryIdCount;
  25884. exports.Geometry = Geometry;
  25885. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  25886. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  25887. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  25888. exports.InterleavedBuffer = InterleavedBuffer;
  25889. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  25890. exports.Layers = Layers;
  25891. exports.Object3D = Object3D;
  25892. exports.Raycaster = Raycaster;
  25893. exports.Uniform = Uniform;
  25894. exports.SceneUtils = SceneUtils;
  25895. exports.ShapeUtils = ShapeUtils;
  25896. exports.Curve = Curve;
  25897. exports.CurvePath = CurvePath;
  25898. exports.Font = Font;
  25899. exports.Path = Path;
  25900. exports.PathPrototype = PathPrototype;
  25901. exports.Shape = Shape;
  25902. exports.ShapePath = ShapePath;
  25903. exports.ArcCurve = ArcCurve;
  25904. exports.CatmullRomCurve3 = CatmullRomCurve3;
  25905. exports.CubicBezierCurve = CubicBezierCurve;
  25906. exports.CubicBezierCurve3 = CubicBezierCurve3;
  25907. exports.EllipseCurve = EllipseCurve;
  25908. exports.LineCurve = LineCurve;
  25909. exports.LineCurve3 = LineCurve3;
  25910. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  25911. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  25912. exports.SplineCurve = SplineCurve;
  25913. exports.ImmediateRenderObject = ImmediateRenderObject;
  25914. exports.MorphBlendMesh = MorphBlendMesh;
  25915. exports.ArrowHelper = ArrowHelper;
  25916. exports.AxisHelper = AxisHelper;
  25917. exports.BoxHelper = BoxHelper;
  25918. exports.CameraHelper = CameraHelper;
  25919. exports.DirectionalLightHelper = DirectionalLightHelper;
  25920. exports.FaceNormalsHelper = FaceNormalsHelper;
  25921. exports.GridHelper = GridHelper;
  25922. exports.HemisphereLightHelper = HemisphereLightHelper;
  25923. exports.PointLightHelper = PointLightHelper;
  25924. exports.PolarGridHelper = PolarGridHelper;
  25925. exports.RectAreaLightHelper = RectAreaLightHelper;
  25926. exports.SkeletonHelper = SkeletonHelper;
  25927. exports.SpotLightHelper = SpotLightHelper;
  25928. exports.VertexNormalsHelper = VertexNormalsHelper;
  25929. exports.AmbientLight = AmbientLight;
  25930. exports.DirectionalLight = DirectionalLight;
  25931. exports.DirectionalLightShadow = DirectionalLightShadow;
  25932. exports.HemisphereLight = HemisphereLight;
  25933. exports.Light = Light;
  25934. exports.LightShadow = LightShadow;
  25935. exports.PointLight = PointLight;
  25936. exports.RectAreaLight = RectAreaLight;
  25937. exports.SpotLight = SpotLight;
  25938. exports.SpotLightShadow = SpotLightShadow;
  25939. exports.AnimationLoader = AnimationLoader;
  25940. exports.AudioLoader = AudioLoader;
  25941. exports.BufferGeometryLoader = BufferGeometryLoader;
  25942. exports.Cache = Cache;
  25943. exports.CompressedTextureLoader = CompressedTextureLoader;
  25944. exports.CubeTextureLoader = CubeTextureLoader;
  25945. exports.DataTextureLoader = DataTextureLoader;
  25946. exports.DefaultLoadingManager = DefaultLoadingManager;
  25947. exports.LoadingManager = LoadingManager;
  25948. exports.FileLoader = FileLoader;
  25949. exports.FontLoader = FontLoader;
  25950. exports.ImageLoader = ImageLoader;
  25951. exports.JSONLoader = JSONLoader;
  25952. exports.Loader = Loader;
  25953. exports.MaterialLoader = MaterialLoader;
  25954. exports.ObjectLoader = ObjectLoader;
  25955. exports.TextureLoader = TextureLoader;
  25956. exports.Math = _Math;
  25957. exports.Box2 = Box2;
  25958. exports.Box3 = Box3;
  25959. exports.Color = Color;
  25960. exports.Cylindrical = Cylindrical;
  25961. exports.Euler = Euler;
  25962. exports.Frustum = Frustum;
  25963. exports.Interpolant = Interpolant;
  25964. exports.Line3 = Line3;
  25965. exports.Matrix3 = Matrix3;
  25966. exports.Matrix4 = Matrix4;
  25967. exports.Plane = Plane;
  25968. exports.Quaternion = Quaternion;
  25969. exports.Ray = Ray;
  25970. exports.Sphere = Sphere;
  25971. exports.Spherical = Spherical;
  25972. exports.Triangle = Triangle;
  25973. exports.Vector2 = Vector2;
  25974. exports.Vector3 = Vector3;
  25975. exports.Vector4 = Vector4;
  25976. exports.CubicInterpolant = CubicInterpolant;
  25977. exports.DiscreteInterpolant = DiscreteInterpolant;
  25978. exports.LinearInterpolant = LinearInterpolant;
  25979. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  25980. exports.Bone = Bone;
  25981. exports.Group = Group;
  25982. exports.LensFlare = LensFlare;
  25983. exports.Line = Line;
  25984. exports.LineSegments = LineSegments;
  25985. exports.LOD = LOD;
  25986. exports.Mesh = Mesh;
  25987. exports.Points = Points;
  25988. exports.Skeleton = Skeleton;
  25989. exports.SkinnedMesh = SkinnedMesh;
  25990. exports.Sprite = Sprite;
  25991. exports.WebGL2Renderer = WebGL2Renderer;
  25992. exports.WebGLRenderer = WebGLRenderer;
  25993. exports.WebGLRenderTarget = WebGLRenderTarget;
  25994. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  25995. exports.ShaderChunk = ShaderChunk;
  25996. exports.ShaderLib = ShaderLib;
  25997. exports.UniformsLib = UniformsLib;
  25998. exports.UniformsUtils = UniformsUtils;
  25999. exports.WebGLBufferRenderer = WebGLBufferRenderer;
  26000. exports.WebGLCapabilities = WebGLCapabilities;
  26001. exports.WebGLClipping = WebGLClipping;
  26002. exports.WebGLExtensions = WebGLExtensions;
  26003. exports.WebGLGeometries = WebGLGeometries;
  26004. exports.WebGLIndexedBufferRenderer = WebGLIndexedBufferRenderer;
  26005. exports.WebGLLights = WebGLLights;
  26006. exports.WebGLObjects = WebGLObjects;
  26007. exports.WebGLProgram = WebGLProgram;
  26008. exports.WebGLProperties = WebGLProperties;
  26009. exports.WebGLShader = WebGLShader;
  26010. exports.WebGLShadowMap = WebGLShadowMap;
  26011. exports.WebGLState = WebGLState;
  26012. exports.WebGLTextures = WebGLTextures;
  26013. exports.WebGLUniforms = WebGLUniforms;
  26014. exports.LensFlarePlugin = LensFlarePlugin;
  26015. exports.SpritePlugin = SpritePlugin;
  26016. exports.Fog = Fog;
  26017. exports.FogExp2 = FogExp2;
  26018. exports.Scene = Scene;
  26019. exports.CanvasTexture = CanvasTexture;
  26020. exports.CompressedTexture = CompressedTexture;
  26021. exports.CubeTexture = CubeTexture;
  26022. exports.DataTexture = DataTexture;
  26023. exports.DepthTexture = DepthTexture;
  26024. exports.Texture = Texture;
  26025. exports.VideoTexture = VideoTexture;
  26026. exports.REVISION = REVISION;
  26027. exports.MOUSE = MOUSE;
  26028. exports.CullFaceNone = CullFaceNone;
  26029. exports.CullFaceBack = CullFaceBack;
  26030. exports.CullFaceFront = CullFaceFront;
  26031. exports.CullFaceFrontBack = CullFaceFrontBack;
  26032. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  26033. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  26034. exports.BasicShadowMap = BasicShadowMap;
  26035. exports.PCFShadowMap = PCFShadowMap;
  26036. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  26037. exports.FrontSide = FrontSide;
  26038. exports.BackSide = BackSide;
  26039. exports.DoubleSide = DoubleSide;
  26040. exports.FlatShading = FlatShading;
  26041. exports.SmoothShading = SmoothShading;
  26042. exports.NoColors = NoColors;
  26043. exports.FaceColors = FaceColors;
  26044. exports.VertexColors = VertexColors;
  26045. exports.NoBlending = NoBlending;
  26046. exports.NormalBlending = NormalBlending;
  26047. exports.AdditiveBlending = AdditiveBlending;
  26048. exports.SubtractiveBlending = SubtractiveBlending;
  26049. exports.MultiplyBlending = MultiplyBlending;
  26050. exports.CustomBlending = CustomBlending;
  26051. exports.AddEquation = AddEquation;
  26052. exports.SubtractEquation = SubtractEquation;
  26053. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  26054. exports.MinEquation = MinEquation;
  26055. exports.MaxEquation = MaxEquation;
  26056. exports.ZeroFactor = ZeroFactor;
  26057. exports.OneFactor = OneFactor;
  26058. exports.SrcColorFactor = SrcColorFactor;
  26059. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  26060. exports.SrcAlphaFactor = SrcAlphaFactor;
  26061. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  26062. exports.DstAlphaFactor = DstAlphaFactor;
  26063. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  26064. exports.DstColorFactor = DstColorFactor;
  26065. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  26066. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  26067. exports.NeverDepth = NeverDepth;
  26068. exports.AlwaysDepth = AlwaysDepth;
  26069. exports.LessDepth = LessDepth;
  26070. exports.LessEqualDepth = LessEqualDepth;
  26071. exports.EqualDepth = EqualDepth;
  26072. exports.GreaterEqualDepth = GreaterEqualDepth;
  26073. exports.GreaterDepth = GreaterDepth;
  26074. exports.NotEqualDepth = NotEqualDepth;
  26075. exports.MultiplyOperation = MultiplyOperation;
  26076. exports.MixOperation = MixOperation;
  26077. exports.AddOperation = AddOperation;
  26078. exports.NoToneMapping = NoToneMapping;
  26079. exports.LinearToneMapping = LinearToneMapping;
  26080. exports.ReinhardToneMapping = ReinhardToneMapping;
  26081. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  26082. exports.CineonToneMapping = CineonToneMapping;
  26083. exports.UVMapping = UVMapping;
  26084. exports.CubeReflectionMapping = CubeReflectionMapping;
  26085. exports.CubeRefractionMapping = CubeRefractionMapping;
  26086. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  26087. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  26088. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  26089. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  26090. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  26091. exports.RepeatWrapping = RepeatWrapping;
  26092. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  26093. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  26094. exports.NearestFilter = NearestFilter;
  26095. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  26096. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  26097. exports.LinearFilter = LinearFilter;
  26098. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  26099. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  26100. exports.UnsignedByteType = UnsignedByteType;
  26101. exports.ByteType = ByteType;
  26102. exports.ShortType = ShortType;
  26103. exports.UnsignedShortType = UnsignedShortType;
  26104. exports.IntType = IntType;
  26105. exports.UnsignedIntType = UnsignedIntType;
  26106. exports.FloatType = FloatType;
  26107. exports.HalfFloatType = HalfFloatType;
  26108. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  26109. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  26110. exports.UnsignedShort565Type = UnsignedShort565Type;
  26111. exports.UnsignedInt248Type = UnsignedInt248Type;
  26112. exports.AlphaFormat = AlphaFormat;
  26113. exports.RGBFormat = RGBFormat;
  26114. exports.RGBAFormat = RGBAFormat;
  26115. exports.LuminanceFormat = LuminanceFormat;
  26116. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  26117. exports.RGBEFormat = RGBEFormat;
  26118. exports.DepthFormat = DepthFormat;
  26119. exports.DepthStencilFormat = DepthStencilFormat;
  26120. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  26121. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  26122. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  26123. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  26124. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  26125. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  26126. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  26127. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  26128. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  26129. exports.LoopOnce = LoopOnce;
  26130. exports.LoopRepeat = LoopRepeat;
  26131. exports.LoopPingPong = LoopPingPong;
  26132. exports.InterpolateDiscrete = InterpolateDiscrete;
  26133. exports.InterpolateLinear = InterpolateLinear;
  26134. exports.InterpolateSmooth = InterpolateSmooth;
  26135. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  26136. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  26137. exports.WrapAroundEnding = WrapAroundEnding;
  26138. exports.TrianglesDrawMode = TrianglesDrawMode;
  26139. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  26140. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  26141. exports.LinearEncoding = LinearEncoding;
  26142. exports.sRGBEncoding = sRGBEncoding;
  26143. exports.GammaEncoding = GammaEncoding;
  26144. exports.RGBEEncoding = RGBEEncoding;
  26145. exports.LogLuvEncoding = LogLuvEncoding;
  26146. exports.RGBM7Encoding = RGBM7Encoding;
  26147. exports.RGBM16Encoding = RGBM16Encoding;
  26148. exports.RGBDEncoding = RGBDEncoding;
  26149. exports.BasicDepthPacking = BasicDepthPacking;
  26150. exports.RGBADepthPacking = RGBADepthPacking;
  26151. exports.CubeGeometry = BoxGeometry;
  26152. exports.Face4 = Face4;
  26153. exports.LineStrip = LineStrip;
  26154. exports.LinePieces = LinePieces;
  26155. exports.MeshFaceMaterial = MeshFaceMaterial;
  26156. exports.PointCloud = PointCloud;
  26157. exports.Particle = Particle;
  26158. exports.ParticleSystem = ParticleSystem;
  26159. exports.PointCloudMaterial = PointCloudMaterial;
  26160. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  26161. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  26162. exports.Vertex = Vertex;
  26163. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  26164. exports.Int8Attribute = Int8Attribute;
  26165. exports.Uint8Attribute = Uint8Attribute;
  26166. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  26167. exports.Int16Attribute = Int16Attribute;
  26168. exports.Uint16Attribute = Uint16Attribute;
  26169. exports.Int32Attribute = Int32Attribute;
  26170. exports.Uint32Attribute = Uint32Attribute;
  26171. exports.Float32Attribute = Float32Attribute;
  26172. exports.Float64Attribute = Float64Attribute;
  26173. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  26174. exports.SplineCurve3 = SplineCurve3;
  26175. exports.Spline = Spline;
  26176. exports.BoundingBoxHelper = BoundingBoxHelper;
  26177. exports.EdgesHelper = EdgesHelper;
  26178. exports.WireframeHelper = WireframeHelper;
  26179. exports.XHRLoader = XHRLoader;
  26180. exports.BinaryTextureLoader = BinaryTextureLoader;
  26181. exports.GeometryUtils = GeometryUtils;
  26182. exports.ImageUtils = ImageUtils;
  26183. exports.Projector = Projector;
  26184. exports.CanvasRenderer = CanvasRenderer;
  26185. exports.Float64BufferAttribute = Float64BufferAttribute;
  26186. exports.Float32BufferAttribute = Float32BufferAttribute;
  26187. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  26188. exports.Int32BufferAttribute = Int32BufferAttribute;
  26189. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  26190. exports.Int16BufferAttribute = Int16BufferAttribute;
  26191. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  26192. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  26193. exports.Int8BufferAttribute = Int8BufferAttribute;
  26194. exports.BufferAttribute = BufferAttribute;
  26195. exports.CatmullRom = CatmullRom;
  26196. exports.QuadraticBezier = QuadraticBezier;
  26197. exports.CubicBezier = CubicBezier;
  26198. exports.WireframeGeometry = WireframeGeometry;
  26199. exports.ParametricGeometry = ParametricGeometry;
  26200. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  26201. exports.TetrahedronGeometry = TetrahedronGeometry;
  26202. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  26203. exports.OctahedronGeometry = OctahedronGeometry;
  26204. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  26205. exports.IcosahedronGeometry = IcosahedronGeometry;
  26206. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  26207. exports.DodecahedronGeometry = DodecahedronGeometry;
  26208. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  26209. exports.PolyhedronGeometry = PolyhedronGeometry;
  26210. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  26211. exports.TubeGeometry = TubeGeometry;
  26212. exports.TubeBufferGeometry = TubeBufferGeometry;
  26213. exports.TorusKnotGeometry = TorusKnotGeometry;
  26214. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  26215. exports.TorusGeometry = TorusGeometry;
  26216. exports.TorusBufferGeometry = TorusBufferGeometry;
  26217. exports.TextGeometry = TextGeometry;
  26218. exports.SphereGeometry = SphereGeometry;
  26219. exports.SphereBufferGeometry = SphereBufferGeometry;
  26220. exports.RingGeometry = RingGeometry;
  26221. exports.RingBufferGeometry = RingBufferGeometry;
  26222. exports.PlaneGeometry = PlaneGeometry;
  26223. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  26224. exports.LatheGeometry = LatheGeometry;
  26225. exports.LatheBufferGeometry = LatheBufferGeometry;
  26226. exports.ShapeGeometry = ShapeGeometry;
  26227. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  26228. exports.ExtrudeGeometry = ExtrudeGeometry;
  26229. exports.EdgesGeometry = EdgesGeometry;
  26230. exports.ConeGeometry = ConeGeometry;
  26231. exports.ConeBufferGeometry = ConeBufferGeometry;
  26232. exports.CylinderGeometry = CylinderGeometry;
  26233. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  26234. exports.CircleGeometry = CircleGeometry;
  26235. exports.CircleBufferGeometry = CircleBufferGeometry;
  26236. exports.BoxGeometry = BoxGeometry;
  26237. exports.BoxBufferGeometry = BoxBufferGeometry;
  26238. exports.ShadowMaterial = ShadowMaterial;
  26239. exports.SpriteMaterial = SpriteMaterial;
  26240. exports.RawShaderMaterial = RawShaderMaterial;
  26241. exports.ShaderMaterial = ShaderMaterial;
  26242. exports.PointsMaterial = PointsMaterial;
  26243. exports.MultiMaterial = MultiMaterial;
  26244. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  26245. exports.MeshStandardMaterial = MeshStandardMaterial;
  26246. exports.MeshPhongMaterial = MeshPhongMaterial;
  26247. exports.MeshToonMaterial = MeshToonMaterial;
  26248. exports.MeshNormalMaterial = MeshNormalMaterial;
  26249. exports.MeshLambertMaterial = MeshLambertMaterial;
  26250. exports.MeshDepthMaterial = MeshDepthMaterial;
  26251. exports.MeshBasicMaterial = MeshBasicMaterial;
  26252. exports.LineDashedMaterial = LineDashedMaterial;
  26253. exports.LineBasicMaterial = LineBasicMaterial;
  26254. exports.Material = Material;
  26255. Object.defineProperty(exports, '__esModule', { value: true });
  26256. })));