three.core.js 1.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '180dev';
  7. /**
  8. * Represents mouse buttons and interaction types in context of controls.
  9. *
  10. * @type {ConstantsMouse}
  11. * @constant
  12. */
  13. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  14. /**
  15. * Represents touch interaction types in context of controls.
  16. *
  17. * @type {ConstantsTouch}
  18. * @constant
  19. */
  20. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  21. /**
  22. * Disables face culling.
  23. *
  24. * @type {number}
  25. * @constant
  26. */
  27. const CullFaceNone = 0;
  28. /**
  29. * Culls back faces.
  30. *
  31. * @type {number}
  32. * @constant
  33. */
  34. const CullFaceBack = 1;
  35. /**
  36. * Culls front faces.
  37. *
  38. * @type {number}
  39. * @constant
  40. */
  41. const CullFaceFront = 2;
  42. /**
  43. * Culls both front and back faces.
  44. *
  45. * @type {number}
  46. * @constant
  47. */
  48. const CullFaceFrontBack = 3;
  49. /**
  50. * Gives unfiltered shadow maps - fastest, but lowest quality.
  51. *
  52. * @type {number}
  53. * @constant
  54. */
  55. const BasicShadowMap = 0;
  56. /**
  57. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm.
  58. *
  59. * @type {number}
  60. * @constant
  61. */
  62. const PCFShadowMap = 1;
  63. /**
  64. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm with
  65. * better soft shadows especially when using low-resolution shadow maps.
  66. *
  67. * @type {number}
  68. * @constant
  69. */
  70. const PCFSoftShadowMap = 2;
  71. /**
  72. * Filters shadow maps using the Variance Shadow Map (VSM) algorithm.
  73. * When using VSMShadowMap all shadow receivers will also cast shadows.
  74. *
  75. * @type {number}
  76. * @constant
  77. */
  78. const VSMShadowMap = 3;
  79. /**
  80. * Only front faces are rendered.
  81. *
  82. * @type {number}
  83. * @constant
  84. */
  85. const FrontSide = 0;
  86. /**
  87. * Only back faces are rendered.
  88. *
  89. * @type {number}
  90. * @constant
  91. */
  92. const BackSide = 1;
  93. /**
  94. * Both front and back faces are rendered.
  95. *
  96. * @type {number}
  97. * @constant
  98. */
  99. const DoubleSide = 2;
  100. /**
  101. * No blending is performed which effectively disables
  102. * alpha transparency.
  103. *
  104. * @type {number}
  105. * @constant
  106. */
  107. const NoBlending = 0;
  108. /**
  109. * The default blending.
  110. *
  111. * @type {number}
  112. * @constant
  113. */
  114. const NormalBlending = 1;
  115. /**
  116. * Represents additive blending.
  117. *
  118. * @type {number}
  119. * @constant
  120. */
  121. const AdditiveBlending = 2;
  122. /**
  123. * Represents subtractive blending.
  124. *
  125. * @type {number}
  126. * @constant
  127. */
  128. const SubtractiveBlending = 3;
  129. /**
  130. * Represents multiply blending.
  131. *
  132. * @type {number}
  133. * @constant
  134. */
  135. const MultiplyBlending = 4;
  136. /**
  137. * Represents custom blending.
  138. *
  139. * @type {number}
  140. * @constant
  141. */
  142. const CustomBlending = 5;
  143. /**
  144. * A `source + destination` blending equation.
  145. *
  146. * @type {number}
  147. * @constant
  148. */
  149. const AddEquation = 100;
  150. /**
  151. * A `source - destination` blending equation.
  152. *
  153. * @type {number}
  154. * @constant
  155. */
  156. const SubtractEquation = 101;
  157. /**
  158. * A `destination - source` blending equation.
  159. *
  160. * @type {number}
  161. * @constant
  162. */
  163. const ReverseSubtractEquation = 102;
  164. /**
  165. * A blend equation that uses the minimum of source and destination.
  166. *
  167. * @type {number}
  168. * @constant
  169. */
  170. const MinEquation = 103;
  171. /**
  172. * A blend equation that uses the maximum of source and destination.
  173. *
  174. * @type {number}
  175. * @constant
  176. */
  177. const MaxEquation = 104;
  178. /**
  179. * Multiplies all colors by `0`.
  180. *
  181. * @type {number}
  182. * @constant
  183. */
  184. const ZeroFactor = 200;
  185. /**
  186. * Multiplies all colors by `1`.
  187. *
  188. * @type {number}
  189. * @constant
  190. */
  191. const OneFactor = 201;
  192. /**
  193. * Multiplies all colors by the source colors.
  194. *
  195. * @type {number}
  196. * @constant
  197. */
  198. const SrcColorFactor = 202;
  199. /**
  200. * Multiplies all colors by `1` minus each source color.
  201. *
  202. * @type {number}
  203. * @constant
  204. */
  205. const OneMinusSrcColorFactor = 203;
  206. /**
  207. * Multiplies all colors by the source alpha value.
  208. *
  209. * @type {number}
  210. * @constant
  211. */
  212. const SrcAlphaFactor = 204;
  213. /**
  214. * Multiplies all colors by 1 minus the source alpha value.
  215. *
  216. * @type {number}
  217. * @constant
  218. */
  219. const OneMinusSrcAlphaFactor = 205;
  220. /**
  221. * Multiplies all colors by the destination alpha value.
  222. *
  223. * @type {number}
  224. * @constant
  225. */
  226. const DstAlphaFactor = 206;
  227. /**
  228. * Multiplies all colors by `1` minus the destination alpha value.
  229. *
  230. * @type {number}
  231. * @constant
  232. */
  233. const OneMinusDstAlphaFactor = 207;
  234. /**
  235. * Multiplies all colors by the destination color.
  236. *
  237. * @type {number}
  238. * @constant
  239. */
  240. const DstColorFactor = 208;
  241. /**
  242. * Multiplies all colors by `1` minus each destination color.
  243. *
  244. * @type {number}
  245. * @constant
  246. */
  247. const OneMinusDstColorFactor = 209;
  248. /**
  249. * Multiplies the RGB colors by the smaller of either the source alpha
  250. * value or the value of `1` minus the destination alpha value. The alpha
  251. * value is multiplied by `1`.
  252. *
  253. * @type {number}
  254. * @constant
  255. */
  256. const SrcAlphaSaturateFactor = 210;
  257. /**
  258. * Multiplies all colors by a constant color.
  259. *
  260. * @type {number}
  261. * @constant
  262. */
  263. const ConstantColorFactor = 211;
  264. /**
  265. * Multiplies all colors by `1` minus a constant color.
  266. *
  267. * @type {number}
  268. * @constant
  269. */
  270. const OneMinusConstantColorFactor = 212;
  271. /**
  272. * Multiplies all colors by a constant alpha value.
  273. *
  274. * @type {number}
  275. * @constant
  276. */
  277. const ConstantAlphaFactor = 213;
  278. /**
  279. * Multiplies all colors by 1 minus a constant alpha value.
  280. *
  281. * @type {number}
  282. * @constant
  283. */
  284. const OneMinusConstantAlphaFactor = 214;
  285. /**
  286. * Never pass.
  287. *
  288. * @type {number}
  289. * @constant
  290. */
  291. const NeverDepth = 0;
  292. /**
  293. * Always pass.
  294. *
  295. * @type {number}
  296. * @constant
  297. */
  298. const AlwaysDepth = 1;
  299. /**
  300. * Pass if the incoming value is less than the depth buffer value.
  301. *
  302. * @type {number}
  303. * @constant
  304. */
  305. const LessDepth = 2;
  306. /**
  307. * Pass if the incoming value is less than or equal to the depth buffer value.
  308. *
  309. * @type {number}
  310. * @constant
  311. */
  312. const LessEqualDepth = 3;
  313. /**
  314. * Pass if the incoming value equals the depth buffer value.
  315. *
  316. * @type {number}
  317. * @constant
  318. */
  319. const EqualDepth = 4;
  320. /**
  321. * Pass if the incoming value is greater than or equal to the depth buffer value.
  322. *
  323. * @type {number}
  324. * @constant
  325. */
  326. const GreaterEqualDepth = 5;
  327. /**
  328. * Pass if the incoming value is greater than the depth buffer value.
  329. *
  330. * @type {number}
  331. * @constant
  332. */
  333. const GreaterDepth = 6;
  334. /**
  335. * Pass if the incoming value is not equal to the depth buffer value.
  336. *
  337. * @type {number}
  338. * @constant
  339. */
  340. const NotEqualDepth = 7;
  341. /**
  342. * Multiplies the environment map color with the surface color.
  343. *
  344. * @type {number}
  345. * @constant
  346. */
  347. const MultiplyOperation = 0;
  348. /**
  349. * Uses reflectivity to blend between the two colors.
  350. *
  351. * @type {number}
  352. * @constant
  353. */
  354. const MixOperation = 1;
  355. /**
  356. * Adds the two colors.
  357. *
  358. * @type {number}
  359. * @constant
  360. */
  361. const AddOperation = 2;
  362. /**
  363. * No tone mapping is applied.
  364. *
  365. * @type {number}
  366. * @constant
  367. */
  368. const NoToneMapping = 0;
  369. /**
  370. * Linear tone mapping.
  371. *
  372. * @type {number}
  373. * @constant
  374. */
  375. const LinearToneMapping = 1;
  376. /**
  377. * Reinhard tone mapping.
  378. *
  379. * @type {number}
  380. * @constant
  381. */
  382. const ReinhardToneMapping = 2;
  383. /**
  384. * Cineon tone mapping.
  385. *
  386. * @type {number}
  387. * @constant
  388. */
  389. const CineonToneMapping = 3;
  390. /**
  391. * ACES Filmic tone mapping.
  392. *
  393. * @type {number}
  394. * @constant
  395. */
  396. const ACESFilmicToneMapping = 4;
  397. /**
  398. * Custom tone mapping.
  399. *
  400. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  401. *
  402. * @type {number}
  403. * @constant
  404. */
  405. const CustomToneMapping = 5;
  406. /**
  407. * AgX tone mapping.
  408. *
  409. * @type {number}
  410. * @constant
  411. */
  412. const AgXToneMapping = 6;
  413. /**
  414. * Neutral tone mapping.
  415. *
  416. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  417. *
  418. * @type {number}
  419. * @constant
  420. */
  421. const NeutralToneMapping = 7;
  422. /**
  423. * The skinned mesh shares the same world space as the skeleton.
  424. *
  425. * @type {string}
  426. * @constant
  427. */
  428. const AttachedBindMode = 'attached';
  429. /**
  430. * The skinned mesh does not share the same world space as the skeleton.
  431. * This is useful when a skeleton is shared across multiple skinned meshes.
  432. *
  433. * @type {string}
  434. * @constant
  435. */
  436. const DetachedBindMode = 'detached';
  437. /**
  438. * Maps textures using the geometry's UV coordinates.
  439. *
  440. * @type {number}
  441. * @constant
  442. */
  443. const UVMapping = 300;
  444. /**
  445. * Reflection mapping for cube textures.
  446. *
  447. * @type {number}
  448. * @constant
  449. */
  450. const CubeReflectionMapping = 301;
  451. /**
  452. * Refraction mapping for cube textures.
  453. *
  454. * @type {number}
  455. * @constant
  456. */
  457. const CubeRefractionMapping = 302;
  458. /**
  459. * Reflection mapping for equirectangular textures.
  460. *
  461. * @type {number}
  462. * @constant
  463. */
  464. const EquirectangularReflectionMapping = 303;
  465. /**
  466. * Refraction mapping for equirectangular textures.
  467. *
  468. * @type {number}
  469. * @constant
  470. */
  471. const EquirectangularRefractionMapping = 304;
  472. /**
  473. * Reflection mapping for PMREM textures.
  474. *
  475. * @type {number}
  476. * @constant
  477. */
  478. const CubeUVReflectionMapping = 306;
  479. /**
  480. * The texture will simply repeat to infinity.
  481. *
  482. * @type {number}
  483. * @constant
  484. */
  485. const RepeatWrapping = 1000;
  486. /**
  487. * The last pixel of the texture stretches to the edge of the mesh.
  488. *
  489. * @type {number}
  490. * @constant
  491. */
  492. const ClampToEdgeWrapping = 1001;
  493. /**
  494. * The texture will repeats to infinity, mirroring on each repeat.
  495. *
  496. * @type {number}
  497. * @constant
  498. */
  499. const MirroredRepeatWrapping = 1002;
  500. /**
  501. * Returns the value of the texture element that is nearest (in Manhattan distance)
  502. * to the specified texture coordinates.
  503. *
  504. * @type {number}
  505. * @constant
  506. */
  507. const NearestFilter = 1003;
  508. /**
  509. * Chooses the mipmap that most closely matches the size of the pixel being textured
  510. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  511. * to produce a texture value.
  512. *
  513. * @type {number}
  514. * @constant
  515. */
  516. const NearestMipmapNearestFilter = 1004;
  517. const NearestMipMapNearestFilter = 1004; // legacy
  518. /**
  519. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  520. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  521. * The final texture value is a weighted average of those two values.
  522. *
  523. * @type {number}
  524. * @constant
  525. */
  526. const NearestMipmapLinearFilter = 1005;
  527. const NearestMipMapLinearFilter = 1005; // legacy
  528. /**
  529. * Returns the weighted average of the four texture elements that are closest to the specified
  530. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  531. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  532. *
  533. * @type {number}
  534. * @constant
  535. */
  536. const LinearFilter = 1006;
  537. /**
  538. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  539. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  540. * center of the pixel) to produce a texture value.
  541. *
  542. * @type {number}
  543. * @constant
  544. */
  545. const LinearMipmapNearestFilter = 1007;
  546. const LinearMipMapNearestFilter = 1007; // legacy
  547. /**
  548. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  549. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  550. * is a weighted average of those two values.
  551. *
  552. * @type {number}
  553. * @constant
  554. */
  555. const LinearMipmapLinearFilter = 1008;
  556. const LinearMipMapLinearFilter = 1008; // legacy
  557. /**
  558. * An unsigned byte data type for textures.
  559. *
  560. * @type {number}
  561. * @constant
  562. */
  563. const UnsignedByteType = 1009;
  564. /**
  565. * A byte data type for textures.
  566. *
  567. * @type {number}
  568. * @constant
  569. */
  570. const ByteType = 1010;
  571. /**
  572. * A short data type for textures.
  573. *
  574. * @type {number}
  575. * @constant
  576. */
  577. const ShortType = 1011;
  578. /**
  579. * An unsigned short data type for textures.
  580. *
  581. * @type {number}
  582. * @constant
  583. */
  584. const UnsignedShortType = 1012;
  585. /**
  586. * An int data type for textures.
  587. *
  588. * @type {number}
  589. * @constant
  590. */
  591. const IntType = 1013;
  592. /**
  593. * An unsigned int data type for textures.
  594. *
  595. * @type {number}
  596. * @constant
  597. */
  598. const UnsignedIntType = 1014;
  599. /**
  600. * A float data type for textures.
  601. *
  602. * @type {number}
  603. * @constant
  604. */
  605. const FloatType = 1015;
  606. /**
  607. * A half float data type for textures.
  608. *
  609. * @type {number}
  610. * @constant
  611. */
  612. const HalfFloatType = 1016;
  613. /**
  614. * An unsigned short 4_4_4_4 (packed) data type for textures.
  615. *
  616. * @type {number}
  617. * @constant
  618. */
  619. const UnsignedShort4444Type = 1017;
  620. /**
  621. * An unsigned short 5_5_5_1 (packed) data type for textures.
  622. *
  623. * @type {number}
  624. * @constant
  625. */
  626. const UnsignedShort5551Type = 1018;
  627. /**
  628. * An unsigned int 24_8 data type for textures.
  629. *
  630. * @type {number}
  631. * @constant
  632. */
  633. const UnsignedInt248Type = 1020;
  634. /**
  635. * An unsigned int 5_9_9_9 (packed) data type for textures.
  636. *
  637. * @type {number}
  638. * @constant
  639. */
  640. const UnsignedInt5999Type = 35902;
  641. /**
  642. * An unsigned int 10_11_11 (packed) data type for textures.
  643. *
  644. * @type {number}
  645. * @constant
  646. */
  647. const UnsignedInt101111Type = 35899;
  648. /**
  649. * Discards the red, green and blue components and reads just the alpha component.
  650. *
  651. * @type {number}
  652. * @constant
  653. */
  654. const AlphaFormat = 1021;
  655. /**
  656. * Discards the alpha component and reads the red, green and blue component.
  657. *
  658. * @type {number}
  659. * @constant
  660. */
  661. const RGBFormat = 1022;
  662. /**
  663. * Reads the red, green, blue and alpha components.
  664. *
  665. * @type {number}
  666. * @constant
  667. */
  668. const RGBAFormat = 1023;
  669. /**
  670. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  671. *
  672. * @type {number}
  673. * @constant
  674. */
  675. const DepthFormat = 1026;
  676. /**
  677. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  678. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  679. *
  680. * @type {number}
  681. * @constant
  682. */
  683. const DepthStencilFormat = 1027;
  684. /**
  685. * Discards the green, blue and alpha components and reads just the red component.
  686. *
  687. * @type {number}
  688. * @constant
  689. */
  690. const RedFormat = 1028;
  691. /**
  692. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  693. *
  694. * @type {number}
  695. * @constant
  696. */
  697. const RedIntegerFormat = 1029;
  698. /**
  699. * Discards the alpha, and blue components and reads the red, and green components.
  700. *
  701. * @type {number}
  702. * @constant
  703. */
  704. const RGFormat = 1030;
  705. /**
  706. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  707. *
  708. * @type {number}
  709. * @constant
  710. */
  711. const RGIntegerFormat = 1031;
  712. /**
  713. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  714. *
  715. * @type {number}
  716. * @constant
  717. */
  718. const RGBIntegerFormat = 1032;
  719. /**
  720. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  721. *
  722. * @type {number}
  723. * @constant
  724. */
  725. const RGBAIntegerFormat = 1033;
  726. /**
  727. * A DXT1-compressed image in an RGB image format.
  728. *
  729. * @type {number}
  730. * @constant
  731. */
  732. const RGB_S3TC_DXT1_Format = 33776;
  733. /**
  734. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  735. *
  736. * @type {number}
  737. * @constant
  738. */
  739. const RGBA_S3TC_DXT1_Format = 33777;
  740. /**
  741. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  742. *
  743. * @type {number}
  744. * @constant
  745. */
  746. const RGBA_S3TC_DXT3_Format = 33778;
  747. /**
  748. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  749. * compression in how the alpha compression is done.
  750. *
  751. * @type {number}
  752. * @constant
  753. */
  754. const RGBA_S3TC_DXT5_Format = 33779;
  755. /**
  756. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  757. *
  758. * @type {number}
  759. * @constant
  760. */
  761. const RGB_PVRTC_4BPPV1_Format = 35840;
  762. /**
  763. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  764. *
  765. * @type {number}
  766. * @constant
  767. */
  768. const RGB_PVRTC_2BPPV1_Format = 35841;
  769. /**
  770. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  771. *
  772. * @type {number}
  773. * @constant
  774. */
  775. const RGBA_PVRTC_4BPPV1_Format = 35842;
  776. /**
  777. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  778. *
  779. * @type {number}
  780. * @constant
  781. */
  782. const RGBA_PVRTC_2BPPV1_Format = 35843;
  783. /**
  784. * ETC1 RGB format.
  785. *
  786. * @type {number}
  787. * @constant
  788. */
  789. const RGB_ETC1_Format = 36196;
  790. /**
  791. * ETC2 RGB format.
  792. *
  793. * @type {number}
  794. * @constant
  795. */
  796. const RGB_ETC2_Format = 37492;
  797. /**
  798. * ETC2 RGBA format.
  799. *
  800. * @type {number}
  801. * @constant
  802. */
  803. const RGBA_ETC2_EAC_Format = 37496;
  804. /**
  805. * ASTC RGBA 4x4 format.
  806. *
  807. * @type {number}
  808. * @constant
  809. */
  810. const RGBA_ASTC_4x4_Format = 37808;
  811. /**
  812. * ASTC RGBA 5x4 format.
  813. *
  814. * @type {number}
  815. * @constant
  816. */
  817. const RGBA_ASTC_5x4_Format = 37809;
  818. /**
  819. * ASTC RGBA 5x5 format.
  820. *
  821. * @type {number}
  822. * @constant
  823. */
  824. const RGBA_ASTC_5x5_Format = 37810;
  825. /**
  826. * ASTC RGBA 6x5 format.
  827. *
  828. * @type {number}
  829. * @constant
  830. */
  831. const RGBA_ASTC_6x5_Format = 37811;
  832. /**
  833. * ASTC RGBA 6x6 format.
  834. *
  835. * @type {number}
  836. * @constant
  837. */
  838. const RGBA_ASTC_6x6_Format = 37812;
  839. /**
  840. * ASTC RGBA 8x5 format.
  841. *
  842. * @type {number}
  843. * @constant
  844. */
  845. const RGBA_ASTC_8x5_Format = 37813;
  846. /**
  847. * ASTC RGBA 8x6 format.
  848. *
  849. * @type {number}
  850. * @constant
  851. */
  852. const RGBA_ASTC_8x6_Format = 37814;
  853. /**
  854. * ASTC RGBA 8x8 format.
  855. *
  856. * @type {number}
  857. * @constant
  858. */
  859. const RGBA_ASTC_8x8_Format = 37815;
  860. /**
  861. * ASTC RGBA 10x5 format.
  862. *
  863. * @type {number}
  864. * @constant
  865. */
  866. const RGBA_ASTC_10x5_Format = 37816;
  867. /**
  868. * ASTC RGBA 10x6 format.
  869. *
  870. * @type {number}
  871. * @constant
  872. */
  873. const RGBA_ASTC_10x6_Format = 37817;
  874. /**
  875. * ASTC RGBA 10x8 format.
  876. *
  877. * @type {number}
  878. * @constant
  879. */
  880. const RGBA_ASTC_10x8_Format = 37818;
  881. /**
  882. * ASTC RGBA 10x10 format.
  883. *
  884. * @type {number}
  885. * @constant
  886. */
  887. const RGBA_ASTC_10x10_Format = 37819;
  888. /**
  889. * ASTC RGBA 12x10 format.
  890. *
  891. * @type {number}
  892. * @constant
  893. */
  894. const RGBA_ASTC_12x10_Format = 37820;
  895. /**
  896. * ASTC RGBA 12x12 format.
  897. *
  898. * @type {number}
  899. * @constant
  900. */
  901. const RGBA_ASTC_12x12_Format = 37821;
  902. /**
  903. * BPTC RGBA format.
  904. *
  905. * @type {number}
  906. * @constant
  907. */
  908. const RGBA_BPTC_Format = 36492;
  909. /**
  910. * BPTC Signed RGB format.
  911. *
  912. * @type {number}
  913. * @constant
  914. */
  915. const RGB_BPTC_SIGNED_Format = 36494;
  916. /**
  917. * BPTC Unsigned RGB format.
  918. *
  919. * @type {number}
  920. * @constant
  921. */
  922. const RGB_BPTC_UNSIGNED_Format = 36495;
  923. /**
  924. * RGTC1 Red format.
  925. *
  926. * @type {number}
  927. * @constant
  928. */
  929. const RED_RGTC1_Format = 36283;
  930. /**
  931. * RGTC1 Signed Red format.
  932. *
  933. * @type {number}
  934. * @constant
  935. */
  936. const SIGNED_RED_RGTC1_Format = 36284;
  937. /**
  938. * RGTC2 Red Green format.
  939. *
  940. * @type {number}
  941. * @constant
  942. */
  943. const RED_GREEN_RGTC2_Format = 36285;
  944. /**
  945. * RGTC2 Signed Red Green format.
  946. *
  947. * @type {number}
  948. * @constant
  949. */
  950. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  951. /**
  952. * Animations are played once.
  953. *
  954. * @type {number}
  955. * @constant
  956. */
  957. const LoopOnce = 2200;
  958. /**
  959. * Animations are played with a chosen number of repetitions, each time jumping from
  960. * the end of the clip directly to its beginning.
  961. *
  962. * @type {number}
  963. * @constant
  964. */
  965. const LoopRepeat = 2201;
  966. /**
  967. * Animations are played with a chosen number of repetitions, alternately playing forward
  968. * and backward.
  969. *
  970. * @type {number}
  971. * @constant
  972. */
  973. const LoopPingPong = 2202;
  974. /**
  975. * Discrete interpolation mode for keyframe tracks.
  976. *
  977. * @type {number}
  978. * @constant
  979. */
  980. const InterpolateDiscrete = 2300;
  981. /**
  982. * Linear interpolation mode for keyframe tracks.
  983. *
  984. * @type {number}
  985. * @constant
  986. */
  987. const InterpolateLinear = 2301;
  988. /**
  989. * Smooth interpolation mode for keyframe tracks.
  990. *
  991. * @type {number}
  992. * @constant
  993. */
  994. const InterpolateSmooth = 2302;
  995. /**
  996. * Zero curvature ending for animations.
  997. *
  998. * @type {number}
  999. * @constant
  1000. */
  1001. const ZeroCurvatureEnding = 2400;
  1002. /**
  1003. * Zero slope ending for animations.
  1004. *
  1005. * @type {number}
  1006. * @constant
  1007. */
  1008. const ZeroSlopeEnding = 2401;
  1009. /**
  1010. * Wrap around ending for animations.
  1011. *
  1012. * @type {number}
  1013. * @constant
  1014. */
  1015. const WrapAroundEnding = 2402;
  1016. /**
  1017. * Default animation blend mode.
  1018. *
  1019. * @type {number}
  1020. * @constant
  1021. */
  1022. const NormalAnimationBlendMode = 2500;
  1023. /**
  1024. * Additive animation blend mode. Can be used to layer motions on top of
  1025. * each other to build complex performances from smaller re-usable assets.
  1026. *
  1027. * @type {number}
  1028. * @constant
  1029. */
  1030. const AdditiveAnimationBlendMode = 2501;
  1031. /**
  1032. * For every three vertices draw a single triangle.
  1033. *
  1034. * @type {number}
  1035. * @constant
  1036. */
  1037. const TrianglesDrawMode = 0;
  1038. /**
  1039. * For each vertex draw a triangle from the last three vertices.
  1040. *
  1041. * @type {number}
  1042. * @constant
  1043. */
  1044. const TriangleStripDrawMode = 1;
  1045. /**
  1046. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1047. *
  1048. * @type {number}
  1049. * @constant
  1050. */
  1051. const TriangleFanDrawMode = 2;
  1052. /**
  1053. * Basic depth packing.
  1054. *
  1055. * @type {number}
  1056. * @constant
  1057. */
  1058. const BasicDepthPacking = 3200;
  1059. /**
  1060. * A depth value is packed into 32 bit RGBA.
  1061. *
  1062. * @type {number}
  1063. * @constant
  1064. */
  1065. const RGBADepthPacking = 3201;
  1066. /**
  1067. * A depth value is packed into 24 bit RGB.
  1068. *
  1069. * @type {number}
  1070. * @constant
  1071. */
  1072. const RGBDepthPacking = 3202;
  1073. /**
  1074. * A depth value is packed into 16 bit RG.
  1075. *
  1076. * @type {number}
  1077. * @constant
  1078. */
  1079. const RGDepthPacking = 3203;
  1080. /**
  1081. * Normal information is relative to the underlying surface.
  1082. *
  1083. * @type {number}
  1084. * @constant
  1085. */
  1086. const TangentSpaceNormalMap = 0;
  1087. /**
  1088. * Normal information is relative to the object orientation.
  1089. *
  1090. * @type {number}
  1091. * @constant
  1092. */
  1093. const ObjectSpaceNormalMap = 1;
  1094. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1095. /**
  1096. * No color space.
  1097. *
  1098. * @type {string}
  1099. * @constant
  1100. */
  1101. const NoColorSpace = '';
  1102. /**
  1103. * sRGB color space.
  1104. *
  1105. * @type {string}
  1106. * @constant
  1107. */
  1108. const SRGBColorSpace = 'srgb';
  1109. /**
  1110. * sRGB-linear color space.
  1111. *
  1112. * @type {string}
  1113. * @constant
  1114. */
  1115. const LinearSRGBColorSpace = 'srgb-linear';
  1116. /**
  1117. * Linear transfer function.
  1118. *
  1119. * @type {string}
  1120. * @constant
  1121. */
  1122. const LinearTransfer = 'linear';
  1123. /**
  1124. * sRGB transfer function.
  1125. *
  1126. * @type {string}
  1127. * @constant
  1128. */
  1129. const SRGBTransfer = 'srgb';
  1130. /**
  1131. * Sets the stencil buffer value to `0`.
  1132. *
  1133. * @type {number}
  1134. * @constant
  1135. */
  1136. const ZeroStencilOp = 0;
  1137. /**
  1138. * Keeps the current value.
  1139. *
  1140. * @type {number}
  1141. * @constant
  1142. */
  1143. const KeepStencilOp = 7680;
  1144. /**
  1145. * Sets the stencil buffer value to the specified reference value.
  1146. *
  1147. * @type {number}
  1148. * @constant
  1149. */
  1150. const ReplaceStencilOp = 7681;
  1151. /**
  1152. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1153. *
  1154. * @type {number}
  1155. * @constant
  1156. */
  1157. const IncrementStencilOp = 7682;
  1158. /**
  1159. * Decrements the current stencil buffer value. Clamps to `0`.
  1160. *
  1161. * @type {number}
  1162. * @constant
  1163. */
  1164. const DecrementStencilOp = 7683;
  1165. /**
  1166. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1167. * the maximum representable unsigned value.
  1168. *
  1169. * @type {number}
  1170. * @constant
  1171. */
  1172. const IncrementWrapStencilOp = 34055;
  1173. /**
  1174. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1175. * unsigned value when decrementing a stencil buffer value of `0`.
  1176. *
  1177. * @type {number}
  1178. * @constant
  1179. */
  1180. const DecrementWrapStencilOp = 34056;
  1181. /**
  1182. * Inverts the current stencil buffer value bitwise.
  1183. *
  1184. * @type {number}
  1185. * @constant
  1186. */
  1187. const InvertStencilOp = 5386;
  1188. /**
  1189. * Will never return true.
  1190. *
  1191. * @type {number}
  1192. * @constant
  1193. */
  1194. const NeverStencilFunc = 512;
  1195. /**
  1196. * Will return true if the stencil reference value is less than the current stencil value.
  1197. *
  1198. * @type {number}
  1199. * @constant
  1200. */
  1201. const LessStencilFunc = 513;
  1202. /**
  1203. * Will return true if the stencil reference value is equal to the current stencil value.
  1204. *
  1205. * @type {number}
  1206. * @constant
  1207. */
  1208. const EqualStencilFunc = 514;
  1209. /**
  1210. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1211. *
  1212. * @type {number}
  1213. * @constant
  1214. */
  1215. const LessEqualStencilFunc = 515;
  1216. /**
  1217. * Will return true if the stencil reference value is greater than the current stencil value.
  1218. *
  1219. * @type {number}
  1220. * @constant
  1221. */
  1222. const GreaterStencilFunc = 516;
  1223. /**
  1224. * Will return true if the stencil reference value is not equal to the current stencil value.
  1225. *
  1226. * @type {number}
  1227. * @constant
  1228. */
  1229. const NotEqualStencilFunc = 517;
  1230. /**
  1231. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1232. *
  1233. * @type {number}
  1234. * @constant
  1235. */
  1236. const GreaterEqualStencilFunc = 518;
  1237. /**
  1238. * Will always return true.
  1239. *
  1240. * @type {number}
  1241. * @constant
  1242. */
  1243. const AlwaysStencilFunc = 519;
  1244. /**
  1245. * Never pass.
  1246. *
  1247. * @type {number}
  1248. * @constant
  1249. */
  1250. const NeverCompare = 512;
  1251. /**
  1252. * Pass if the incoming value is less than the texture value.
  1253. *
  1254. * @type {number}
  1255. * @constant
  1256. */
  1257. const LessCompare = 513;
  1258. /**
  1259. * Pass if the incoming value equals the texture value.
  1260. *
  1261. * @type {number}
  1262. * @constant
  1263. */
  1264. const EqualCompare = 514;
  1265. /**
  1266. * Pass if the incoming value is less than or equal to the texture value.
  1267. *
  1268. * @type {number}
  1269. * @constant
  1270. */
  1271. const LessEqualCompare = 515;
  1272. /**
  1273. * Pass if the incoming value is greater than the texture value.
  1274. *
  1275. * @type {number}
  1276. * @constant
  1277. */
  1278. const GreaterCompare = 516;
  1279. /**
  1280. * Pass if the incoming value is not equal to the texture value.
  1281. *
  1282. * @type {number}
  1283. * @constant
  1284. */
  1285. const NotEqualCompare = 517;
  1286. /**
  1287. * Pass if the incoming value is greater than or equal to the texture value.
  1288. *
  1289. * @type {number}
  1290. * @constant
  1291. */
  1292. const GreaterEqualCompare = 518;
  1293. /**
  1294. * Always pass.
  1295. *
  1296. * @type {number}
  1297. * @constant
  1298. */
  1299. const AlwaysCompare = 519;
  1300. /**
  1301. * The contents are intended to be specified once by the application, and used many
  1302. * times as the source for drawing and image specification commands.
  1303. *
  1304. * @type {number}
  1305. * @constant
  1306. */
  1307. const StaticDrawUsage = 35044;
  1308. /**
  1309. * The contents are intended to be respecified repeatedly by the application, and
  1310. * used many times as the source for drawing and image specification commands.
  1311. *
  1312. * @type {number}
  1313. * @constant
  1314. */
  1315. const DynamicDrawUsage = 35048;
  1316. /**
  1317. * The contents are intended to be specified once by the application, and used at most
  1318. * a few times as the source for drawing and image specification commands.
  1319. *
  1320. * @type {number}
  1321. * @constant
  1322. */
  1323. const StreamDrawUsage = 35040;
  1324. /**
  1325. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1326. * many times by the application.
  1327. *
  1328. * @type {number}
  1329. * @constant
  1330. */
  1331. const StaticReadUsage = 35045;
  1332. /**
  1333. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1334. * many times by the application.
  1335. *
  1336. * @type {number}
  1337. * @constant
  1338. */
  1339. const DynamicReadUsage = 35049;
  1340. /**
  1341. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1342. * a few times by the application
  1343. *
  1344. * @type {number}
  1345. * @constant
  1346. */
  1347. const StreamReadUsage = 35041;
  1348. /**
  1349. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1350. * the source for WebGL drawing and image specification commands.
  1351. *
  1352. * @type {number}
  1353. * @constant
  1354. */
  1355. const StaticCopyUsage = 35046;
  1356. /**
  1357. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1358. * as the source for WebGL drawing and image specification commands.
  1359. *
  1360. * @type {number}
  1361. * @constant
  1362. */
  1363. const DynamicCopyUsage = 35050;
  1364. /**
  1365. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1366. * as the source for WebGL drawing and image specification commands.
  1367. *
  1368. * @type {number}
  1369. * @constant
  1370. */
  1371. const StreamCopyUsage = 35042;
  1372. /**
  1373. * GLSL 1 shader code.
  1374. *
  1375. * @type {string}
  1376. * @constant
  1377. */
  1378. const GLSL1 = '100';
  1379. /**
  1380. * GLSL 3 shader code.
  1381. *
  1382. * @type {string}
  1383. * @constant
  1384. */
  1385. const GLSL3 = '300 es';
  1386. /**
  1387. * WebGL coordinate system.
  1388. *
  1389. * @type {number}
  1390. * @constant
  1391. */
  1392. const WebGLCoordinateSystem = 2000;
  1393. /**
  1394. * WebGPU coordinate system.
  1395. *
  1396. * @type {number}
  1397. * @constant
  1398. */
  1399. const WebGPUCoordinateSystem = 2001;
  1400. /**
  1401. * Represents the different timestamp query types.
  1402. *
  1403. * @type {ConstantsTimestampQuery}
  1404. * @constant
  1405. */
  1406. const TimestampQuery = {
  1407. COMPUTE: 'compute',
  1408. RENDER: 'render'
  1409. };
  1410. /**
  1411. * Represents mouse buttons and interaction types in context of controls.
  1412. *
  1413. * @type {ConstantsInterpolationSamplingType}
  1414. * @constant
  1415. */
  1416. const InterpolationSamplingType = {
  1417. PERSPECTIVE: 'perspective',
  1418. LINEAR: 'linear',
  1419. FLAT: 'flat'
  1420. };
  1421. /**
  1422. * Represents the different interpolation sampling modes.
  1423. *
  1424. * @type {ConstantsInterpolationSamplingMode}
  1425. * @constant
  1426. */
  1427. const InterpolationSamplingMode = {
  1428. NORMAL: 'normal',
  1429. CENTROID: 'centroid',
  1430. SAMPLE: 'sample',
  1431. FIRST: 'first',
  1432. EITHER: 'either'
  1433. };
  1434. /**
  1435. * This type represents mouse buttons and interaction types in context of controls.
  1436. *
  1437. * @typedef {Object} ConstantsMouse
  1438. * @property {number} MIDDLE - The left mouse button.
  1439. * @property {number} LEFT - The middle mouse button.
  1440. * @property {number} RIGHT - The right mouse button.
  1441. * @property {number} ROTATE - A rotate interaction.
  1442. * @property {number} DOLLY - A dolly interaction.
  1443. * @property {number} PAN - A pan interaction.
  1444. **/
  1445. /**
  1446. * This type represents touch interaction types in context of controls.
  1447. *
  1448. * @typedef {Object} ConstantsTouch
  1449. * @property {number} ROTATE - A rotate interaction.
  1450. * @property {number} PAN - A pan interaction.
  1451. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1452. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1453. **/
  1454. /**
  1455. * This type represents the different timestamp query types.
  1456. *
  1457. * @typedef {Object} ConstantsTimestampQuery
  1458. * @property {string} COMPUTE - A `compute` timestamp query.
  1459. * @property {string} RENDER - A `render` timestamp query.
  1460. **/
  1461. /**
  1462. * Represents the different interpolation sampling types.
  1463. *
  1464. * @typedef {Object} ConstantsInterpolationSamplingType
  1465. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1466. * @property {string} LINEAR - Linear interpolation.
  1467. * @property {string} FLAT - Flat interpolation.
  1468. */
  1469. /**
  1470. * Represents the different interpolation sampling modes.
  1471. *
  1472. * @typedef {Object} ConstantsInterpolationSamplingMode
  1473. * @property {string} NORMAL - Normal sampling mode.
  1474. * @property {string} CENTROID - Centroid sampling mode.
  1475. * @property {string} SAMPLE - Sample-specific sampling mode.
  1476. * @property {string} FLAT_FIRST - Flat interpolation using the first vertex.
  1477. * @property {string} FLAT_EITHER - Flat interpolation using either vertex.
  1478. */
  1479. /**
  1480. * This modules allows to dispatch event objects on custom JavaScript objects.
  1481. *
  1482. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  1483. *
  1484. * Code Example:
  1485. * ```js
  1486. * class Car extends EventDispatcher {
  1487. * start() {
  1488. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1489. * }
  1490. *};
  1491. *
  1492. * // Using events with the custom object
  1493. * const car = new Car();
  1494. * car.addEventListener( 'start', function ( event ) {
  1495. * alert( event.message );
  1496. * } );
  1497. *
  1498. * car.start();
  1499. * ```
  1500. */
  1501. class EventDispatcher {
  1502. /**
  1503. * Adds the given event listener to the given event type.
  1504. *
  1505. * @param {string} type - The type of event to listen to.
  1506. * @param {Function} listener - The function that gets called when the event is fired.
  1507. */
  1508. addEventListener( type, listener ) {
  1509. if ( this._listeners === undefined ) this._listeners = {};
  1510. const listeners = this._listeners;
  1511. if ( listeners[ type ] === undefined ) {
  1512. listeners[ type ] = [];
  1513. }
  1514. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1515. listeners[ type ].push( listener );
  1516. }
  1517. }
  1518. /**
  1519. * Returns `true` if the given event listener has been added to the given event type.
  1520. *
  1521. * @param {string} type - The type of event.
  1522. * @param {Function} listener - The listener to check.
  1523. * @return {boolean} Whether the given event listener has been added to the given event type.
  1524. */
  1525. hasEventListener( type, listener ) {
  1526. const listeners = this._listeners;
  1527. if ( listeners === undefined ) return false;
  1528. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1529. }
  1530. /**
  1531. * Removes the given event listener from the given event type.
  1532. *
  1533. * @param {string} type - The type of event.
  1534. * @param {Function} listener - The listener to remove.
  1535. */
  1536. removeEventListener( type, listener ) {
  1537. const listeners = this._listeners;
  1538. if ( listeners === undefined ) return;
  1539. const listenerArray = listeners[ type ];
  1540. if ( listenerArray !== undefined ) {
  1541. const index = listenerArray.indexOf( listener );
  1542. if ( index !== -1 ) {
  1543. listenerArray.splice( index, 1 );
  1544. }
  1545. }
  1546. }
  1547. /**
  1548. * Dispatches an event object.
  1549. *
  1550. * @param {Object} event - The event that gets fired.
  1551. */
  1552. dispatchEvent( event ) {
  1553. const listeners = this._listeners;
  1554. if ( listeners === undefined ) return;
  1555. const listenerArray = listeners[ event.type ];
  1556. if ( listenerArray !== undefined ) {
  1557. event.target = this;
  1558. // Make a copy, in case listeners are removed while iterating.
  1559. const array = listenerArray.slice( 0 );
  1560. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1561. array[ i ].call( this, event );
  1562. }
  1563. event.target = null;
  1564. }
  1565. }
  1566. }
  1567. const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];
  1568. let _seed = 1234567;
  1569. const DEG2RAD = Math.PI / 180;
  1570. const RAD2DEG = 180 / Math.PI;
  1571. /**
  1572. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1573. * (universally unique identifier).
  1574. *
  1575. * @return {string} The UUID.
  1576. */
  1577. function generateUUID() {
  1578. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1579. const d0 = Math.random() * 0xffffffff | 0;
  1580. const d1 = Math.random() * 0xffffffff | 0;
  1581. const d2 = Math.random() * 0xffffffff | 0;
  1582. const d3 = Math.random() * 0xffffffff | 0;
  1583. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1584. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1585. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1586. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1587. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1588. return uuid.toLowerCase();
  1589. }
  1590. /**
  1591. * Clamps the given value between min and max.
  1592. *
  1593. * @param {number} value - The value to clamp.
  1594. * @param {number} min - The min value.
  1595. * @param {number} max - The max value.
  1596. * @return {number} The clamped value.
  1597. */
  1598. function clamp( value, min, max ) {
  1599. return Math.max( min, Math.min( max, value ) );
  1600. }
  1601. /**
  1602. * Computes the Euclidean modulo of the given parameters that
  1603. * is `( ( n % m ) + m ) % m`.
  1604. *
  1605. * @param {number} n - The first parameter.
  1606. * @param {number} m - The second parameter.
  1607. * @return {number} The Euclidean modulo.
  1608. */
  1609. function euclideanModulo( n, m ) {
  1610. // https://en.wikipedia.org/wiki/Modulo_operation
  1611. return ( ( n % m ) + m ) % m;
  1612. }
  1613. /**
  1614. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1615. * for the given value.
  1616. *
  1617. * @param {number} x - The value to be mapped.
  1618. * @param {number} a1 - Minimum value for range A.
  1619. * @param {number} a2 - Maximum value for range A.
  1620. * @param {number} b1 - Minimum value for range B.
  1621. * @param {number} b2 - Maximum value for range B.
  1622. * @return {number} The mapped value.
  1623. */
  1624. function mapLinear( x, a1, a2, b1, b2 ) {
  1625. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1626. }
  1627. /**
  1628. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1629. * between the start and end point.
  1630. *
  1631. * @param {number} x - The start point
  1632. * @param {number} y - The end point.
  1633. * @param {number} value - A value between start and end.
  1634. * @return {number} The interpolation factor.
  1635. */
  1636. function inverseLerp( x, y, value ) {
  1637. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1638. if ( x !== y ) {
  1639. return ( value - x ) / ( y - x );
  1640. } else {
  1641. return 0;
  1642. }
  1643. }
  1644. /**
  1645. * Returns a value linearly interpolated from two known points based on the given interval -
  1646. * `t = 0` will return `x` and `t = 1` will return `y`.
  1647. *
  1648. * @param {number} x - The start point
  1649. * @param {number} y - The end point.
  1650. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1651. * @return {number} The interpolated value.
  1652. */
  1653. function lerp( x, y, t ) {
  1654. return ( 1 - t ) * x + t * y;
  1655. }
  1656. /**
  1657. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1658. * time to maintain frame rate independent movement. For details, see
  1659. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1660. *
  1661. * @param {number} x - The current point.
  1662. * @param {number} y - The target point.
  1663. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1664. * and a lower value will make the movement more gradual.
  1665. * @param {number} dt - Delta time in seconds.
  1666. * @return {number} The interpolated value.
  1667. */
  1668. function damp( x, y, lambda, dt ) {
  1669. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1670. }
  1671. /**
  1672. * Returns a value that alternates between `0` and the given `length` parameter.
  1673. *
  1674. * @param {number} x - The value to pingpong.
  1675. * @param {number} [length=1] - The positive value the function will pingpong to.
  1676. * @return {number} The alternated value.
  1677. */
  1678. function pingpong( x, length = 1 ) {
  1679. // https://www.desmos.com/calculator/vcsjnyz7x4
  1680. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1681. }
  1682. /**
  1683. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1684. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1685. * the `min` and `max`.
  1686. *
  1687. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  1688. *
  1689. * @param {number} x - The value to evaluate based on its position between min and max.
  1690. * @param {number} min - The min value. Any x value below min will be `0`.
  1691. * @param {number} max - The max value. Any x value above max will be `1`.
  1692. * @return {number} The alternated value.
  1693. */
  1694. function smoothstep( x, min, max ) {
  1695. if ( x <= min ) return 0;
  1696. if ( x >= max ) return 1;
  1697. x = ( x - min ) / ( max - min );
  1698. return x * x * ( 3 - 2 * x );
  1699. }
  1700. /**
  1701. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  1702. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1703. *
  1704. * @param {number} x - The value to evaluate based on its position between min and max.
  1705. * @param {number} min - The min value. Any x value below min will be `0`.
  1706. * @param {number} max - The max value. Any x value above max will be `1`.
  1707. * @return {number} The alternated value.
  1708. */
  1709. function smootherstep( x, min, max ) {
  1710. if ( x <= min ) return 0;
  1711. if ( x >= max ) return 1;
  1712. x = ( x - min ) / ( max - min );
  1713. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1714. }
  1715. /**
  1716. * Returns a random integer from `<low, high>` interval.
  1717. *
  1718. * @param {number} low - The lower value boundary.
  1719. * @param {number} high - The upper value boundary
  1720. * @return {number} A random integer.
  1721. */
  1722. function randInt( low, high ) {
  1723. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1724. }
  1725. /**
  1726. * Returns a random float from `<low, high>` interval.
  1727. *
  1728. * @param {number} low - The lower value boundary.
  1729. * @param {number} high - The upper value boundary
  1730. * @return {number} A random float.
  1731. */
  1732. function randFloat( low, high ) {
  1733. return low + Math.random() * ( high - low );
  1734. }
  1735. /**
  1736. * Returns a random integer from `<-range/2, range/2>` interval.
  1737. *
  1738. * @param {number} range - Defines the value range.
  1739. * @return {number} A random float.
  1740. */
  1741. function randFloatSpread( range ) {
  1742. return range * ( 0.5 - Math.random() );
  1743. }
  1744. /**
  1745. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1746. *
  1747. * @param {number} [s] - The integer seed.
  1748. * @return {number} A random float.
  1749. */
  1750. function seededRandom( s ) {
  1751. if ( s !== undefined ) _seed = s;
  1752. // Mulberry32 generator
  1753. let t = _seed += 0x6D2B79F5;
  1754. t = Math.imul( t ^ t >>> 15, t | 1 );
  1755. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1756. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1757. }
  1758. /**
  1759. * Converts degrees to radians.
  1760. *
  1761. * @param {number} degrees - A value in degrees.
  1762. * @return {number} The converted value in radians.
  1763. */
  1764. function degToRad( degrees ) {
  1765. return degrees * DEG2RAD;
  1766. }
  1767. /**
  1768. * Converts radians to degrees.
  1769. *
  1770. * @param {number} radians - A value in radians.
  1771. * @return {number} The converted value in degrees.
  1772. */
  1773. function radToDeg( radians ) {
  1774. return radians * RAD2DEG;
  1775. }
  1776. /**
  1777. * Returns `true` if the given number is a power of two.
  1778. *
  1779. * @param {number} value - The value to check.
  1780. * @return {boolean} Whether the given number is a power of two or not.
  1781. */
  1782. function isPowerOfTwo( value ) {
  1783. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1784. }
  1785. /**
  1786. * Returns the smallest power of two that is greater than or equal to the given number.
  1787. *
  1788. * @param {number} value - The value to find a POT for.
  1789. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1790. */
  1791. function ceilPowerOfTwo( value ) {
  1792. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1793. }
  1794. /**
  1795. * Returns the largest power of two that is less than or equal to the given number.
  1796. *
  1797. * @param {number} value - The value to find a POT for.
  1798. * @return {number} The largest power of two that is less than or equal to the given number.
  1799. */
  1800. function floorPowerOfTwo( value ) {
  1801. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1802. }
  1803. /**
  1804. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  1805. * defined by the given angles and order.
  1806. *
  1807. * Rotations are applied to the axes in the order specified by order:
  1808. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1809. *
  1810. * @param {Quaternion} q - The quaternion to set.
  1811. * @param {number} a - The rotation applied to the first axis, in radians.
  1812. * @param {number} b - The rotation applied to the second axis, in radians.
  1813. * @param {number} c - The rotation applied to the third axis, in radians.
  1814. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1815. */
  1816. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1817. const cos = Math.cos;
  1818. const sin = Math.sin;
  1819. const c2 = cos( b / 2 );
  1820. const s2 = sin( b / 2 );
  1821. const c13 = cos( ( a + c ) / 2 );
  1822. const s13 = sin( ( a + c ) / 2 );
  1823. const c1_3 = cos( ( a - c ) / 2 );
  1824. const s1_3 = sin( ( a - c ) / 2 );
  1825. const c3_1 = cos( ( c - a ) / 2 );
  1826. const s3_1 = sin( ( c - a ) / 2 );
  1827. switch ( order ) {
  1828. case 'XYX':
  1829. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1830. break;
  1831. case 'YZY':
  1832. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1833. break;
  1834. case 'ZXZ':
  1835. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1836. break;
  1837. case 'XZX':
  1838. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1839. break;
  1840. case 'YXY':
  1841. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1842. break;
  1843. case 'ZYZ':
  1844. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1845. break;
  1846. default:
  1847. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1848. }
  1849. }
  1850. /**
  1851. * Denormalizes the given value according to the given typed array.
  1852. *
  1853. * @param {number} value - The value to denormalize.
  1854. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1855. * @return {number} The denormalize (float) value in the range `[0,1]`.
  1856. */
  1857. function denormalize( value, array ) {
  1858. switch ( array.constructor ) {
  1859. case Float32Array:
  1860. return value;
  1861. case Uint32Array:
  1862. return value / 4294967295.0;
  1863. case Uint16Array:
  1864. return value / 65535.0;
  1865. case Uint8Array:
  1866. return value / 255.0;
  1867. case Int32Array:
  1868. return Math.max( value / 2147483647.0, -1 );
  1869. case Int16Array:
  1870. return Math.max( value / 32767.0, -1 );
  1871. case Int8Array:
  1872. return Math.max( value / 127.0, -1 );
  1873. default:
  1874. throw new Error( 'Invalid component type.' );
  1875. }
  1876. }
  1877. /**
  1878. * Normalizes the given value according to the given typed array.
  1879. *
  1880. * @param {number} value - The float value in the range `[0,1]` to normalize.
  1881. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1882. * @return {number} The normalize value.
  1883. */
  1884. function normalize( value, array ) {
  1885. switch ( array.constructor ) {
  1886. case Float32Array:
  1887. return value;
  1888. case Uint32Array:
  1889. return Math.round( value * 4294967295.0 );
  1890. case Uint16Array:
  1891. return Math.round( value * 65535.0 );
  1892. case Uint8Array:
  1893. return Math.round( value * 255.0 );
  1894. case Int32Array:
  1895. return Math.round( value * 2147483647.0 );
  1896. case Int16Array:
  1897. return Math.round( value * 32767.0 );
  1898. case Int8Array:
  1899. return Math.round( value * 127.0 );
  1900. default:
  1901. throw new Error( 'Invalid component type.' );
  1902. }
  1903. }
  1904. /**
  1905. * @class
  1906. * @classdesc A collection of math utility functions.
  1907. * @hideconstructor
  1908. */
  1909. const MathUtils = {
  1910. DEG2RAD: DEG2RAD,
  1911. RAD2DEG: RAD2DEG,
  1912. /**
  1913. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1914. * (universally unique identifier).
  1915. *
  1916. * @static
  1917. * @method
  1918. * @return {string} The UUID.
  1919. */
  1920. generateUUID: generateUUID,
  1921. /**
  1922. * Clamps the given value between min and max.
  1923. *
  1924. * @static
  1925. * @method
  1926. * @param {number} value - The value to clamp.
  1927. * @param {number} min - The min value.
  1928. * @param {number} max - The max value.
  1929. * @return {number} The clamped value.
  1930. */
  1931. clamp: clamp,
  1932. /**
  1933. * Computes the Euclidean modulo of the given parameters that
  1934. * is `( ( n % m ) + m ) % m`.
  1935. *
  1936. * @static
  1937. * @method
  1938. * @param {number} n - The first parameter.
  1939. * @param {number} m - The second parameter.
  1940. * @return {number} The Euclidean modulo.
  1941. */
  1942. euclideanModulo: euclideanModulo,
  1943. /**
  1944. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1945. * for the given value.
  1946. *
  1947. * @static
  1948. * @method
  1949. * @param {number} x - The value to be mapped.
  1950. * @param {number} a1 - Minimum value for range A.
  1951. * @param {number} a2 - Maximum value for range A.
  1952. * @param {number} b1 - Minimum value for range B.
  1953. * @param {number} b2 - Maximum value for range B.
  1954. * @return {number} The mapped value.
  1955. */
  1956. mapLinear: mapLinear,
  1957. /**
  1958. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1959. * between the start and end point.
  1960. *
  1961. * @static
  1962. * @method
  1963. * @param {number} x - The start point
  1964. * @param {number} y - The end point.
  1965. * @param {number} value - A value between start and end.
  1966. * @return {number} The interpolation factor.
  1967. */
  1968. inverseLerp: inverseLerp,
  1969. /**
  1970. * Returns a value linearly interpolated from two known points based on the given interval -
  1971. * `t = 0` will return `x` and `t = 1` will return `y`.
  1972. *
  1973. * @static
  1974. * @method
  1975. * @param {number} x - The start point
  1976. * @param {number} y - The end point.
  1977. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1978. * @return {number} The interpolated value.
  1979. */
  1980. lerp: lerp,
  1981. /**
  1982. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1983. * time to maintain frame rate independent movement. For details, see
  1984. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1985. *
  1986. * @static
  1987. * @method
  1988. * @param {number} x - The current point.
  1989. * @param {number} y - The target point.
  1990. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1991. * and a lower value will make the movement more gradual.
  1992. * @param {number} dt - Delta time in seconds.
  1993. * @return {number} The interpolated value.
  1994. */
  1995. damp: damp,
  1996. /**
  1997. * Returns a value that alternates between `0` and the given `length` parameter.
  1998. *
  1999. * @static
  2000. * @method
  2001. * @param {number} x - The value to pingpong.
  2002. * @param {number} [length=1] - The positive value the function will pingpong to.
  2003. * @return {number} The alternated value.
  2004. */
  2005. pingpong: pingpong,
  2006. /**
  2007. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2008. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2009. * the `min` and `max`.
  2010. *
  2011. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  2012. *
  2013. * @static
  2014. * @method
  2015. * @param {number} x - The value to evaluate based on its position between min and max.
  2016. * @param {number} min - The min value. Any x value below min will be `0`.
  2017. * @param {number} max - The max value. Any x value above max will be `1`.
  2018. * @return {number} The alternated value.
  2019. */
  2020. smoothstep: smoothstep,
  2021. /**
  2022. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  2023. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2024. *
  2025. * @static
  2026. * @method
  2027. * @param {number} x - The value to evaluate based on its position between min and max.
  2028. * @param {number} min - The min value. Any x value below min will be `0`.
  2029. * @param {number} max - The max value. Any x value above max will be `1`.
  2030. * @return {number} The alternated value.
  2031. */
  2032. smootherstep: smootherstep,
  2033. /**
  2034. * Returns a random integer from `<low, high>` interval.
  2035. *
  2036. * @static
  2037. * @method
  2038. * @param {number} low - The lower value boundary.
  2039. * @param {number} high - The upper value boundary
  2040. * @return {number} A random integer.
  2041. */
  2042. randInt: randInt,
  2043. /**
  2044. * Returns a random float from `<low, high>` interval.
  2045. *
  2046. * @static
  2047. * @method
  2048. * @param {number} low - The lower value boundary.
  2049. * @param {number} high - The upper value boundary
  2050. * @return {number} A random float.
  2051. */
  2052. randFloat: randFloat,
  2053. /**
  2054. * Returns a random integer from `<-range/2, range/2>` interval.
  2055. *
  2056. * @static
  2057. * @method
  2058. * @param {number} range - Defines the value range.
  2059. * @return {number} A random float.
  2060. */
  2061. randFloatSpread: randFloatSpread,
  2062. /**
  2063. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2064. *
  2065. * @static
  2066. * @method
  2067. * @param {number} [s] - The integer seed.
  2068. * @return {number} A random float.
  2069. */
  2070. seededRandom: seededRandom,
  2071. /**
  2072. * Converts degrees to radians.
  2073. *
  2074. * @static
  2075. * @method
  2076. * @param {number} degrees - A value in degrees.
  2077. * @return {number} The converted value in radians.
  2078. */
  2079. degToRad: degToRad,
  2080. /**
  2081. * Converts radians to degrees.
  2082. *
  2083. * @static
  2084. * @method
  2085. * @param {number} radians - A value in radians.
  2086. * @return {number} The converted value in degrees.
  2087. */
  2088. radToDeg: radToDeg,
  2089. /**
  2090. * Returns `true` if the given number is a power of two.
  2091. *
  2092. * @static
  2093. * @method
  2094. * @param {number} value - The value to check.
  2095. * @return {boolean} Whether the given number is a power of two or not.
  2096. */
  2097. isPowerOfTwo: isPowerOfTwo,
  2098. /**
  2099. * Returns the smallest power of two that is greater than or equal to the given number.
  2100. *
  2101. * @static
  2102. * @method
  2103. * @param {number} value - The value to find a POT for.
  2104. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2105. */
  2106. ceilPowerOfTwo: ceilPowerOfTwo,
  2107. /**
  2108. * Returns the largest power of two that is less than or equal to the given number.
  2109. *
  2110. * @static
  2111. * @method
  2112. * @param {number} value - The value to find a POT for.
  2113. * @return {number} The largest power of two that is less than or equal to the given number.
  2114. */
  2115. floorPowerOfTwo: floorPowerOfTwo,
  2116. /**
  2117. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  2118. * defined by the given angles and order.
  2119. *
  2120. * Rotations are applied to the axes in the order specified by order:
  2121. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2122. *
  2123. * @static
  2124. * @method
  2125. * @param {Quaternion} q - The quaternion to set.
  2126. * @param {number} a - The rotation applied to the first axis, in radians.
  2127. * @param {number} b - The rotation applied to the second axis, in radians.
  2128. * @param {number} c - The rotation applied to the third axis, in radians.
  2129. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2130. */
  2131. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2132. /**
  2133. * Normalizes the given value according to the given typed array.
  2134. *
  2135. * @static
  2136. * @method
  2137. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2138. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2139. * @return {number} The normalize value.
  2140. */
  2141. normalize: normalize,
  2142. /**
  2143. * Denormalizes the given value according to the given typed array.
  2144. *
  2145. * @static
  2146. * @method
  2147. * @param {number} value - The value to denormalize.
  2148. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2149. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2150. */
  2151. denormalize: denormalize
  2152. };
  2153. /**
  2154. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2155. * (labeled x and y), which can be used to represent a number of things, such as:
  2156. *
  2157. * - A point in 2D space (i.e. a position on a plane).
  2158. * - A direction and length across a plane. In three.js the length will
  2159. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2160. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2161. * - Any arbitrary ordered pair of numbers.
  2162. *
  2163. * There are other things a 2D vector can be used to represent, such as
  2164. * momentum vectors, complex numbers and so on, however these are the most
  2165. * common uses in three.js.
  2166. *
  2167. * Iterating through a vector instance will yield its components `(x, y)` in
  2168. * the corresponding order.
  2169. * ```js
  2170. * const a = new THREE.Vector2( 0, 1 );
  2171. *
  2172. * //no arguments; will be initialised to (0, 0)
  2173. * const b = new THREE.Vector2( );
  2174. *
  2175. * const d = a.distanceTo( b );
  2176. * ```
  2177. */
  2178. class Vector2 {
  2179. /**
  2180. * Constructs a new 2D vector.
  2181. *
  2182. * @param {number} [x=0] - The x value of this vector.
  2183. * @param {number} [y=0] - The y value of this vector.
  2184. */
  2185. constructor( x = 0, y = 0 ) {
  2186. /**
  2187. * This flag can be used for type testing.
  2188. *
  2189. * @type {boolean}
  2190. * @readonly
  2191. * @default true
  2192. */
  2193. Vector2.prototype.isVector2 = true;
  2194. /**
  2195. * The x value of this vector.
  2196. *
  2197. * @type {number}
  2198. */
  2199. this.x = x;
  2200. /**
  2201. * The y value of this vector.
  2202. *
  2203. * @type {number}
  2204. */
  2205. this.y = y;
  2206. }
  2207. /**
  2208. * Alias for {@link Vector2#x}.
  2209. *
  2210. * @type {number}
  2211. */
  2212. get width() {
  2213. return this.x;
  2214. }
  2215. set width( value ) {
  2216. this.x = value;
  2217. }
  2218. /**
  2219. * Alias for {@link Vector2#y}.
  2220. *
  2221. * @type {number}
  2222. */
  2223. get height() {
  2224. return this.y;
  2225. }
  2226. set height( value ) {
  2227. this.y = value;
  2228. }
  2229. /**
  2230. * Sets the vector components.
  2231. *
  2232. * @param {number} x - The value of the x component.
  2233. * @param {number} y - The value of the y component.
  2234. * @return {Vector2} A reference to this vector.
  2235. */
  2236. set( x, y ) {
  2237. this.x = x;
  2238. this.y = y;
  2239. return this;
  2240. }
  2241. /**
  2242. * Sets the vector components to the same value.
  2243. *
  2244. * @param {number} scalar - The value to set for all vector components.
  2245. * @return {Vector2} A reference to this vector.
  2246. */
  2247. setScalar( scalar ) {
  2248. this.x = scalar;
  2249. this.y = scalar;
  2250. return this;
  2251. }
  2252. /**
  2253. * Sets the vector's x component to the given value
  2254. *
  2255. * @param {number} x - The value to set.
  2256. * @return {Vector2} A reference to this vector.
  2257. */
  2258. setX( x ) {
  2259. this.x = x;
  2260. return this;
  2261. }
  2262. /**
  2263. * Sets the vector's y component to the given value
  2264. *
  2265. * @param {number} y - The value to set.
  2266. * @return {Vector2} A reference to this vector.
  2267. */
  2268. setY( y ) {
  2269. this.y = y;
  2270. return this;
  2271. }
  2272. /**
  2273. * Allows to set a vector component with an index.
  2274. *
  2275. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2276. * @param {number} value - The value to set.
  2277. * @return {Vector2} A reference to this vector.
  2278. */
  2279. setComponent( index, value ) {
  2280. switch ( index ) {
  2281. case 0: this.x = value; break;
  2282. case 1: this.y = value; break;
  2283. default: throw new Error( 'index is out of range: ' + index );
  2284. }
  2285. return this;
  2286. }
  2287. /**
  2288. * Returns the value of the vector component which matches the given index.
  2289. *
  2290. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2291. * @return {number} A vector component value.
  2292. */
  2293. getComponent( index ) {
  2294. switch ( index ) {
  2295. case 0: return this.x;
  2296. case 1: return this.y;
  2297. default: throw new Error( 'index is out of range: ' + index );
  2298. }
  2299. }
  2300. /**
  2301. * Returns a new vector with copied values from this instance.
  2302. *
  2303. * @return {Vector2} A clone of this instance.
  2304. */
  2305. clone() {
  2306. return new this.constructor( this.x, this.y );
  2307. }
  2308. /**
  2309. * Copies the values of the given vector to this instance.
  2310. *
  2311. * @param {Vector2} v - The vector to copy.
  2312. * @return {Vector2} A reference to this vector.
  2313. */
  2314. copy( v ) {
  2315. this.x = v.x;
  2316. this.y = v.y;
  2317. return this;
  2318. }
  2319. /**
  2320. * Adds the given vector to this instance.
  2321. *
  2322. * @param {Vector2} v - The vector to add.
  2323. * @return {Vector2} A reference to this vector.
  2324. */
  2325. add( v ) {
  2326. this.x += v.x;
  2327. this.y += v.y;
  2328. return this;
  2329. }
  2330. /**
  2331. * Adds the given scalar value to all components of this instance.
  2332. *
  2333. * @param {number} s - The scalar to add.
  2334. * @return {Vector2} A reference to this vector.
  2335. */
  2336. addScalar( s ) {
  2337. this.x += s;
  2338. this.y += s;
  2339. return this;
  2340. }
  2341. /**
  2342. * Adds the given vectors and stores the result in this instance.
  2343. *
  2344. * @param {Vector2} a - The first vector.
  2345. * @param {Vector2} b - The second vector.
  2346. * @return {Vector2} A reference to this vector.
  2347. */
  2348. addVectors( a, b ) {
  2349. this.x = a.x + b.x;
  2350. this.y = a.y + b.y;
  2351. return this;
  2352. }
  2353. /**
  2354. * Adds the given vector scaled by the given factor to this instance.
  2355. *
  2356. * @param {Vector2} v - The vector.
  2357. * @param {number} s - The factor that scales `v`.
  2358. * @return {Vector2} A reference to this vector.
  2359. */
  2360. addScaledVector( v, s ) {
  2361. this.x += v.x * s;
  2362. this.y += v.y * s;
  2363. return this;
  2364. }
  2365. /**
  2366. * Subtracts the given vector from this instance.
  2367. *
  2368. * @param {Vector2} v - The vector to subtract.
  2369. * @return {Vector2} A reference to this vector.
  2370. */
  2371. sub( v ) {
  2372. this.x -= v.x;
  2373. this.y -= v.y;
  2374. return this;
  2375. }
  2376. /**
  2377. * Subtracts the given scalar value from all components of this instance.
  2378. *
  2379. * @param {number} s - The scalar to subtract.
  2380. * @return {Vector2} A reference to this vector.
  2381. */
  2382. subScalar( s ) {
  2383. this.x -= s;
  2384. this.y -= s;
  2385. return this;
  2386. }
  2387. /**
  2388. * Subtracts the given vectors and stores the result in this instance.
  2389. *
  2390. * @param {Vector2} a - The first vector.
  2391. * @param {Vector2} b - The second vector.
  2392. * @return {Vector2} A reference to this vector.
  2393. */
  2394. subVectors( a, b ) {
  2395. this.x = a.x - b.x;
  2396. this.y = a.y - b.y;
  2397. return this;
  2398. }
  2399. /**
  2400. * Multiplies the given vector with this instance.
  2401. *
  2402. * @param {Vector2} v - The vector to multiply.
  2403. * @return {Vector2} A reference to this vector.
  2404. */
  2405. multiply( v ) {
  2406. this.x *= v.x;
  2407. this.y *= v.y;
  2408. return this;
  2409. }
  2410. /**
  2411. * Multiplies the given scalar value with all components of this instance.
  2412. *
  2413. * @param {number} scalar - The scalar to multiply.
  2414. * @return {Vector2} A reference to this vector.
  2415. */
  2416. multiplyScalar( scalar ) {
  2417. this.x *= scalar;
  2418. this.y *= scalar;
  2419. return this;
  2420. }
  2421. /**
  2422. * Divides this instance by the given vector.
  2423. *
  2424. * @param {Vector2} v - The vector to divide.
  2425. * @return {Vector2} A reference to this vector.
  2426. */
  2427. divide( v ) {
  2428. this.x /= v.x;
  2429. this.y /= v.y;
  2430. return this;
  2431. }
  2432. /**
  2433. * Divides this vector by the given scalar.
  2434. *
  2435. * @param {number} scalar - The scalar to divide.
  2436. * @return {Vector2} A reference to this vector.
  2437. */
  2438. divideScalar( scalar ) {
  2439. return this.multiplyScalar( 1 / scalar );
  2440. }
  2441. /**
  2442. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2443. * the given 3x3 matrix.
  2444. *
  2445. * @param {Matrix3} m - The matrix to apply.
  2446. * @return {Vector2} A reference to this vector.
  2447. */
  2448. applyMatrix3( m ) {
  2449. const x = this.x, y = this.y;
  2450. const e = m.elements;
  2451. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2452. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2453. return this;
  2454. }
  2455. /**
  2456. * If this vector's x or y value is greater than the given vector's x or y
  2457. * value, replace that value with the corresponding min value.
  2458. *
  2459. * @param {Vector2} v - The vector.
  2460. * @return {Vector2} A reference to this vector.
  2461. */
  2462. min( v ) {
  2463. this.x = Math.min( this.x, v.x );
  2464. this.y = Math.min( this.y, v.y );
  2465. return this;
  2466. }
  2467. /**
  2468. * If this vector's x or y value is less than the given vector's x or y
  2469. * value, replace that value with the corresponding max value.
  2470. *
  2471. * @param {Vector2} v - The vector.
  2472. * @return {Vector2} A reference to this vector.
  2473. */
  2474. max( v ) {
  2475. this.x = Math.max( this.x, v.x );
  2476. this.y = Math.max( this.y, v.y );
  2477. return this;
  2478. }
  2479. /**
  2480. * If this vector's x or y value is greater than the max vector's x or y
  2481. * value, it is replaced by the corresponding value.
  2482. * If this vector's x or y value is less than the min vector's x or y value,
  2483. * it is replaced by the corresponding value.
  2484. *
  2485. * @param {Vector2} min - The minimum x and y values.
  2486. * @param {Vector2} max - The maximum x and y values in the desired range.
  2487. * @return {Vector2} A reference to this vector.
  2488. */
  2489. clamp( min, max ) {
  2490. // assumes min < max, componentwise
  2491. this.x = clamp( this.x, min.x, max.x );
  2492. this.y = clamp( this.y, min.y, max.y );
  2493. return this;
  2494. }
  2495. /**
  2496. * If this vector's x or y values are greater than the max value, they are
  2497. * replaced by the max value.
  2498. * If this vector's x or y values are less than the min value, they are
  2499. * replaced by the min value.
  2500. *
  2501. * @param {number} minVal - The minimum value the components will be clamped to.
  2502. * @param {number} maxVal - The maximum value the components will be clamped to.
  2503. * @return {Vector2} A reference to this vector.
  2504. */
  2505. clampScalar( minVal, maxVal ) {
  2506. this.x = clamp( this.x, minVal, maxVal );
  2507. this.y = clamp( this.y, minVal, maxVal );
  2508. return this;
  2509. }
  2510. /**
  2511. * If this vector's length is greater than the max value, it is replaced by
  2512. * the max value.
  2513. * If this vector's length is less than the min value, it is replaced by the
  2514. * min value.
  2515. *
  2516. * @param {number} min - The minimum value the vector length will be clamped to.
  2517. * @param {number} max - The maximum value the vector length will be clamped to.
  2518. * @return {Vector2} A reference to this vector.
  2519. */
  2520. clampLength( min, max ) {
  2521. const length = this.length();
  2522. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2523. }
  2524. /**
  2525. * The components of this vector are rounded down to the nearest integer value.
  2526. *
  2527. * @return {Vector2} A reference to this vector.
  2528. */
  2529. floor() {
  2530. this.x = Math.floor( this.x );
  2531. this.y = Math.floor( this.y );
  2532. return this;
  2533. }
  2534. /**
  2535. * The components of this vector are rounded up to the nearest integer value.
  2536. *
  2537. * @return {Vector2} A reference to this vector.
  2538. */
  2539. ceil() {
  2540. this.x = Math.ceil( this.x );
  2541. this.y = Math.ceil( this.y );
  2542. return this;
  2543. }
  2544. /**
  2545. * The components of this vector are rounded to the nearest integer value
  2546. *
  2547. * @return {Vector2} A reference to this vector.
  2548. */
  2549. round() {
  2550. this.x = Math.round( this.x );
  2551. this.y = Math.round( this.y );
  2552. return this;
  2553. }
  2554. /**
  2555. * The components of this vector are rounded towards zero (up if negative,
  2556. * down if positive) to an integer value.
  2557. *
  2558. * @return {Vector2} A reference to this vector.
  2559. */
  2560. roundToZero() {
  2561. this.x = Math.trunc( this.x );
  2562. this.y = Math.trunc( this.y );
  2563. return this;
  2564. }
  2565. /**
  2566. * Inverts this vector - i.e. sets x = -x and y = -y.
  2567. *
  2568. * @return {Vector2} A reference to this vector.
  2569. */
  2570. negate() {
  2571. this.x = - this.x;
  2572. this.y = - this.y;
  2573. return this;
  2574. }
  2575. /**
  2576. * Calculates the dot product of the given vector with this instance.
  2577. *
  2578. * @param {Vector2} v - The vector to compute the dot product with.
  2579. * @return {number} The result of the dot product.
  2580. */
  2581. dot( v ) {
  2582. return this.x * v.x + this.y * v.y;
  2583. }
  2584. /**
  2585. * Calculates the cross product of the given vector with this instance.
  2586. *
  2587. * @param {Vector2} v - The vector to compute the cross product with.
  2588. * @return {number} The result of the cross product.
  2589. */
  2590. cross( v ) {
  2591. return this.x * v.y - this.y * v.x;
  2592. }
  2593. /**
  2594. * Computes the square of the Euclidean length (straight-line length) from
  2595. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2596. * compare the length squared instead as it is slightly more efficient to calculate.
  2597. *
  2598. * @return {number} The square length of this vector.
  2599. */
  2600. lengthSq() {
  2601. return this.x * this.x + this.y * this.y;
  2602. }
  2603. /**
  2604. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2605. *
  2606. * @return {number} The length of this vector.
  2607. */
  2608. length() {
  2609. return Math.sqrt( this.x * this.x + this.y * this.y );
  2610. }
  2611. /**
  2612. * Computes the Manhattan length of this vector.
  2613. *
  2614. * @return {number} The length of this vector.
  2615. */
  2616. manhattanLength() {
  2617. return Math.abs( this.x ) + Math.abs( this.y );
  2618. }
  2619. /**
  2620. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2621. * with the same direction as this one, but with a vector length of `1`.
  2622. *
  2623. * @return {Vector2} A reference to this vector.
  2624. */
  2625. normalize() {
  2626. return this.divideScalar( this.length() || 1 );
  2627. }
  2628. /**
  2629. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2630. *
  2631. * @return {number} The angle in radians.
  2632. */
  2633. angle() {
  2634. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2635. return angle;
  2636. }
  2637. /**
  2638. * Returns the angle between the given vector and this instance in radians.
  2639. *
  2640. * @param {Vector2} v - The vector to compute the angle with.
  2641. * @return {number} The angle in radians.
  2642. */
  2643. angleTo( v ) {
  2644. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2645. if ( denominator === 0 ) return Math.PI / 2;
  2646. const theta = this.dot( v ) / denominator;
  2647. // clamp, to handle numerical problems
  2648. return Math.acos( clamp( theta, -1, 1 ) );
  2649. }
  2650. /**
  2651. * Computes the distance from the given vector to this instance.
  2652. *
  2653. * @param {Vector2} v - The vector to compute the distance to.
  2654. * @return {number} The distance.
  2655. */
  2656. distanceTo( v ) {
  2657. return Math.sqrt( this.distanceToSquared( v ) );
  2658. }
  2659. /**
  2660. * Computes the squared distance from the given vector to this instance.
  2661. * If you are just comparing the distance with another distance, you should compare
  2662. * the distance squared instead as it is slightly more efficient to calculate.
  2663. *
  2664. * @param {Vector2} v - The vector to compute the squared distance to.
  2665. * @return {number} The squared distance.
  2666. */
  2667. distanceToSquared( v ) {
  2668. const dx = this.x - v.x, dy = this.y - v.y;
  2669. return dx * dx + dy * dy;
  2670. }
  2671. /**
  2672. * Computes the Manhattan distance from the given vector to this instance.
  2673. *
  2674. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2675. * @return {number} The Manhattan distance.
  2676. */
  2677. manhattanDistanceTo( v ) {
  2678. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2679. }
  2680. /**
  2681. * Sets this vector to a vector with the same direction as this one, but
  2682. * with the specified length.
  2683. *
  2684. * @param {number} length - The new length of this vector.
  2685. * @return {Vector2} A reference to this vector.
  2686. */
  2687. setLength( length ) {
  2688. return this.normalize().multiplyScalar( length );
  2689. }
  2690. /**
  2691. * Linearly interpolates between the given vector and this instance, where
  2692. * alpha is the percent distance along the line - alpha = 0 will be this
  2693. * vector, and alpha = 1 will be the given one.
  2694. *
  2695. * @param {Vector2} v - The vector to interpolate towards.
  2696. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2697. * @return {Vector2} A reference to this vector.
  2698. */
  2699. lerp( v, alpha ) {
  2700. this.x += ( v.x - this.x ) * alpha;
  2701. this.y += ( v.y - this.y ) * alpha;
  2702. return this;
  2703. }
  2704. /**
  2705. * Linearly interpolates between the given vectors, where alpha is the percent
  2706. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2707. * be the second one. The result is stored in this instance.
  2708. *
  2709. * @param {Vector2} v1 - The first vector.
  2710. * @param {Vector2} v2 - The second vector.
  2711. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2712. * @return {Vector2} A reference to this vector.
  2713. */
  2714. lerpVectors( v1, v2, alpha ) {
  2715. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2716. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2717. return this;
  2718. }
  2719. /**
  2720. * Returns `true` if this vector is equal with the given one.
  2721. *
  2722. * @param {Vector2} v - The vector to test for equality.
  2723. * @return {boolean} Whether this vector is equal with the given one.
  2724. */
  2725. equals( v ) {
  2726. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2727. }
  2728. /**
  2729. * Sets this vector's x value to be `array[ offset ]` and y
  2730. * value to be `array[ offset + 1 ]`.
  2731. *
  2732. * @param {Array<number>} array - An array holding the vector component values.
  2733. * @param {number} [offset=0] - The offset into the array.
  2734. * @return {Vector2} A reference to this vector.
  2735. */
  2736. fromArray( array, offset = 0 ) {
  2737. this.x = array[ offset ];
  2738. this.y = array[ offset + 1 ];
  2739. return this;
  2740. }
  2741. /**
  2742. * Writes the components of this vector to the given array. If no array is provided,
  2743. * the method returns a new instance.
  2744. *
  2745. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2746. * @param {number} [offset=0] - Index of the first element in the array.
  2747. * @return {Array<number>} The vector components.
  2748. */
  2749. toArray( array = [], offset = 0 ) {
  2750. array[ offset ] = this.x;
  2751. array[ offset + 1 ] = this.y;
  2752. return array;
  2753. }
  2754. /**
  2755. * Sets the components of this vector from the given buffer attribute.
  2756. *
  2757. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2758. * @param {number} index - The index into the attribute.
  2759. * @return {Vector2} A reference to this vector.
  2760. */
  2761. fromBufferAttribute( attribute, index ) {
  2762. this.x = attribute.getX( index );
  2763. this.y = attribute.getY( index );
  2764. return this;
  2765. }
  2766. /**
  2767. * Rotates this vector around the given center by the given angle.
  2768. *
  2769. * @param {Vector2} center - The point around which to rotate.
  2770. * @param {number} angle - The angle to rotate, in radians.
  2771. * @return {Vector2} A reference to this vector.
  2772. */
  2773. rotateAround( center, angle ) {
  2774. const c = Math.cos( angle ), s = Math.sin( angle );
  2775. const x = this.x - center.x;
  2776. const y = this.y - center.y;
  2777. this.x = x * c - y * s + center.x;
  2778. this.y = x * s + y * c + center.y;
  2779. return this;
  2780. }
  2781. /**
  2782. * Sets each component of this vector to a pseudo-random value between `0` and
  2783. * `1`, excluding `1`.
  2784. *
  2785. * @return {Vector2} A reference to this vector.
  2786. */
  2787. random() {
  2788. this.x = Math.random();
  2789. this.y = Math.random();
  2790. return this;
  2791. }
  2792. *[ Symbol.iterator ]() {
  2793. yield this.x;
  2794. yield this.y;
  2795. }
  2796. }
  2797. /**
  2798. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2799. *
  2800. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2801. * the corresponding order.
  2802. *
  2803. * Note that three.js expects Quaternions to be normalized.
  2804. * ```js
  2805. * const quaternion = new THREE.Quaternion();
  2806. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2807. *
  2808. * const vector = new THREE.Vector3( 1, 0, 0 );
  2809. * vector.applyQuaternion( quaternion );
  2810. * ```
  2811. */
  2812. class Quaternion {
  2813. /**
  2814. * Constructs a new quaternion.
  2815. *
  2816. * @param {number} [x=0] - The x value of this quaternion.
  2817. * @param {number} [y=0] - The y value of this quaternion.
  2818. * @param {number} [z=0] - The z value of this quaternion.
  2819. * @param {number} [w=1] - The w value of this quaternion.
  2820. */
  2821. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2822. /**
  2823. * This flag can be used for type testing.
  2824. *
  2825. * @type {boolean}
  2826. * @readonly
  2827. * @default true
  2828. */
  2829. this.isQuaternion = true;
  2830. this._x = x;
  2831. this._y = y;
  2832. this._z = z;
  2833. this._w = w;
  2834. }
  2835. /**
  2836. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2837. * quaternion data are managed in flat arrays.
  2838. *
  2839. * @param {Array<number>} dst - The destination array.
  2840. * @param {number} dstOffset - An offset into the destination array.
  2841. * @param {Array<number>} src0 - The source array of the first quaternion.
  2842. * @param {number} srcOffset0 - An offset into the first source array.
  2843. * @param {Array<number>} src1 - The source array of the second quaternion.
  2844. * @param {number} srcOffset1 - An offset into the second source array.
  2845. * @param {number} t - The interpolation factor in the range `[0,1]`.
  2846. * @see {@link Quaternion#slerp}
  2847. */
  2848. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2849. // fuzz-free, array-based Quaternion SLERP operation
  2850. let x0 = src0[ srcOffset0 + 0 ],
  2851. y0 = src0[ srcOffset0 + 1 ],
  2852. z0 = src0[ srcOffset0 + 2 ],
  2853. w0 = src0[ srcOffset0 + 3 ];
  2854. const x1 = src1[ srcOffset1 + 0 ],
  2855. y1 = src1[ srcOffset1 + 1 ],
  2856. z1 = src1[ srcOffset1 + 2 ],
  2857. w1 = src1[ srcOffset1 + 3 ];
  2858. if ( t === 0 ) {
  2859. dst[ dstOffset + 0 ] = x0;
  2860. dst[ dstOffset + 1 ] = y0;
  2861. dst[ dstOffset + 2 ] = z0;
  2862. dst[ dstOffset + 3 ] = w0;
  2863. return;
  2864. }
  2865. if ( t === 1 ) {
  2866. dst[ dstOffset + 0 ] = x1;
  2867. dst[ dstOffset + 1 ] = y1;
  2868. dst[ dstOffset + 2 ] = z1;
  2869. dst[ dstOffset + 3 ] = w1;
  2870. return;
  2871. }
  2872. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2873. let s = 1 - t;
  2874. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2875. dir = ( cos >= 0 ? 1 : -1 ),
  2876. sqrSin = 1 - cos * cos;
  2877. // Skip the Slerp for tiny steps to avoid numeric problems:
  2878. if ( sqrSin > Number.EPSILON ) {
  2879. const sin = Math.sqrt( sqrSin ),
  2880. len = Math.atan2( sin, cos * dir );
  2881. s = Math.sin( s * len ) / sin;
  2882. t = Math.sin( t * len ) / sin;
  2883. }
  2884. const tDir = t * dir;
  2885. x0 = x0 * s + x1 * tDir;
  2886. y0 = y0 * s + y1 * tDir;
  2887. z0 = z0 * s + z1 * tDir;
  2888. w0 = w0 * s + w1 * tDir;
  2889. // Normalize in case we just did a lerp:
  2890. if ( s === 1 - t ) {
  2891. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2892. x0 *= f;
  2893. y0 *= f;
  2894. z0 *= f;
  2895. w0 *= f;
  2896. }
  2897. }
  2898. dst[ dstOffset ] = x0;
  2899. dst[ dstOffset + 1 ] = y0;
  2900. dst[ dstOffset + 2 ] = z0;
  2901. dst[ dstOffset + 3 ] = w0;
  2902. }
  2903. /**
  2904. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  2905. * in flat arrays.
  2906. *
  2907. * @param {Array<number>} dst - The destination array.
  2908. * @param {number} dstOffset - An offset into the destination array.
  2909. * @param {Array<number>} src0 - The source array of the first quaternion.
  2910. * @param {number} srcOffset0 - An offset into the first source array.
  2911. * @param {Array<number>} src1 - The source array of the second quaternion.
  2912. * @param {number} srcOffset1 - An offset into the second source array.
  2913. * @return {Array<number>} The destination array.
  2914. * @see {@link Quaternion#multiplyQuaternions}.
  2915. */
  2916. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2917. const x0 = src0[ srcOffset0 ];
  2918. const y0 = src0[ srcOffset0 + 1 ];
  2919. const z0 = src0[ srcOffset0 + 2 ];
  2920. const w0 = src0[ srcOffset0 + 3 ];
  2921. const x1 = src1[ srcOffset1 ];
  2922. const y1 = src1[ srcOffset1 + 1 ];
  2923. const z1 = src1[ srcOffset1 + 2 ];
  2924. const w1 = src1[ srcOffset1 + 3 ];
  2925. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2926. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2927. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2928. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2929. return dst;
  2930. }
  2931. /**
  2932. * The x value of this quaternion.
  2933. *
  2934. * @type {number}
  2935. * @default 0
  2936. */
  2937. get x() {
  2938. return this._x;
  2939. }
  2940. set x( value ) {
  2941. this._x = value;
  2942. this._onChangeCallback();
  2943. }
  2944. /**
  2945. * The y value of this quaternion.
  2946. *
  2947. * @type {number}
  2948. * @default 0
  2949. */
  2950. get y() {
  2951. return this._y;
  2952. }
  2953. set y( value ) {
  2954. this._y = value;
  2955. this._onChangeCallback();
  2956. }
  2957. /**
  2958. * The z value of this quaternion.
  2959. *
  2960. * @type {number}
  2961. * @default 0
  2962. */
  2963. get z() {
  2964. return this._z;
  2965. }
  2966. set z( value ) {
  2967. this._z = value;
  2968. this._onChangeCallback();
  2969. }
  2970. /**
  2971. * The w value of this quaternion.
  2972. *
  2973. * @type {number}
  2974. * @default 1
  2975. */
  2976. get w() {
  2977. return this._w;
  2978. }
  2979. set w( value ) {
  2980. this._w = value;
  2981. this._onChangeCallback();
  2982. }
  2983. /**
  2984. * Sets the quaternion components.
  2985. *
  2986. * @param {number} x - The x value of this quaternion.
  2987. * @param {number} y - The y value of this quaternion.
  2988. * @param {number} z - The z value of this quaternion.
  2989. * @param {number} w - The w value of this quaternion.
  2990. * @return {Quaternion} A reference to this quaternion.
  2991. */
  2992. set( x, y, z, w ) {
  2993. this._x = x;
  2994. this._y = y;
  2995. this._z = z;
  2996. this._w = w;
  2997. this._onChangeCallback();
  2998. return this;
  2999. }
  3000. /**
  3001. * Returns a new quaternion with copied values from this instance.
  3002. *
  3003. * @return {Quaternion} A clone of this instance.
  3004. */
  3005. clone() {
  3006. return new this.constructor( this._x, this._y, this._z, this._w );
  3007. }
  3008. /**
  3009. * Copies the values of the given quaternion to this instance.
  3010. *
  3011. * @param {Quaternion} quaternion - The quaternion to copy.
  3012. * @return {Quaternion} A reference to this quaternion.
  3013. */
  3014. copy( quaternion ) {
  3015. this._x = quaternion.x;
  3016. this._y = quaternion.y;
  3017. this._z = quaternion.z;
  3018. this._w = quaternion.w;
  3019. this._onChangeCallback();
  3020. return this;
  3021. }
  3022. /**
  3023. * Sets this quaternion from the rotation specified by the given
  3024. * Euler angles.
  3025. *
  3026. * @param {Euler} euler - The Euler angles.
  3027. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3028. * @return {Quaternion} A reference to this quaternion.
  3029. */
  3030. setFromEuler( euler, update = true ) {
  3031. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3032. // http://www.mathworks.com/matlabcentral/fileexchange/
  3033. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3034. // content/SpinCalc.m
  3035. const cos = Math.cos;
  3036. const sin = Math.sin;
  3037. const c1 = cos( x / 2 );
  3038. const c2 = cos( y / 2 );
  3039. const c3 = cos( z / 2 );
  3040. const s1 = sin( x / 2 );
  3041. const s2 = sin( y / 2 );
  3042. const s3 = sin( z / 2 );
  3043. switch ( order ) {
  3044. case 'XYZ':
  3045. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3046. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3047. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3048. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3049. break;
  3050. case 'YXZ':
  3051. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3052. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3053. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3054. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3055. break;
  3056. case 'ZXY':
  3057. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3058. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3059. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3060. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3061. break;
  3062. case 'ZYX':
  3063. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3064. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3065. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3066. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3067. break;
  3068. case 'YZX':
  3069. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3070. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3071. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3072. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3073. break;
  3074. case 'XZY':
  3075. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3076. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3077. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3078. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3079. break;
  3080. default:
  3081. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3082. }
  3083. if ( update === true ) this._onChangeCallback();
  3084. return this;
  3085. }
  3086. /**
  3087. * Sets this quaternion from the given axis and angle.
  3088. *
  3089. * @param {Vector3} axis - The normalized axis.
  3090. * @param {number} angle - The angle in radians.
  3091. * @return {Quaternion} A reference to this quaternion.
  3092. */
  3093. setFromAxisAngle( axis, angle ) {
  3094. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3095. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3096. this._x = axis.x * s;
  3097. this._y = axis.y * s;
  3098. this._z = axis.z * s;
  3099. this._w = Math.cos( halfAngle );
  3100. this._onChangeCallback();
  3101. return this;
  3102. }
  3103. /**
  3104. * Sets this quaternion from the given rotation matrix.
  3105. *
  3106. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3107. * @return {Quaternion} A reference to this quaternion.
  3108. */
  3109. setFromRotationMatrix( m ) {
  3110. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3111. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3112. const te = m.elements,
  3113. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3114. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3115. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3116. trace = m11 + m22 + m33;
  3117. if ( trace > 0 ) {
  3118. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3119. this._w = 0.25 / s;
  3120. this._x = ( m32 - m23 ) * s;
  3121. this._y = ( m13 - m31 ) * s;
  3122. this._z = ( m21 - m12 ) * s;
  3123. } else if ( m11 > m22 && m11 > m33 ) {
  3124. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3125. this._w = ( m32 - m23 ) / s;
  3126. this._x = 0.25 * s;
  3127. this._y = ( m12 + m21 ) / s;
  3128. this._z = ( m13 + m31 ) / s;
  3129. } else if ( m22 > m33 ) {
  3130. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3131. this._w = ( m13 - m31 ) / s;
  3132. this._x = ( m12 + m21 ) / s;
  3133. this._y = 0.25 * s;
  3134. this._z = ( m23 + m32 ) / s;
  3135. } else {
  3136. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3137. this._w = ( m21 - m12 ) / s;
  3138. this._x = ( m13 + m31 ) / s;
  3139. this._y = ( m23 + m32 ) / s;
  3140. this._z = 0.25 * s;
  3141. }
  3142. this._onChangeCallback();
  3143. return this;
  3144. }
  3145. /**
  3146. * Sets this quaternion to the rotation required to rotate the direction vector
  3147. * `vFrom` to the direction vector `vTo`.
  3148. *
  3149. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3150. * @param {Vector3} vTo - The second (normalized) direction vector.
  3151. * @return {Quaternion} A reference to this quaternion.
  3152. */
  3153. setFromUnitVectors( vFrom, vTo ) {
  3154. // assumes direction vectors vFrom and vTo are normalized
  3155. let r = vFrom.dot( vTo ) + 1;
  3156. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3157. // vFrom and vTo point in opposite directions
  3158. r = 0;
  3159. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3160. this._x = - vFrom.y;
  3161. this._y = vFrom.x;
  3162. this._z = 0;
  3163. this._w = r;
  3164. } else {
  3165. this._x = 0;
  3166. this._y = - vFrom.z;
  3167. this._z = vFrom.y;
  3168. this._w = r;
  3169. }
  3170. } else {
  3171. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3172. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3173. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3174. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3175. this._w = r;
  3176. }
  3177. return this.normalize();
  3178. }
  3179. /**
  3180. * Returns the angle between this quaternion and the given one in radians.
  3181. *
  3182. * @param {Quaternion} q - The quaternion to compute the angle with.
  3183. * @return {number} The angle in radians.
  3184. */
  3185. angleTo( q ) {
  3186. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3187. }
  3188. /**
  3189. * Rotates this quaternion by a given angular step to the given quaternion.
  3190. * The method ensures that the final quaternion will not overshoot `q`.
  3191. *
  3192. * @param {Quaternion} q - The target quaternion.
  3193. * @param {number} step - The angular step in radians.
  3194. * @return {Quaternion} A reference to this quaternion.
  3195. */
  3196. rotateTowards( q, step ) {
  3197. const angle = this.angleTo( q );
  3198. if ( angle === 0 ) return this;
  3199. const t = Math.min( 1, step / angle );
  3200. this.slerp( q, t );
  3201. return this;
  3202. }
  3203. /**
  3204. * Sets this quaternion to the identity quaternion; that is, to the
  3205. * quaternion that represents "no rotation".
  3206. *
  3207. * @return {Quaternion} A reference to this quaternion.
  3208. */
  3209. identity() {
  3210. return this.set( 0, 0, 0, 1 );
  3211. }
  3212. /**
  3213. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3214. * quaternion is assumed to have unit length.
  3215. *
  3216. * @return {Quaternion} A reference to this quaternion.
  3217. */
  3218. invert() {
  3219. return this.conjugate();
  3220. }
  3221. /**
  3222. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3223. * quaternion represents the same rotation in the opposite direction about
  3224. * the rotational axis.
  3225. *
  3226. * @return {Quaternion} A reference to this quaternion.
  3227. */
  3228. conjugate() {
  3229. this._x *= -1;
  3230. this._y *= -1;
  3231. this._z *= -1;
  3232. this._onChangeCallback();
  3233. return this;
  3234. }
  3235. /**
  3236. * Calculates the dot product of this quaternion and the given one.
  3237. *
  3238. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3239. * @return {number} The result of the dot product.
  3240. */
  3241. dot( v ) {
  3242. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3243. }
  3244. /**
  3245. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3246. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3247. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3248. * {@link Quaternion#length}.
  3249. *
  3250. * @return {number} The squared Euclidean length.
  3251. */
  3252. lengthSq() {
  3253. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3254. }
  3255. /**
  3256. * Computes the Euclidean length (straight-line length) of this quaternion,
  3257. * considered as a 4 dimensional vector.
  3258. *
  3259. * @return {number} The Euclidean length.
  3260. */
  3261. length() {
  3262. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3263. }
  3264. /**
  3265. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3266. * the same rotation as this one, but has a length equal to `1`.
  3267. *
  3268. * @return {Quaternion} A reference to this quaternion.
  3269. */
  3270. normalize() {
  3271. let l = this.length();
  3272. if ( l === 0 ) {
  3273. this._x = 0;
  3274. this._y = 0;
  3275. this._z = 0;
  3276. this._w = 1;
  3277. } else {
  3278. l = 1 / l;
  3279. this._x = this._x * l;
  3280. this._y = this._y * l;
  3281. this._z = this._z * l;
  3282. this._w = this._w * l;
  3283. }
  3284. this._onChangeCallback();
  3285. return this;
  3286. }
  3287. /**
  3288. * Multiplies this quaternion by the given one.
  3289. *
  3290. * @param {Quaternion} q - The quaternion.
  3291. * @return {Quaternion} A reference to this quaternion.
  3292. */
  3293. multiply( q ) {
  3294. return this.multiplyQuaternions( this, q );
  3295. }
  3296. /**
  3297. * Pre-multiplies this quaternion by the given one.
  3298. *
  3299. * @param {Quaternion} q - The quaternion.
  3300. * @return {Quaternion} A reference to this quaternion.
  3301. */
  3302. premultiply( q ) {
  3303. return this.multiplyQuaternions( q, this );
  3304. }
  3305. /**
  3306. * Multiplies the given quaternions and stores the result in this instance.
  3307. *
  3308. * @param {Quaternion} a - The first quaternion.
  3309. * @param {Quaternion} b - The second quaternion.
  3310. * @return {Quaternion} A reference to this quaternion.
  3311. */
  3312. multiplyQuaternions( a, b ) {
  3313. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3314. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3315. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3316. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3317. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3318. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3319. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3320. this._onChangeCallback();
  3321. return this;
  3322. }
  3323. /**
  3324. * Performs a spherical linear interpolation between quaternions.
  3325. *
  3326. * @param {Quaternion} qb - The target quaternion.
  3327. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3328. * @return {Quaternion} A reference to this quaternion.
  3329. */
  3330. slerp( qb, t ) {
  3331. if ( t === 0 ) return this;
  3332. if ( t === 1 ) return this.copy( qb );
  3333. const x = this._x, y = this._y, z = this._z, w = this._w;
  3334. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3335. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  3336. if ( cosHalfTheta < 0 ) {
  3337. this._w = - qb._w;
  3338. this._x = - qb._x;
  3339. this._y = - qb._y;
  3340. this._z = - qb._z;
  3341. cosHalfTheta = - cosHalfTheta;
  3342. } else {
  3343. this.copy( qb );
  3344. }
  3345. if ( cosHalfTheta >= 1.0 ) {
  3346. this._w = w;
  3347. this._x = x;
  3348. this._y = y;
  3349. this._z = z;
  3350. return this;
  3351. }
  3352. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  3353. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  3354. const s = 1 - t;
  3355. this._w = s * w + t * this._w;
  3356. this._x = s * x + t * this._x;
  3357. this._y = s * y + t * this._y;
  3358. this._z = s * z + t * this._z;
  3359. this.normalize(); // normalize calls _onChangeCallback()
  3360. return this;
  3361. }
  3362. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  3363. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  3364. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3365. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3366. this._w = ( w * ratioA + this._w * ratioB );
  3367. this._x = ( x * ratioA + this._x * ratioB );
  3368. this._y = ( y * ratioA + this._y * ratioB );
  3369. this._z = ( z * ratioA + this._z * ratioB );
  3370. this._onChangeCallback();
  3371. return this;
  3372. }
  3373. /**
  3374. * Performs a spherical linear interpolation between the given quaternions
  3375. * and stores the result in this quaternion.
  3376. *
  3377. * @param {Quaternion} qa - The source quaternion.
  3378. * @param {Quaternion} qb - The target quaternion.
  3379. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3380. * @return {Quaternion} A reference to this quaternion.
  3381. */
  3382. slerpQuaternions( qa, qb, t ) {
  3383. return this.copy( qa ).slerp( qb, t );
  3384. }
  3385. /**
  3386. * Sets this quaternion to a uniformly random, normalized quaternion.
  3387. *
  3388. * @return {Quaternion} A reference to this quaternion.
  3389. */
  3390. random() {
  3391. // Ken Shoemake
  3392. // Uniform random rotations
  3393. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3394. const theta1 = 2 * Math.PI * Math.random();
  3395. const theta2 = 2 * Math.PI * Math.random();
  3396. const x0 = Math.random();
  3397. const r1 = Math.sqrt( 1 - x0 );
  3398. const r2 = Math.sqrt( x0 );
  3399. return this.set(
  3400. r1 * Math.sin( theta1 ),
  3401. r1 * Math.cos( theta1 ),
  3402. r2 * Math.sin( theta2 ),
  3403. r2 * Math.cos( theta2 ),
  3404. );
  3405. }
  3406. /**
  3407. * Returns `true` if this quaternion is equal with the given one.
  3408. *
  3409. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3410. * @return {boolean} Whether this quaternion is equal with the given one.
  3411. */
  3412. equals( quaternion ) {
  3413. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3414. }
  3415. /**
  3416. * Sets this quaternion's components from the given array.
  3417. *
  3418. * @param {Array<number>} array - An array holding the quaternion component values.
  3419. * @param {number} [offset=0] - The offset into the array.
  3420. * @return {Quaternion} A reference to this quaternion.
  3421. */
  3422. fromArray( array, offset = 0 ) {
  3423. this._x = array[ offset ];
  3424. this._y = array[ offset + 1 ];
  3425. this._z = array[ offset + 2 ];
  3426. this._w = array[ offset + 3 ];
  3427. this._onChangeCallback();
  3428. return this;
  3429. }
  3430. /**
  3431. * Writes the components of this quaternion to the given array. If no array is provided,
  3432. * the method returns a new instance.
  3433. *
  3434. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3435. * @param {number} [offset=0] - Index of the first element in the array.
  3436. * @return {Array<number>} The quaternion components.
  3437. */
  3438. toArray( array = [], offset = 0 ) {
  3439. array[ offset ] = this._x;
  3440. array[ offset + 1 ] = this._y;
  3441. array[ offset + 2 ] = this._z;
  3442. array[ offset + 3 ] = this._w;
  3443. return array;
  3444. }
  3445. /**
  3446. * Sets the components of this quaternion from the given buffer attribute.
  3447. *
  3448. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3449. * @param {number} index - The index into the attribute.
  3450. * @return {Quaternion} A reference to this quaternion.
  3451. */
  3452. fromBufferAttribute( attribute, index ) {
  3453. this._x = attribute.getX( index );
  3454. this._y = attribute.getY( index );
  3455. this._z = attribute.getZ( index );
  3456. this._w = attribute.getW( index );
  3457. this._onChangeCallback();
  3458. return this;
  3459. }
  3460. /**
  3461. * This methods defines the serialization result of this class. Returns the
  3462. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3463. *
  3464. * @return {Array<number>} The serialized quaternion.
  3465. */
  3466. toJSON() {
  3467. return this.toArray();
  3468. }
  3469. _onChange( callback ) {
  3470. this._onChangeCallback = callback;
  3471. return this;
  3472. }
  3473. _onChangeCallback() {}
  3474. *[ Symbol.iterator ]() {
  3475. yield this._x;
  3476. yield this._y;
  3477. yield this._z;
  3478. yield this._w;
  3479. }
  3480. }
  3481. /**
  3482. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3483. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3484. *
  3485. * - A point in 3D space.
  3486. * - A direction and length in 3D space. In three.js the length will
  3487. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3488. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3489. * - Any arbitrary ordered triplet of numbers.
  3490. *
  3491. * There are other things a 3D vector can be used to represent, such as
  3492. * momentum vectors and so on, however these are the most
  3493. * common uses in three.js.
  3494. *
  3495. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3496. * the corresponding order.
  3497. * ```js
  3498. * const a = new THREE.Vector3( 0, 1, 0 );
  3499. *
  3500. * //no arguments; will be initialised to (0, 0, 0)
  3501. * const b = new THREE.Vector3( );
  3502. *
  3503. * const d = a.distanceTo( b );
  3504. * ```
  3505. */
  3506. class Vector3 {
  3507. /**
  3508. * Constructs a new 3D vector.
  3509. *
  3510. * @param {number} [x=0] - The x value of this vector.
  3511. * @param {number} [y=0] - The y value of this vector.
  3512. * @param {number} [z=0] - The z value of this vector.
  3513. */
  3514. constructor( x = 0, y = 0, z = 0 ) {
  3515. /**
  3516. * This flag can be used for type testing.
  3517. *
  3518. * @type {boolean}
  3519. * @readonly
  3520. * @default true
  3521. */
  3522. Vector3.prototype.isVector3 = true;
  3523. /**
  3524. * The x value of this vector.
  3525. *
  3526. * @type {number}
  3527. */
  3528. this.x = x;
  3529. /**
  3530. * The y value of this vector.
  3531. *
  3532. * @type {number}
  3533. */
  3534. this.y = y;
  3535. /**
  3536. * The z value of this vector.
  3537. *
  3538. * @type {number}
  3539. */
  3540. this.z = z;
  3541. }
  3542. /**
  3543. * Sets the vector components.
  3544. *
  3545. * @param {number} x - The value of the x component.
  3546. * @param {number} y - The value of the y component.
  3547. * @param {number} z - The value of the z component.
  3548. * @return {Vector3} A reference to this vector.
  3549. */
  3550. set( x, y, z ) {
  3551. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3552. this.x = x;
  3553. this.y = y;
  3554. this.z = z;
  3555. return this;
  3556. }
  3557. /**
  3558. * Sets the vector components to the same value.
  3559. *
  3560. * @param {number} scalar - The value to set for all vector components.
  3561. * @return {Vector3} A reference to this vector.
  3562. */
  3563. setScalar( scalar ) {
  3564. this.x = scalar;
  3565. this.y = scalar;
  3566. this.z = scalar;
  3567. return this;
  3568. }
  3569. /**
  3570. * Sets the vector's x component to the given value
  3571. *
  3572. * @param {number} x - The value to set.
  3573. * @return {Vector3} A reference to this vector.
  3574. */
  3575. setX( x ) {
  3576. this.x = x;
  3577. return this;
  3578. }
  3579. /**
  3580. * Sets the vector's y component to the given value
  3581. *
  3582. * @param {number} y - The value to set.
  3583. * @return {Vector3} A reference to this vector.
  3584. */
  3585. setY( y ) {
  3586. this.y = y;
  3587. return this;
  3588. }
  3589. /**
  3590. * Sets the vector's z component to the given value
  3591. *
  3592. * @param {number} z - The value to set.
  3593. * @return {Vector3} A reference to this vector.
  3594. */
  3595. setZ( z ) {
  3596. this.z = z;
  3597. return this;
  3598. }
  3599. /**
  3600. * Allows to set a vector component with an index.
  3601. *
  3602. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3603. * @param {number} value - The value to set.
  3604. * @return {Vector3} A reference to this vector.
  3605. */
  3606. setComponent( index, value ) {
  3607. switch ( index ) {
  3608. case 0: this.x = value; break;
  3609. case 1: this.y = value; break;
  3610. case 2: this.z = value; break;
  3611. default: throw new Error( 'index is out of range: ' + index );
  3612. }
  3613. return this;
  3614. }
  3615. /**
  3616. * Returns the value of the vector component which matches the given index.
  3617. *
  3618. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3619. * @return {number} A vector component value.
  3620. */
  3621. getComponent( index ) {
  3622. switch ( index ) {
  3623. case 0: return this.x;
  3624. case 1: return this.y;
  3625. case 2: return this.z;
  3626. default: throw new Error( 'index is out of range: ' + index );
  3627. }
  3628. }
  3629. /**
  3630. * Returns a new vector with copied values from this instance.
  3631. *
  3632. * @return {Vector3} A clone of this instance.
  3633. */
  3634. clone() {
  3635. return new this.constructor( this.x, this.y, this.z );
  3636. }
  3637. /**
  3638. * Copies the values of the given vector to this instance.
  3639. *
  3640. * @param {Vector3} v - The vector to copy.
  3641. * @return {Vector3} A reference to this vector.
  3642. */
  3643. copy( v ) {
  3644. this.x = v.x;
  3645. this.y = v.y;
  3646. this.z = v.z;
  3647. return this;
  3648. }
  3649. /**
  3650. * Adds the given vector to this instance.
  3651. *
  3652. * @param {Vector3} v - The vector to add.
  3653. * @return {Vector3} A reference to this vector.
  3654. */
  3655. add( v ) {
  3656. this.x += v.x;
  3657. this.y += v.y;
  3658. this.z += v.z;
  3659. return this;
  3660. }
  3661. /**
  3662. * Adds the given scalar value to all components of this instance.
  3663. *
  3664. * @param {number} s - The scalar to add.
  3665. * @return {Vector3} A reference to this vector.
  3666. */
  3667. addScalar( s ) {
  3668. this.x += s;
  3669. this.y += s;
  3670. this.z += s;
  3671. return this;
  3672. }
  3673. /**
  3674. * Adds the given vectors and stores the result in this instance.
  3675. *
  3676. * @param {Vector3} a - The first vector.
  3677. * @param {Vector3} b - The second vector.
  3678. * @return {Vector3} A reference to this vector.
  3679. */
  3680. addVectors( a, b ) {
  3681. this.x = a.x + b.x;
  3682. this.y = a.y + b.y;
  3683. this.z = a.z + b.z;
  3684. return this;
  3685. }
  3686. /**
  3687. * Adds the given vector scaled by the given factor to this instance.
  3688. *
  3689. * @param {Vector3|Vector4} v - The vector.
  3690. * @param {number} s - The factor that scales `v`.
  3691. * @return {Vector3} A reference to this vector.
  3692. */
  3693. addScaledVector( v, s ) {
  3694. this.x += v.x * s;
  3695. this.y += v.y * s;
  3696. this.z += v.z * s;
  3697. return this;
  3698. }
  3699. /**
  3700. * Subtracts the given vector from this instance.
  3701. *
  3702. * @param {Vector3} v - The vector to subtract.
  3703. * @return {Vector3} A reference to this vector.
  3704. */
  3705. sub( v ) {
  3706. this.x -= v.x;
  3707. this.y -= v.y;
  3708. this.z -= v.z;
  3709. return this;
  3710. }
  3711. /**
  3712. * Subtracts the given scalar value from all components of this instance.
  3713. *
  3714. * @param {number} s - The scalar to subtract.
  3715. * @return {Vector3} A reference to this vector.
  3716. */
  3717. subScalar( s ) {
  3718. this.x -= s;
  3719. this.y -= s;
  3720. this.z -= s;
  3721. return this;
  3722. }
  3723. /**
  3724. * Subtracts the given vectors and stores the result in this instance.
  3725. *
  3726. * @param {Vector3} a - The first vector.
  3727. * @param {Vector3} b - The second vector.
  3728. * @return {Vector3} A reference to this vector.
  3729. */
  3730. subVectors( a, b ) {
  3731. this.x = a.x - b.x;
  3732. this.y = a.y - b.y;
  3733. this.z = a.z - b.z;
  3734. return this;
  3735. }
  3736. /**
  3737. * Multiplies the given vector with this instance.
  3738. *
  3739. * @param {Vector3} v - The vector to multiply.
  3740. * @return {Vector3} A reference to this vector.
  3741. */
  3742. multiply( v ) {
  3743. this.x *= v.x;
  3744. this.y *= v.y;
  3745. this.z *= v.z;
  3746. return this;
  3747. }
  3748. /**
  3749. * Multiplies the given scalar value with all components of this instance.
  3750. *
  3751. * @param {number} scalar - The scalar to multiply.
  3752. * @return {Vector3} A reference to this vector.
  3753. */
  3754. multiplyScalar( scalar ) {
  3755. this.x *= scalar;
  3756. this.y *= scalar;
  3757. this.z *= scalar;
  3758. return this;
  3759. }
  3760. /**
  3761. * Multiplies the given vectors and stores the result in this instance.
  3762. *
  3763. * @param {Vector3} a - The first vector.
  3764. * @param {Vector3} b - The second vector.
  3765. * @return {Vector3} A reference to this vector.
  3766. */
  3767. multiplyVectors( a, b ) {
  3768. this.x = a.x * b.x;
  3769. this.y = a.y * b.y;
  3770. this.z = a.z * b.z;
  3771. return this;
  3772. }
  3773. /**
  3774. * Applies the given Euler rotation to this vector.
  3775. *
  3776. * @param {Euler} euler - The Euler angles.
  3777. * @return {Vector3} A reference to this vector.
  3778. */
  3779. applyEuler( euler ) {
  3780. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3781. }
  3782. /**
  3783. * Applies a rotation specified by an axis and an angle to this vector.
  3784. *
  3785. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3786. * @param {number} angle - The angle in radians.
  3787. * @return {Vector3} A reference to this vector.
  3788. */
  3789. applyAxisAngle( axis, angle ) {
  3790. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3791. }
  3792. /**
  3793. * Multiplies this vector with the given 3x3 matrix.
  3794. *
  3795. * @param {Matrix3} m - The 3x3 matrix.
  3796. * @return {Vector3} A reference to this vector.
  3797. */
  3798. applyMatrix3( m ) {
  3799. const x = this.x, y = this.y, z = this.z;
  3800. const e = m.elements;
  3801. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3802. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3803. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3804. return this;
  3805. }
  3806. /**
  3807. * Multiplies this vector by the given normal matrix and normalizes
  3808. * the result.
  3809. *
  3810. * @param {Matrix3} m - The normal matrix.
  3811. * @return {Vector3} A reference to this vector.
  3812. */
  3813. applyNormalMatrix( m ) {
  3814. return this.applyMatrix3( m ).normalize();
  3815. }
  3816. /**
  3817. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3818. * divides by perspective.
  3819. *
  3820. * @param {Matrix4} m - The matrix to apply.
  3821. * @return {Vector3} A reference to this vector.
  3822. */
  3823. applyMatrix4( m ) {
  3824. const x = this.x, y = this.y, z = this.z;
  3825. const e = m.elements;
  3826. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3827. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3828. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3829. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3830. return this;
  3831. }
  3832. /**
  3833. * Applies the given Quaternion to this vector.
  3834. *
  3835. * @param {Quaternion} q - The Quaternion.
  3836. * @return {Vector3} A reference to this vector.
  3837. */
  3838. applyQuaternion( q ) {
  3839. // quaternion q is assumed to have unit length
  3840. const vx = this.x, vy = this.y, vz = this.z;
  3841. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3842. // t = 2 * cross( q.xyz, v );
  3843. const tx = 2 * ( qy * vz - qz * vy );
  3844. const ty = 2 * ( qz * vx - qx * vz );
  3845. const tz = 2 * ( qx * vy - qy * vx );
  3846. // v + q.w * t + cross( q.xyz, t );
  3847. this.x = vx + qw * tx + qy * tz - qz * ty;
  3848. this.y = vy + qw * ty + qz * tx - qx * tz;
  3849. this.z = vz + qw * tz + qx * ty - qy * tx;
  3850. return this;
  3851. }
  3852. /**
  3853. * Projects this vector from world space into the camera's normalized
  3854. * device coordinate (NDC) space.
  3855. *
  3856. * @param {Camera} camera - The camera.
  3857. * @return {Vector3} A reference to this vector.
  3858. */
  3859. project( camera ) {
  3860. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3861. }
  3862. /**
  3863. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  3864. * space into world space.
  3865. *
  3866. * @param {Camera} camera - The camera.
  3867. * @return {Vector3} A reference to this vector.
  3868. */
  3869. unproject( camera ) {
  3870. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  3871. }
  3872. /**
  3873. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  3874. * subset of the given 4x4 matrix and then normalizes the result.
  3875. *
  3876. * @param {Matrix4} m - The matrix.
  3877. * @return {Vector3} A reference to this vector.
  3878. */
  3879. transformDirection( m ) {
  3880. // input: THREE.Matrix4 affine matrix
  3881. // vector interpreted as a direction
  3882. const x = this.x, y = this.y, z = this.z;
  3883. const e = m.elements;
  3884. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  3885. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  3886. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  3887. return this.normalize();
  3888. }
  3889. /**
  3890. * Divides this instance by the given vector.
  3891. *
  3892. * @param {Vector3} v - The vector to divide.
  3893. * @return {Vector3} A reference to this vector.
  3894. */
  3895. divide( v ) {
  3896. this.x /= v.x;
  3897. this.y /= v.y;
  3898. this.z /= v.z;
  3899. return this;
  3900. }
  3901. /**
  3902. * Divides this vector by the given scalar.
  3903. *
  3904. * @param {number} scalar - The scalar to divide.
  3905. * @return {Vector3} A reference to this vector.
  3906. */
  3907. divideScalar( scalar ) {
  3908. return this.multiplyScalar( 1 / scalar );
  3909. }
  3910. /**
  3911. * If this vector's x, y or z value is greater than the given vector's x, y or z
  3912. * value, replace that value with the corresponding min value.
  3913. *
  3914. * @param {Vector3} v - The vector.
  3915. * @return {Vector3} A reference to this vector.
  3916. */
  3917. min( v ) {
  3918. this.x = Math.min( this.x, v.x );
  3919. this.y = Math.min( this.y, v.y );
  3920. this.z = Math.min( this.z, v.z );
  3921. return this;
  3922. }
  3923. /**
  3924. * If this vector's x, y or z value is less than the given vector's x, y or z
  3925. * value, replace that value with the corresponding max value.
  3926. *
  3927. * @param {Vector3} v - The vector.
  3928. * @return {Vector3} A reference to this vector.
  3929. */
  3930. max( v ) {
  3931. this.x = Math.max( this.x, v.x );
  3932. this.y = Math.max( this.y, v.y );
  3933. this.z = Math.max( this.z, v.z );
  3934. return this;
  3935. }
  3936. /**
  3937. * If this vector's x, y or z value is greater than the max vector's x, y or z
  3938. * value, it is replaced by the corresponding value.
  3939. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  3940. * it is replaced by the corresponding value.
  3941. *
  3942. * @param {Vector3} min - The minimum x, y and z values.
  3943. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  3944. * @return {Vector3} A reference to this vector.
  3945. */
  3946. clamp( min, max ) {
  3947. // assumes min < max, componentwise
  3948. this.x = clamp( this.x, min.x, max.x );
  3949. this.y = clamp( this.y, min.y, max.y );
  3950. this.z = clamp( this.z, min.z, max.z );
  3951. return this;
  3952. }
  3953. /**
  3954. * If this vector's x, y or z values are greater than the max value, they are
  3955. * replaced by the max value.
  3956. * If this vector's x, y or z values are less than the min value, they are
  3957. * replaced by the min value.
  3958. *
  3959. * @param {number} minVal - The minimum value the components will be clamped to.
  3960. * @param {number} maxVal - The maximum value the components will be clamped to.
  3961. * @return {Vector3} A reference to this vector.
  3962. */
  3963. clampScalar( minVal, maxVal ) {
  3964. this.x = clamp( this.x, minVal, maxVal );
  3965. this.y = clamp( this.y, minVal, maxVal );
  3966. this.z = clamp( this.z, minVal, maxVal );
  3967. return this;
  3968. }
  3969. /**
  3970. * If this vector's length is greater than the max value, it is replaced by
  3971. * the max value.
  3972. * If this vector's length is less than the min value, it is replaced by the
  3973. * min value.
  3974. *
  3975. * @param {number} min - The minimum value the vector length will be clamped to.
  3976. * @param {number} max - The maximum value the vector length will be clamped to.
  3977. * @return {Vector3} A reference to this vector.
  3978. */
  3979. clampLength( min, max ) {
  3980. const length = this.length();
  3981. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3982. }
  3983. /**
  3984. * The components of this vector are rounded down to the nearest integer value.
  3985. *
  3986. * @return {Vector3} A reference to this vector.
  3987. */
  3988. floor() {
  3989. this.x = Math.floor( this.x );
  3990. this.y = Math.floor( this.y );
  3991. this.z = Math.floor( this.z );
  3992. return this;
  3993. }
  3994. /**
  3995. * The components of this vector are rounded up to the nearest integer value.
  3996. *
  3997. * @return {Vector3} A reference to this vector.
  3998. */
  3999. ceil() {
  4000. this.x = Math.ceil( this.x );
  4001. this.y = Math.ceil( this.y );
  4002. this.z = Math.ceil( this.z );
  4003. return this;
  4004. }
  4005. /**
  4006. * The components of this vector are rounded to the nearest integer value
  4007. *
  4008. * @return {Vector3} A reference to this vector.
  4009. */
  4010. round() {
  4011. this.x = Math.round( this.x );
  4012. this.y = Math.round( this.y );
  4013. this.z = Math.round( this.z );
  4014. return this;
  4015. }
  4016. /**
  4017. * The components of this vector are rounded towards zero (up if negative,
  4018. * down if positive) to an integer value.
  4019. *
  4020. * @return {Vector3} A reference to this vector.
  4021. */
  4022. roundToZero() {
  4023. this.x = Math.trunc( this.x );
  4024. this.y = Math.trunc( this.y );
  4025. this.z = Math.trunc( this.z );
  4026. return this;
  4027. }
  4028. /**
  4029. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4030. *
  4031. * @return {Vector3} A reference to this vector.
  4032. */
  4033. negate() {
  4034. this.x = - this.x;
  4035. this.y = - this.y;
  4036. this.z = - this.z;
  4037. return this;
  4038. }
  4039. /**
  4040. * Calculates the dot product of the given vector with this instance.
  4041. *
  4042. * @param {Vector3} v - The vector to compute the dot product with.
  4043. * @return {number} The result of the dot product.
  4044. */
  4045. dot( v ) {
  4046. return this.x * v.x + this.y * v.y + this.z * v.z;
  4047. }
  4048. // TODO lengthSquared?
  4049. /**
  4050. * Computes the square of the Euclidean length (straight-line length) from
  4051. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4052. * compare the length squared instead as it is slightly more efficient to calculate.
  4053. *
  4054. * @return {number} The square length of this vector.
  4055. */
  4056. lengthSq() {
  4057. return this.x * this.x + this.y * this.y + this.z * this.z;
  4058. }
  4059. /**
  4060. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4061. *
  4062. * @return {number} The length of this vector.
  4063. */
  4064. length() {
  4065. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4066. }
  4067. /**
  4068. * Computes the Manhattan length of this vector.
  4069. *
  4070. * @return {number} The length of this vector.
  4071. */
  4072. manhattanLength() {
  4073. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4074. }
  4075. /**
  4076. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4077. * with the same direction as this one, but with a vector length of `1`.
  4078. *
  4079. * @return {Vector3} A reference to this vector.
  4080. */
  4081. normalize() {
  4082. return this.divideScalar( this.length() || 1 );
  4083. }
  4084. /**
  4085. * Sets this vector to a vector with the same direction as this one, but
  4086. * with the specified length.
  4087. *
  4088. * @param {number} length - The new length of this vector.
  4089. * @return {Vector3} A reference to this vector.
  4090. */
  4091. setLength( length ) {
  4092. return this.normalize().multiplyScalar( length );
  4093. }
  4094. /**
  4095. * Linearly interpolates between the given vector and this instance, where
  4096. * alpha is the percent distance along the line - alpha = 0 will be this
  4097. * vector, and alpha = 1 will be the given one.
  4098. *
  4099. * @param {Vector3} v - The vector to interpolate towards.
  4100. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4101. * @return {Vector3} A reference to this vector.
  4102. */
  4103. lerp( v, alpha ) {
  4104. this.x += ( v.x - this.x ) * alpha;
  4105. this.y += ( v.y - this.y ) * alpha;
  4106. this.z += ( v.z - this.z ) * alpha;
  4107. return this;
  4108. }
  4109. /**
  4110. * Linearly interpolates between the given vectors, where alpha is the percent
  4111. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4112. * be the second one. The result is stored in this instance.
  4113. *
  4114. * @param {Vector3} v1 - The first vector.
  4115. * @param {Vector3} v2 - The second vector.
  4116. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4117. * @return {Vector3} A reference to this vector.
  4118. */
  4119. lerpVectors( v1, v2, alpha ) {
  4120. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4121. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4122. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4123. return this;
  4124. }
  4125. /**
  4126. * Calculates the cross product of the given vector with this instance.
  4127. *
  4128. * @param {Vector3} v - The vector to compute the cross product with.
  4129. * @return {Vector3} The result of the cross product.
  4130. */
  4131. cross( v ) {
  4132. return this.crossVectors( this, v );
  4133. }
  4134. /**
  4135. * Calculates the cross product of the given vectors and stores the result
  4136. * in this instance.
  4137. *
  4138. * @param {Vector3} a - The first vector.
  4139. * @param {Vector3} b - The second vector.
  4140. * @return {Vector3} A reference to this vector.
  4141. */
  4142. crossVectors( a, b ) {
  4143. const ax = a.x, ay = a.y, az = a.z;
  4144. const bx = b.x, by = b.y, bz = b.z;
  4145. this.x = ay * bz - az * by;
  4146. this.y = az * bx - ax * bz;
  4147. this.z = ax * by - ay * bx;
  4148. return this;
  4149. }
  4150. /**
  4151. * Projects this vector onto the given one.
  4152. *
  4153. * @param {Vector3} v - The vector to project to.
  4154. * @return {Vector3} A reference to this vector.
  4155. */
  4156. projectOnVector( v ) {
  4157. const denominator = v.lengthSq();
  4158. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4159. const scalar = v.dot( this ) / denominator;
  4160. return this.copy( v ).multiplyScalar( scalar );
  4161. }
  4162. /**
  4163. * Projects this vector onto a plane by subtracting this
  4164. * vector projected onto the plane's normal from this vector.
  4165. *
  4166. * @param {Vector3} planeNormal - The plane normal.
  4167. * @return {Vector3} A reference to this vector.
  4168. */
  4169. projectOnPlane( planeNormal ) {
  4170. _vector$c.copy( this ).projectOnVector( planeNormal );
  4171. return this.sub( _vector$c );
  4172. }
  4173. /**
  4174. * Reflects this vector off a plane orthogonal to the given normal vector.
  4175. *
  4176. * @param {Vector3} normal - The (normalized) normal vector.
  4177. * @return {Vector3} A reference to this vector.
  4178. */
  4179. reflect( normal ) {
  4180. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4181. }
  4182. /**
  4183. * Returns the angle between the given vector and this instance in radians.
  4184. *
  4185. * @param {Vector3} v - The vector to compute the angle with.
  4186. * @return {number} The angle in radians.
  4187. */
  4188. angleTo( v ) {
  4189. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4190. if ( denominator === 0 ) return Math.PI / 2;
  4191. const theta = this.dot( v ) / denominator;
  4192. // clamp, to handle numerical problems
  4193. return Math.acos( clamp( theta, -1, 1 ) );
  4194. }
  4195. /**
  4196. * Computes the distance from the given vector to this instance.
  4197. *
  4198. * @param {Vector3} v - The vector to compute the distance to.
  4199. * @return {number} The distance.
  4200. */
  4201. distanceTo( v ) {
  4202. return Math.sqrt( this.distanceToSquared( v ) );
  4203. }
  4204. /**
  4205. * Computes the squared distance from the given vector to this instance.
  4206. * If you are just comparing the distance with another distance, you should compare
  4207. * the distance squared instead as it is slightly more efficient to calculate.
  4208. *
  4209. * @param {Vector3} v - The vector to compute the squared distance to.
  4210. * @return {number} The squared distance.
  4211. */
  4212. distanceToSquared( v ) {
  4213. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4214. return dx * dx + dy * dy + dz * dz;
  4215. }
  4216. /**
  4217. * Computes the Manhattan distance from the given vector to this instance.
  4218. *
  4219. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4220. * @return {number} The Manhattan distance.
  4221. */
  4222. manhattanDistanceTo( v ) {
  4223. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4224. }
  4225. /**
  4226. * Sets the vector components from the given spherical coordinates.
  4227. *
  4228. * @param {Spherical} s - The spherical coordinates.
  4229. * @return {Vector3} A reference to this vector.
  4230. */
  4231. setFromSpherical( s ) {
  4232. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4233. }
  4234. /**
  4235. * Sets the vector components from the given spherical coordinates.
  4236. *
  4237. * @param {number} radius - The radius.
  4238. * @param {number} phi - The phi angle in radians.
  4239. * @param {number} theta - The theta angle in radians.
  4240. * @return {Vector3} A reference to this vector.
  4241. */
  4242. setFromSphericalCoords( radius, phi, theta ) {
  4243. const sinPhiRadius = Math.sin( phi ) * radius;
  4244. this.x = sinPhiRadius * Math.sin( theta );
  4245. this.y = Math.cos( phi ) * radius;
  4246. this.z = sinPhiRadius * Math.cos( theta );
  4247. return this;
  4248. }
  4249. /**
  4250. * Sets the vector components from the given cylindrical coordinates.
  4251. *
  4252. * @param {Cylindrical} c - The cylindrical coordinates.
  4253. * @return {Vector3} A reference to this vector.
  4254. */
  4255. setFromCylindrical( c ) {
  4256. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4257. }
  4258. /**
  4259. * Sets the vector components from the given cylindrical coordinates.
  4260. *
  4261. * @param {number} radius - The radius.
  4262. * @param {number} theta - The theta angle in radians.
  4263. * @param {number} y - The y value.
  4264. * @return {Vector3} A reference to this vector.
  4265. */
  4266. setFromCylindricalCoords( radius, theta, y ) {
  4267. this.x = radius * Math.sin( theta );
  4268. this.y = y;
  4269. this.z = radius * Math.cos( theta );
  4270. return this;
  4271. }
  4272. /**
  4273. * Sets the vector components to the position elements of the
  4274. * given transformation matrix.
  4275. *
  4276. * @param {Matrix4} m - The 4x4 matrix.
  4277. * @return {Vector3} A reference to this vector.
  4278. */
  4279. setFromMatrixPosition( m ) {
  4280. const e = m.elements;
  4281. this.x = e[ 12 ];
  4282. this.y = e[ 13 ];
  4283. this.z = e[ 14 ];
  4284. return this;
  4285. }
  4286. /**
  4287. * Sets the vector components to the scale elements of the
  4288. * given transformation matrix.
  4289. *
  4290. * @param {Matrix4} m - The 4x4 matrix.
  4291. * @return {Vector3} A reference to this vector.
  4292. */
  4293. setFromMatrixScale( m ) {
  4294. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4295. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4296. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4297. this.x = sx;
  4298. this.y = sy;
  4299. this.z = sz;
  4300. return this;
  4301. }
  4302. /**
  4303. * Sets the vector components from the specified matrix column.
  4304. *
  4305. * @param {Matrix4} m - The 4x4 matrix.
  4306. * @param {number} index - The column index.
  4307. * @return {Vector3} A reference to this vector.
  4308. */
  4309. setFromMatrixColumn( m, index ) {
  4310. return this.fromArray( m.elements, index * 4 );
  4311. }
  4312. /**
  4313. * Sets the vector components from the specified matrix column.
  4314. *
  4315. * @param {Matrix3} m - The 3x3 matrix.
  4316. * @param {number} index - The column index.
  4317. * @return {Vector3} A reference to this vector.
  4318. */
  4319. setFromMatrix3Column( m, index ) {
  4320. return this.fromArray( m.elements, index * 3 );
  4321. }
  4322. /**
  4323. * Sets the vector components from the given Euler angles.
  4324. *
  4325. * @param {Euler} e - The Euler angles to set.
  4326. * @return {Vector3} A reference to this vector.
  4327. */
  4328. setFromEuler( e ) {
  4329. this.x = e._x;
  4330. this.y = e._y;
  4331. this.z = e._z;
  4332. return this;
  4333. }
  4334. /**
  4335. * Sets the vector components from the RGB components of the
  4336. * given color.
  4337. *
  4338. * @param {Color} c - The color to set.
  4339. * @return {Vector3} A reference to this vector.
  4340. */
  4341. setFromColor( c ) {
  4342. this.x = c.r;
  4343. this.y = c.g;
  4344. this.z = c.b;
  4345. return this;
  4346. }
  4347. /**
  4348. * Returns `true` if this vector is equal with the given one.
  4349. *
  4350. * @param {Vector3} v - The vector to test for equality.
  4351. * @return {boolean} Whether this vector is equal with the given one.
  4352. */
  4353. equals( v ) {
  4354. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4355. }
  4356. /**
  4357. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4358. * and z value to be `array[ offset + 2 ]`.
  4359. *
  4360. * @param {Array<number>} array - An array holding the vector component values.
  4361. * @param {number} [offset=0] - The offset into the array.
  4362. * @return {Vector3} A reference to this vector.
  4363. */
  4364. fromArray( array, offset = 0 ) {
  4365. this.x = array[ offset ];
  4366. this.y = array[ offset + 1 ];
  4367. this.z = array[ offset + 2 ];
  4368. return this;
  4369. }
  4370. /**
  4371. * Writes the components of this vector to the given array. If no array is provided,
  4372. * the method returns a new instance.
  4373. *
  4374. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4375. * @param {number} [offset=0] - Index of the first element in the array.
  4376. * @return {Array<number>} The vector components.
  4377. */
  4378. toArray( array = [], offset = 0 ) {
  4379. array[ offset ] = this.x;
  4380. array[ offset + 1 ] = this.y;
  4381. array[ offset + 2 ] = this.z;
  4382. return array;
  4383. }
  4384. /**
  4385. * Sets the components of this vector from the given buffer attribute.
  4386. *
  4387. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4388. * @param {number} index - The index into the attribute.
  4389. * @return {Vector3} A reference to this vector.
  4390. */
  4391. fromBufferAttribute( attribute, index ) {
  4392. this.x = attribute.getX( index );
  4393. this.y = attribute.getY( index );
  4394. this.z = attribute.getZ( index );
  4395. return this;
  4396. }
  4397. /**
  4398. * Sets each component of this vector to a pseudo-random value between `0` and
  4399. * `1`, excluding `1`.
  4400. *
  4401. * @return {Vector3} A reference to this vector.
  4402. */
  4403. random() {
  4404. this.x = Math.random();
  4405. this.y = Math.random();
  4406. this.z = Math.random();
  4407. return this;
  4408. }
  4409. /**
  4410. * Sets this vector to a uniformly random point on a unit sphere.
  4411. *
  4412. * @return {Vector3} A reference to this vector.
  4413. */
  4414. randomDirection() {
  4415. // https://mathworld.wolfram.com/SpherePointPicking.html
  4416. const theta = Math.random() * Math.PI * 2;
  4417. const u = Math.random() * 2 - 1;
  4418. const c = Math.sqrt( 1 - u * u );
  4419. this.x = c * Math.cos( theta );
  4420. this.y = u;
  4421. this.z = c * Math.sin( theta );
  4422. return this;
  4423. }
  4424. *[ Symbol.iterator ]() {
  4425. yield this.x;
  4426. yield this.y;
  4427. yield this.z;
  4428. }
  4429. }
  4430. const _vector$c = /*@__PURE__*/ new Vector3();
  4431. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4432. /**
  4433. * Represents a 3x3 matrix.
  4434. *
  4435. * A Note on Row-Major and Column-Major Ordering:
  4436. *
  4437. * The constructor and {@link Matrix3#set} method take arguments in
  4438. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  4439. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4440. * This means that calling:
  4441. * ```js
  4442. * const m = new THREE.Matrix();
  4443. * m.set( 11, 12, 13,
  4444. * 21, 22, 23,
  4445. * 31, 32, 33 );
  4446. * ```
  4447. * will result in the elements array containing:
  4448. * ```js
  4449. * m.elements = [ 11, 21, 31,
  4450. * 12, 22, 32,
  4451. * 13, 23, 33 ];
  4452. * ```
  4453. * and internally all calculations are performed using column-major ordering.
  4454. * However, as the actual ordering makes no difference mathematically and
  4455. * most people are used to thinking about matrices in row-major order, the
  4456. * three.js documentation shows matrices in row-major order. Just bear in
  4457. * mind that if you are reading the source code, you'll have to take the
  4458. * transpose of any matrices outlined here to make sense of the calculations.
  4459. */
  4460. class Matrix3 {
  4461. /**
  4462. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4463. * in row-major order. If no arguments are provided, the constructor
  4464. * initializes the matrix as an identity matrix.
  4465. *
  4466. * @param {number} [n11] - 1-1 matrix element.
  4467. * @param {number} [n12] - 1-2 matrix element.
  4468. * @param {number} [n13] - 1-3 matrix element.
  4469. * @param {number} [n21] - 2-1 matrix element.
  4470. * @param {number} [n22] - 2-2 matrix element.
  4471. * @param {number} [n23] - 2-3 matrix element.
  4472. * @param {number} [n31] - 3-1 matrix element.
  4473. * @param {number} [n32] - 3-2 matrix element.
  4474. * @param {number} [n33] - 3-3 matrix element.
  4475. */
  4476. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4477. /**
  4478. * This flag can be used for type testing.
  4479. *
  4480. * @type {boolean}
  4481. * @readonly
  4482. * @default true
  4483. */
  4484. Matrix3.prototype.isMatrix3 = true;
  4485. /**
  4486. * A column-major list of matrix values.
  4487. *
  4488. * @type {Array<number>}
  4489. */
  4490. this.elements = [
  4491. 1, 0, 0,
  4492. 0, 1, 0,
  4493. 0, 0, 1
  4494. ];
  4495. if ( n11 !== undefined ) {
  4496. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4497. }
  4498. }
  4499. /**
  4500. * Sets the elements of the matrix.The arguments are supposed to be
  4501. * in row-major order.
  4502. *
  4503. * @param {number} [n11] - 1-1 matrix element.
  4504. * @param {number} [n12] - 1-2 matrix element.
  4505. * @param {number} [n13] - 1-3 matrix element.
  4506. * @param {number} [n21] - 2-1 matrix element.
  4507. * @param {number} [n22] - 2-2 matrix element.
  4508. * @param {number} [n23] - 2-3 matrix element.
  4509. * @param {number} [n31] - 3-1 matrix element.
  4510. * @param {number} [n32] - 3-2 matrix element.
  4511. * @param {number} [n33] - 3-3 matrix element.
  4512. * @return {Matrix3} A reference to this matrix.
  4513. */
  4514. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4515. const te = this.elements;
  4516. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4517. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4518. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4519. return this;
  4520. }
  4521. /**
  4522. * Sets this matrix to the 3x3 identity matrix.
  4523. *
  4524. * @return {Matrix3} A reference to this matrix.
  4525. */
  4526. identity() {
  4527. this.set(
  4528. 1, 0, 0,
  4529. 0, 1, 0,
  4530. 0, 0, 1
  4531. );
  4532. return this;
  4533. }
  4534. /**
  4535. * Copies the values of the given matrix to this instance.
  4536. *
  4537. * @param {Matrix3} m - The matrix to copy.
  4538. * @return {Matrix3} A reference to this matrix.
  4539. */
  4540. copy( m ) {
  4541. const te = this.elements;
  4542. const me = m.elements;
  4543. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4544. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4545. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4546. return this;
  4547. }
  4548. /**
  4549. * Extracts the basis of this matrix into the three axis vectors provided.
  4550. *
  4551. * @param {Vector3} xAxis - The basis's x axis.
  4552. * @param {Vector3} yAxis - The basis's y axis.
  4553. * @param {Vector3} zAxis - The basis's z axis.
  4554. * @return {Matrix3} A reference to this matrix.
  4555. */
  4556. extractBasis( xAxis, yAxis, zAxis ) {
  4557. xAxis.setFromMatrix3Column( this, 0 );
  4558. yAxis.setFromMatrix3Column( this, 1 );
  4559. zAxis.setFromMatrix3Column( this, 2 );
  4560. return this;
  4561. }
  4562. /**
  4563. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4564. *
  4565. * @param {Matrix4} m - The 4x4 matrix.
  4566. * @return {Matrix3} A reference to this matrix.
  4567. */
  4568. setFromMatrix4( m ) {
  4569. const me = m.elements;
  4570. this.set(
  4571. me[ 0 ], me[ 4 ], me[ 8 ],
  4572. me[ 1 ], me[ 5 ], me[ 9 ],
  4573. me[ 2 ], me[ 6 ], me[ 10 ]
  4574. );
  4575. return this;
  4576. }
  4577. /**
  4578. * Post-multiplies this matrix by the given 3x3 matrix.
  4579. *
  4580. * @param {Matrix3} m - The matrix to multiply with.
  4581. * @return {Matrix3} A reference to this matrix.
  4582. */
  4583. multiply( m ) {
  4584. return this.multiplyMatrices( this, m );
  4585. }
  4586. /**
  4587. * Pre-multiplies this matrix by the given 3x3 matrix.
  4588. *
  4589. * @param {Matrix3} m - The matrix to multiply with.
  4590. * @return {Matrix3} A reference to this matrix.
  4591. */
  4592. premultiply( m ) {
  4593. return this.multiplyMatrices( m, this );
  4594. }
  4595. /**
  4596. * Multiples the given 3x3 matrices and stores the result
  4597. * in this matrix.
  4598. *
  4599. * @param {Matrix3} a - The first matrix.
  4600. * @param {Matrix3} b - The second matrix.
  4601. * @return {Matrix3} A reference to this matrix.
  4602. */
  4603. multiplyMatrices( a, b ) {
  4604. const ae = a.elements;
  4605. const be = b.elements;
  4606. const te = this.elements;
  4607. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4608. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4609. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4610. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4611. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4612. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4613. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4614. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4615. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4616. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4617. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4618. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4619. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4620. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4621. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4622. return this;
  4623. }
  4624. /**
  4625. * Multiplies every component of the matrix by the given scalar.
  4626. *
  4627. * @param {number} s - The scalar.
  4628. * @return {Matrix3} A reference to this matrix.
  4629. */
  4630. multiplyScalar( s ) {
  4631. const te = this.elements;
  4632. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4633. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4634. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4635. return this;
  4636. }
  4637. /**
  4638. * Computes and returns the determinant of this matrix.
  4639. *
  4640. * @return {number} The determinant.
  4641. */
  4642. determinant() {
  4643. const te = this.elements;
  4644. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4645. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4646. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4647. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4648. }
  4649. /**
  4650. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  4651. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4652. * a zero matrix instead.
  4653. *
  4654. * @return {Matrix3} A reference to this matrix.
  4655. */
  4656. invert() {
  4657. const te = this.elements,
  4658. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4659. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4660. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4661. t11 = n33 * n22 - n32 * n23,
  4662. t12 = n32 * n13 - n33 * n12,
  4663. t13 = n23 * n12 - n22 * n13,
  4664. det = n11 * t11 + n21 * t12 + n31 * t13;
  4665. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4666. const detInv = 1 / det;
  4667. te[ 0 ] = t11 * detInv;
  4668. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4669. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4670. te[ 3 ] = t12 * detInv;
  4671. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4672. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4673. te[ 6 ] = t13 * detInv;
  4674. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4675. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4676. return this;
  4677. }
  4678. /**
  4679. * Transposes this matrix in place.
  4680. *
  4681. * @return {Matrix3} A reference to this matrix.
  4682. */
  4683. transpose() {
  4684. let tmp;
  4685. const m = this.elements;
  4686. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4687. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4688. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4689. return this;
  4690. }
  4691. /**
  4692. * Computes the normal matrix which is the inverse transpose of the upper
  4693. * left 3x3 portion of the given 4x4 matrix.
  4694. *
  4695. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4696. * @return {Matrix3} A reference to this matrix.
  4697. */
  4698. getNormalMatrix( matrix4 ) {
  4699. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4700. }
  4701. /**
  4702. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4703. *
  4704. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4705. * @return {Matrix3} A reference to this matrix.
  4706. */
  4707. transposeIntoArray( r ) {
  4708. const m = this.elements;
  4709. r[ 0 ] = m[ 0 ];
  4710. r[ 1 ] = m[ 3 ];
  4711. r[ 2 ] = m[ 6 ];
  4712. r[ 3 ] = m[ 1 ];
  4713. r[ 4 ] = m[ 4 ];
  4714. r[ 5 ] = m[ 7 ];
  4715. r[ 6 ] = m[ 2 ];
  4716. r[ 7 ] = m[ 5 ];
  4717. r[ 8 ] = m[ 8 ];
  4718. return this;
  4719. }
  4720. /**
  4721. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4722. *
  4723. * @param {number} tx - Offset x.
  4724. * @param {number} ty - Offset y.
  4725. * @param {number} sx - Repeat x.
  4726. * @param {number} sy - Repeat y.
  4727. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4728. * @param {number} cx - Center x of rotation.
  4729. * @param {number} cy - Center y of rotation
  4730. * @return {Matrix3} A reference to this matrix.
  4731. */
  4732. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4733. const c = Math.cos( rotation );
  4734. const s = Math.sin( rotation );
  4735. this.set(
  4736. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4737. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4738. 0, 0, 1
  4739. );
  4740. return this;
  4741. }
  4742. /**
  4743. * Scales this matrix with the given scalar values.
  4744. *
  4745. * @param {number} sx - The amount to scale in the X axis.
  4746. * @param {number} sy - The amount to scale in the Y axis.
  4747. * @return {Matrix3} A reference to this matrix.
  4748. */
  4749. scale( sx, sy ) {
  4750. this.premultiply( _m3.makeScale( sx, sy ) );
  4751. return this;
  4752. }
  4753. /**
  4754. * Rotates this matrix by the given angle.
  4755. *
  4756. * @param {number} theta - The rotation in radians.
  4757. * @return {Matrix3} A reference to this matrix.
  4758. */
  4759. rotate( theta ) {
  4760. this.premultiply( _m3.makeRotation( - theta ) );
  4761. return this;
  4762. }
  4763. /**
  4764. * Translates this matrix by the given scalar values.
  4765. *
  4766. * @param {number} tx - The amount to translate in the X axis.
  4767. * @param {number} ty - The amount to translate in the Y axis.
  4768. * @return {Matrix3} A reference to this matrix.
  4769. */
  4770. translate( tx, ty ) {
  4771. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4772. return this;
  4773. }
  4774. // for 2D Transforms
  4775. /**
  4776. * Sets this matrix as a 2D translation transform.
  4777. *
  4778. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4779. * @param {number} y - The amount to translate in the Y axis.
  4780. * @return {Matrix3} A reference to this matrix.
  4781. */
  4782. makeTranslation( x, y ) {
  4783. if ( x.isVector2 ) {
  4784. this.set(
  4785. 1, 0, x.x,
  4786. 0, 1, x.y,
  4787. 0, 0, 1
  4788. );
  4789. } else {
  4790. this.set(
  4791. 1, 0, x,
  4792. 0, 1, y,
  4793. 0, 0, 1
  4794. );
  4795. }
  4796. return this;
  4797. }
  4798. /**
  4799. * Sets this matrix as a 2D rotational transformation.
  4800. *
  4801. * @param {number} theta - The rotation in radians.
  4802. * @return {Matrix3} A reference to this matrix.
  4803. */
  4804. makeRotation( theta ) {
  4805. // counterclockwise
  4806. const c = Math.cos( theta );
  4807. const s = Math.sin( theta );
  4808. this.set(
  4809. c, - s, 0,
  4810. s, c, 0,
  4811. 0, 0, 1
  4812. );
  4813. return this;
  4814. }
  4815. /**
  4816. * Sets this matrix as a 2D scale transform.
  4817. *
  4818. * @param {number} x - The amount to scale in the X axis.
  4819. * @param {number} y - The amount to scale in the Y axis.
  4820. * @return {Matrix3} A reference to this matrix.
  4821. */
  4822. makeScale( x, y ) {
  4823. this.set(
  4824. x, 0, 0,
  4825. 0, y, 0,
  4826. 0, 0, 1
  4827. );
  4828. return this;
  4829. }
  4830. /**
  4831. * Returns `true` if this matrix is equal with the given one.
  4832. *
  4833. * @param {Matrix3} matrix - The matrix to test for equality.
  4834. * @return {boolean} Whether this matrix is equal with the given one.
  4835. */
  4836. equals( matrix ) {
  4837. const te = this.elements;
  4838. const me = matrix.elements;
  4839. for ( let i = 0; i < 9; i ++ ) {
  4840. if ( te[ i ] !== me[ i ] ) return false;
  4841. }
  4842. return true;
  4843. }
  4844. /**
  4845. * Sets the elements of the matrix from the given array.
  4846. *
  4847. * @param {Array<number>} array - The matrix elements in column-major order.
  4848. * @param {number} [offset=0] - Index of the first element in the array.
  4849. * @return {Matrix3} A reference to this matrix.
  4850. */
  4851. fromArray( array, offset = 0 ) {
  4852. for ( let i = 0; i < 9; i ++ ) {
  4853. this.elements[ i ] = array[ i + offset ];
  4854. }
  4855. return this;
  4856. }
  4857. /**
  4858. * Writes the elements of this matrix to the given array. If no array is provided,
  4859. * the method returns a new instance.
  4860. *
  4861. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  4862. * @param {number} [offset=0] - Index of the first element in the array.
  4863. * @return {Array<number>} The matrix elements in column-major order.
  4864. */
  4865. toArray( array = [], offset = 0 ) {
  4866. const te = this.elements;
  4867. array[ offset ] = te[ 0 ];
  4868. array[ offset + 1 ] = te[ 1 ];
  4869. array[ offset + 2 ] = te[ 2 ];
  4870. array[ offset + 3 ] = te[ 3 ];
  4871. array[ offset + 4 ] = te[ 4 ];
  4872. array[ offset + 5 ] = te[ 5 ];
  4873. array[ offset + 6 ] = te[ 6 ];
  4874. array[ offset + 7 ] = te[ 7 ];
  4875. array[ offset + 8 ] = te[ 8 ];
  4876. return array;
  4877. }
  4878. /**
  4879. * Returns a matrix with copied values from this instance.
  4880. *
  4881. * @return {Matrix3} A clone of this instance.
  4882. */
  4883. clone() {
  4884. return new this.constructor().fromArray( this.elements );
  4885. }
  4886. }
  4887. const _m3 = /*@__PURE__*/ new Matrix3();
  4888. function arrayNeedsUint32( array ) {
  4889. // assumes larger values usually on last
  4890. for ( let i = array.length - 1; i >= 0; -- i ) {
  4891. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  4892. }
  4893. return false;
  4894. }
  4895. const TYPED_ARRAYS = {
  4896. Int8Array: Int8Array,
  4897. Uint8Array: Uint8Array,
  4898. Uint8ClampedArray: Uint8ClampedArray,
  4899. Int16Array: Int16Array,
  4900. Uint16Array: Uint16Array,
  4901. Int32Array: Int32Array,
  4902. Uint32Array: Uint32Array,
  4903. Float32Array: Float32Array,
  4904. Float64Array: Float64Array
  4905. };
  4906. function getTypedArray( type, buffer ) {
  4907. return new TYPED_ARRAYS[ type ]( buffer );
  4908. }
  4909. function createElementNS( name ) {
  4910. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  4911. }
  4912. function createCanvasElement() {
  4913. const canvas = createElementNS( 'canvas' );
  4914. canvas.style.display = 'block';
  4915. return canvas;
  4916. }
  4917. const _cache = {};
  4918. function warnOnce( message ) {
  4919. if ( message in _cache ) return;
  4920. _cache[ message ] = true;
  4921. console.warn( message );
  4922. }
  4923. function probeAsync( gl, sync, interval ) {
  4924. return new Promise( function ( resolve, reject ) {
  4925. function probe() {
  4926. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  4927. case gl.WAIT_FAILED:
  4928. reject();
  4929. break;
  4930. case gl.TIMEOUT_EXPIRED:
  4931. setTimeout( probe, interval );
  4932. break;
  4933. default:
  4934. resolve();
  4935. }
  4936. }
  4937. setTimeout( probe, interval );
  4938. } );
  4939. }
  4940. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  4941. 0.4123908, 0.3575843, 0.1804808,
  4942. 0.2126390, 0.7151687, 0.0721923,
  4943. 0.0193308, 0.1191948, 0.9505322
  4944. );
  4945. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  4946. 3.2409699, -1.5373832, -0.4986108,
  4947. -0.9692436, 1.8759675, 0.0415551,
  4948. 0.0556301, -0.203977, 1.0569715
  4949. );
  4950. function createColorManagement() {
  4951. const ColorManagement = {
  4952. enabled: true,
  4953. workingColorSpace: LinearSRGBColorSpace,
  4954. /**
  4955. * Implementations of supported color spaces.
  4956. *
  4957. * Required:
  4958. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  4959. * - whitePoint: reference white [ x y ]
  4960. * - transfer: transfer function (pre-defined)
  4961. * - toXYZ: Matrix3 RGB to XYZ transform
  4962. * - fromXYZ: Matrix3 XYZ to RGB transform
  4963. * - luminanceCoefficients: RGB luminance coefficients
  4964. *
  4965. * Optional:
  4966. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  4967. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  4968. *
  4969. * Reference:
  4970. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  4971. */
  4972. spaces: {},
  4973. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  4974. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  4975. return color;
  4976. }
  4977. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  4978. color.r = SRGBToLinear( color.r );
  4979. color.g = SRGBToLinear( color.g );
  4980. color.b = SRGBToLinear( color.b );
  4981. }
  4982. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  4983. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  4984. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  4985. }
  4986. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  4987. color.r = LinearToSRGB( color.r );
  4988. color.g = LinearToSRGB( color.g );
  4989. color.b = LinearToSRGB( color.b );
  4990. }
  4991. return color;
  4992. },
  4993. workingToColorSpace: function ( color, targetColorSpace ) {
  4994. return this.convert( color, this.workingColorSpace, targetColorSpace );
  4995. },
  4996. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  4997. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  4998. },
  4999. getPrimaries: function ( colorSpace ) {
  5000. return this.spaces[ colorSpace ].primaries;
  5001. },
  5002. getTransfer: function ( colorSpace ) {
  5003. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5004. return this.spaces[ colorSpace ].transfer;
  5005. },
  5006. getToneMappingMode: function ( colorSpace ) {
  5007. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5008. },
  5009. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5010. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5011. },
  5012. define: function ( colorSpaces ) {
  5013. Object.assign( this.spaces, colorSpaces );
  5014. },
  5015. // Internal APIs
  5016. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5017. return targetMatrix
  5018. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5019. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5020. },
  5021. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5022. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5023. },
  5024. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5025. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5026. },
  5027. // Deprecated
  5028. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5029. warnOnce( 'THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5030. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5031. },
  5032. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5033. warnOnce( 'THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5034. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5035. },
  5036. };
  5037. /******************************************************************************
  5038. * sRGB definitions
  5039. */
  5040. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5041. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5042. const D65 = [ 0.3127, 0.3290 ];
  5043. ColorManagement.define( {
  5044. [ LinearSRGBColorSpace ]: {
  5045. primaries: REC709_PRIMARIES,
  5046. whitePoint: D65,
  5047. transfer: LinearTransfer,
  5048. toXYZ: LINEAR_REC709_TO_XYZ,
  5049. fromXYZ: XYZ_TO_LINEAR_REC709,
  5050. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5051. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5052. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5053. },
  5054. [ SRGBColorSpace ]: {
  5055. primaries: REC709_PRIMARIES,
  5056. whitePoint: D65,
  5057. transfer: SRGBTransfer,
  5058. toXYZ: LINEAR_REC709_TO_XYZ,
  5059. fromXYZ: XYZ_TO_LINEAR_REC709,
  5060. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5061. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5062. },
  5063. } );
  5064. return ColorManagement;
  5065. }
  5066. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5067. function SRGBToLinear( c ) {
  5068. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5069. }
  5070. function LinearToSRGB( c ) {
  5071. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5072. }
  5073. let _canvas;
  5074. /**
  5075. * A class containing utility functions for images.
  5076. *
  5077. * @hideconstructor
  5078. */
  5079. class ImageUtils {
  5080. /**
  5081. * Returns a data URI containing a representation of the given image.
  5082. *
  5083. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5084. * @param {string} [type='image/png'] - Indicates the image format.
  5085. * @return {string} The data URI.
  5086. */
  5087. static getDataURL( image, type = 'image/png' ) {
  5088. if ( /^data:/i.test( image.src ) ) {
  5089. return image.src;
  5090. }
  5091. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5092. return image.src;
  5093. }
  5094. let canvas;
  5095. if ( image instanceof HTMLCanvasElement ) {
  5096. canvas = image;
  5097. } else {
  5098. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5099. _canvas.width = image.width;
  5100. _canvas.height = image.height;
  5101. const context = _canvas.getContext( '2d' );
  5102. if ( image instanceof ImageData ) {
  5103. context.putImageData( image, 0, 0 );
  5104. } else {
  5105. context.drawImage( image, 0, 0, image.width, image.height );
  5106. }
  5107. canvas = _canvas;
  5108. }
  5109. return canvas.toDataURL( type );
  5110. }
  5111. /**
  5112. * Converts the given sRGB image data to linear color space.
  5113. *
  5114. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5115. * @return {HTMLCanvasElement|Object} The converted image.
  5116. */
  5117. static sRGBToLinear( image ) {
  5118. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5119. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5120. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5121. const canvas = createElementNS( 'canvas' );
  5122. canvas.width = image.width;
  5123. canvas.height = image.height;
  5124. const context = canvas.getContext( '2d' );
  5125. context.drawImage( image, 0, 0, image.width, image.height );
  5126. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5127. const data = imageData.data;
  5128. for ( let i = 0; i < data.length; i ++ ) {
  5129. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5130. }
  5131. context.putImageData( imageData, 0, 0 );
  5132. return canvas;
  5133. } else if ( image.data ) {
  5134. const data = image.data.slice( 0 );
  5135. for ( let i = 0; i < data.length; i ++ ) {
  5136. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5137. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5138. } else {
  5139. // assuming float
  5140. data[ i ] = SRGBToLinear( data[ i ] );
  5141. }
  5142. }
  5143. return {
  5144. data: data,
  5145. width: image.width,
  5146. height: image.height
  5147. };
  5148. } else {
  5149. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5150. return image;
  5151. }
  5152. }
  5153. }
  5154. let _sourceId = 0;
  5155. /**
  5156. * Represents the data source of a texture.
  5157. *
  5158. * The main purpose of this class is to decouple the data definition from the texture
  5159. * definition so the same data can be used with multiple texture instances.
  5160. */
  5161. class Source {
  5162. /**
  5163. * Constructs a new video texture.
  5164. *
  5165. * @param {any} [data=null] - The data definition of a texture.
  5166. */
  5167. constructor( data = null ) {
  5168. /**
  5169. * This flag can be used for type testing.
  5170. *
  5171. * @type {boolean}
  5172. * @readonly
  5173. * @default true
  5174. */
  5175. this.isSource = true;
  5176. /**
  5177. * The ID of the source.
  5178. *
  5179. * @name Source#id
  5180. * @type {number}
  5181. * @readonly
  5182. */
  5183. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5184. /**
  5185. * The UUID of the source.
  5186. *
  5187. * @type {string}
  5188. * @readonly
  5189. */
  5190. this.uuid = generateUUID();
  5191. /**
  5192. * The data definition of a texture.
  5193. *
  5194. * @type {any}
  5195. */
  5196. this.data = data;
  5197. /**
  5198. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5199. * provides more control on how texture data should be processed. When `dataReady` is set
  5200. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5201. * the data into the GPU memory.
  5202. *
  5203. * @type {boolean}
  5204. * @default true
  5205. */
  5206. this.dataReady = true;
  5207. /**
  5208. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5209. *
  5210. * @type {number}
  5211. * @readonly
  5212. * @default 0
  5213. */
  5214. this.version = 0;
  5215. }
  5216. /**
  5217. * Returns the dimensions of the source into the given target vector.
  5218. *
  5219. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5220. * @return {(Vector2|Vector3)} The dimensions of the source.
  5221. */
  5222. getSize( target ) {
  5223. const data = this.data;
  5224. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5225. target.set( data.videoWidth, data.videoHeight, 0 );
  5226. } else if ( data instanceof VideoFrame ) {
  5227. target.set( data.displayHeight, data.displayWidth, 0 );
  5228. } else if ( data !== null ) {
  5229. target.set( data.width, data.height, data.depth || 0 );
  5230. } else {
  5231. target.set( 0, 0, 0 );
  5232. }
  5233. return target;
  5234. }
  5235. /**
  5236. * When the property is set to `true`, the engine allocates the memory
  5237. * for the texture (if necessary) and triggers the actual texture upload
  5238. * to the GPU next time the source is used.
  5239. *
  5240. * @type {boolean}
  5241. * @default false
  5242. * @param {boolean} value
  5243. */
  5244. set needsUpdate( value ) {
  5245. if ( value === true ) this.version ++;
  5246. }
  5247. /**
  5248. * Serializes the source into JSON.
  5249. *
  5250. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5251. * @return {Object} A JSON object representing the serialized source.
  5252. * @see {@link ObjectLoader#parse}
  5253. */
  5254. toJSON( meta ) {
  5255. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5256. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5257. return meta.images[ this.uuid ];
  5258. }
  5259. const output = {
  5260. uuid: this.uuid,
  5261. url: ''
  5262. };
  5263. const data = this.data;
  5264. if ( data !== null ) {
  5265. let url;
  5266. if ( Array.isArray( data ) ) {
  5267. // cube texture
  5268. url = [];
  5269. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5270. if ( data[ i ].isDataTexture ) {
  5271. url.push( serializeImage( data[ i ].image ) );
  5272. } else {
  5273. url.push( serializeImage( data[ i ] ) );
  5274. }
  5275. }
  5276. } else {
  5277. // texture
  5278. url = serializeImage( data );
  5279. }
  5280. output.url = url;
  5281. }
  5282. if ( ! isRootObject ) {
  5283. meta.images[ this.uuid ] = output;
  5284. }
  5285. return output;
  5286. }
  5287. }
  5288. function serializeImage( image ) {
  5289. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5290. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5291. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5292. // default images
  5293. return ImageUtils.getDataURL( image );
  5294. } else {
  5295. if ( image.data ) {
  5296. // images of DataTexture
  5297. return {
  5298. data: Array.from( image.data ),
  5299. width: image.width,
  5300. height: image.height,
  5301. type: image.data.constructor.name
  5302. };
  5303. } else {
  5304. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  5305. return {};
  5306. }
  5307. }
  5308. }
  5309. let _textureId = 0;
  5310. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5311. /**
  5312. * Base class for all textures.
  5313. *
  5314. * Note: After the initial use of a texture, its dimensions, format, and type
  5315. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5316. *
  5317. * @augments EventDispatcher
  5318. */
  5319. class Texture extends EventDispatcher {
  5320. /**
  5321. * Constructs a new texture.
  5322. *
  5323. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5324. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5325. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5326. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5327. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5328. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5329. * @param {number} [format=RGBAFormat] - The texture format.
  5330. * @param {number} [type=UnsignedByteType] - The texture type.
  5331. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5332. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5333. */
  5334. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {
  5335. super();
  5336. /**
  5337. * This flag can be used for type testing.
  5338. *
  5339. * @type {boolean}
  5340. * @readonly
  5341. * @default true
  5342. */
  5343. this.isTexture = true;
  5344. /**
  5345. * The ID of the texture.
  5346. *
  5347. * @name Texture#id
  5348. * @type {number}
  5349. * @readonly
  5350. */
  5351. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5352. /**
  5353. * The UUID of the material.
  5354. *
  5355. * @type {string}
  5356. * @readonly
  5357. */
  5358. this.uuid = generateUUID();
  5359. /**
  5360. * The name of the material.
  5361. *
  5362. * @type {string}
  5363. */
  5364. this.name = '';
  5365. /**
  5366. * The data definition of a texture. A reference to the data source can be
  5367. * shared across textures. This is often useful in context of spritesheets
  5368. * where multiple textures render the same data but with different texture
  5369. * transformations.
  5370. *
  5371. * @type {Source}
  5372. */
  5373. this.source = new Source( image );
  5374. /**
  5375. * An array holding user-defined mipmaps.
  5376. *
  5377. * @type {Array<Object>}
  5378. */
  5379. this.mipmaps = [];
  5380. /**
  5381. * How the texture is applied to the object. The value `UVMapping`
  5382. * is the default, where texture or uv coordinates are used to apply the map.
  5383. *
  5384. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5385. * @default UVMapping
  5386. */
  5387. this.mapping = mapping;
  5388. /**
  5389. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5390. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5391. *
  5392. * @type {number}
  5393. * @default 0
  5394. */
  5395. this.channel = 0;
  5396. /**
  5397. * This defines how the texture is wrapped horizontally and corresponds to
  5398. * *U* in UV mapping.
  5399. *
  5400. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5401. * @default ClampToEdgeWrapping
  5402. */
  5403. this.wrapS = wrapS;
  5404. /**
  5405. * This defines how the texture is wrapped horizontally and corresponds to
  5406. * *V* in UV mapping.
  5407. *
  5408. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5409. * @default ClampToEdgeWrapping
  5410. */
  5411. this.wrapT = wrapT;
  5412. /**
  5413. * How the texture is sampled when a texel covers more than one pixel.
  5414. *
  5415. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5416. * @default LinearFilter
  5417. */
  5418. this.magFilter = magFilter;
  5419. /**
  5420. * How the texture is sampled when a texel covers less than one pixel.
  5421. *
  5422. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5423. * @default LinearMipmapLinearFilter
  5424. */
  5425. this.minFilter = minFilter;
  5426. /**
  5427. * The number of samples taken along the axis through the pixel that has the
  5428. * highest density of texels. By default, this value is `1`. A higher value
  5429. * gives a less blurry result than a basic mipmap, at the cost of more
  5430. * texture samples being used.
  5431. *
  5432. * @type {number}
  5433. * @default 0
  5434. */
  5435. this.anisotropy = anisotropy;
  5436. /**
  5437. * The format of the texture.
  5438. *
  5439. * @type {number}
  5440. * @default RGBAFormat
  5441. */
  5442. this.format = format;
  5443. /**
  5444. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5445. * defines how the texture data is going to be stored on the GPU.
  5446. *
  5447. * This property allows to overwrite the default format.
  5448. *
  5449. * @type {?string}
  5450. * @default null
  5451. */
  5452. this.internalFormat = null;
  5453. /**
  5454. * The data type of the texture.
  5455. *
  5456. * @type {number}
  5457. * @default UnsignedByteType
  5458. */
  5459. this.type = type;
  5460. /**
  5461. * How much a single repetition of the texture is offset from the beginning,
  5462. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5463. *
  5464. * @type {Vector2}
  5465. * @default (0,0)
  5466. */
  5467. this.offset = new Vector2( 0, 0 );
  5468. /**
  5469. * How many times the texture is repeated across the surface, in each
  5470. * direction U and V. If repeat is set greater than `1` in either direction,
  5471. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5472. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5473. *
  5474. * @type {Vector2}
  5475. * @default (1,1)
  5476. */
  5477. this.repeat = new Vector2( 1, 1 );
  5478. /**
  5479. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5480. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5481. *
  5482. * @type {Vector2}
  5483. * @default (0,0)
  5484. */
  5485. this.center = new Vector2( 0, 0 );
  5486. /**
  5487. * How much the texture is rotated around the center point, in radians.
  5488. * Positive values are counter-clockwise.
  5489. *
  5490. * @type {number}
  5491. * @default 0
  5492. */
  5493. this.rotation = 0;
  5494. /**
  5495. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5496. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5497. * {@link Texture#rotation}, and {@link Texture#center}.
  5498. *
  5499. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5500. *
  5501. * @type {boolean}
  5502. * @default true
  5503. */
  5504. this.matrixAutoUpdate = true;
  5505. /**
  5506. * The uv-transformation matrix of the texture.
  5507. *
  5508. * @type {Matrix3}
  5509. */
  5510. this.matrix = new Matrix3();
  5511. /**
  5512. * Whether to generate mipmaps (if possible) for a texture.
  5513. *
  5514. * Set this to `false` if you are creating mipmaps manually.
  5515. *
  5516. * @type {boolean}
  5517. * @default true
  5518. */
  5519. this.generateMipmaps = true;
  5520. /**
  5521. * If set to `true`, the alpha channel, if present, is multiplied into the
  5522. * color channels when the texture is uploaded to the GPU.
  5523. *
  5524. * Note that this property has no effect when using `ImageBitmap`. You need to
  5525. * configure premultiply alpha on bitmap creation instead.
  5526. *
  5527. * @type {boolean}
  5528. * @default false
  5529. */
  5530. this.premultiplyAlpha = false;
  5531. /**
  5532. * If set to `true`, the texture is flipped along the vertical axis when
  5533. * uploaded to the GPU.
  5534. *
  5535. * Note that this property has no effect when using `ImageBitmap`. You need to
  5536. * configure the flip on bitmap creation instead.
  5537. *
  5538. * @type {boolean}
  5539. * @default true
  5540. */
  5541. this.flipY = true;
  5542. /**
  5543. * Specifies the alignment requirements for the start of each pixel row in memory.
  5544. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5545. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5546. *
  5547. * @type {number}
  5548. * @default 4
  5549. */
  5550. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5551. /**
  5552. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5553. *
  5554. * @type {string}
  5555. * @default NoColorSpace
  5556. */
  5557. this.colorSpace = colorSpace;
  5558. /**
  5559. * An object that can be used to store custom data about the texture. It
  5560. * should not hold references to functions as these will not be cloned.
  5561. *
  5562. * @type {Object}
  5563. */
  5564. this.userData = {};
  5565. /**
  5566. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5567. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5568. *
  5569. * @type {Array<Object>}
  5570. */
  5571. this.updateRanges = [];
  5572. /**
  5573. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5574. *
  5575. * @type {number}
  5576. * @readonly
  5577. * @default 0
  5578. */
  5579. this.version = 0;
  5580. /**
  5581. * A callback function, called when the texture is updated (e.g., when
  5582. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5583. *
  5584. * @type {?Function}
  5585. * @default null
  5586. */
  5587. this.onUpdate = null;
  5588. /**
  5589. * An optional back reference to the textures render target.
  5590. *
  5591. * @type {?(RenderTarget|WebGLRenderTarget)}
  5592. * @default null
  5593. */
  5594. this.renderTarget = null;
  5595. /**
  5596. * Indicates whether a texture belongs to a render target or not.
  5597. *
  5598. * @type {boolean}
  5599. * @readonly
  5600. * @default false
  5601. */
  5602. this.isRenderTargetTexture = false;
  5603. /**
  5604. * Indicates if a texture should be handled like a texture array.
  5605. *
  5606. * @type {boolean}
  5607. * @readonly
  5608. * @default false
  5609. */
  5610. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5611. /**
  5612. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5613. * (only relevant for render target textures).
  5614. *
  5615. * @type {number}
  5616. * @readonly
  5617. * @default 0
  5618. */
  5619. this.pmremVersion = 0;
  5620. }
  5621. /**
  5622. * The width of the texture in pixels.
  5623. */
  5624. get width() {
  5625. return this.source.getSize( _tempVec3 ).x;
  5626. }
  5627. /**
  5628. * The height of the texture in pixels.
  5629. */
  5630. get height() {
  5631. return this.source.getSize( _tempVec3 ).y;
  5632. }
  5633. /**
  5634. * The depth of the texture in pixels.
  5635. */
  5636. get depth() {
  5637. return this.source.getSize( _tempVec3 ).z;
  5638. }
  5639. /**
  5640. * The image object holding the texture data.
  5641. *
  5642. * @type {?Object}
  5643. */
  5644. get image() {
  5645. return this.source.data;
  5646. }
  5647. set image( value = null ) {
  5648. this.source.data = value;
  5649. }
  5650. /**
  5651. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5652. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5653. */
  5654. updateMatrix() {
  5655. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5656. }
  5657. /**
  5658. * Adds a range of data in the data texture to be updated on the GPU.
  5659. *
  5660. * @param {number} start - Position at which to start update.
  5661. * @param {number} count - The number of components to update.
  5662. */
  5663. addUpdateRange( start, count ) {
  5664. this.updateRanges.push( { start, count } );
  5665. }
  5666. /**
  5667. * Clears the update ranges.
  5668. */
  5669. clearUpdateRanges() {
  5670. this.updateRanges.length = 0;
  5671. }
  5672. /**
  5673. * Returns a new texture with copied values from this instance.
  5674. *
  5675. * @return {Texture} A clone of this instance.
  5676. */
  5677. clone() {
  5678. return new this.constructor().copy( this );
  5679. }
  5680. /**
  5681. * Copies the values of the given texture to this instance.
  5682. *
  5683. * @param {Texture} source - The texture to copy.
  5684. * @return {Texture} A reference to this instance.
  5685. */
  5686. copy( source ) {
  5687. this.name = source.name;
  5688. this.source = source.source;
  5689. this.mipmaps = source.mipmaps.slice( 0 );
  5690. this.mapping = source.mapping;
  5691. this.channel = source.channel;
  5692. this.wrapS = source.wrapS;
  5693. this.wrapT = source.wrapT;
  5694. this.magFilter = source.magFilter;
  5695. this.minFilter = source.minFilter;
  5696. this.anisotropy = source.anisotropy;
  5697. this.format = source.format;
  5698. this.internalFormat = source.internalFormat;
  5699. this.type = source.type;
  5700. this.offset.copy( source.offset );
  5701. this.repeat.copy( source.repeat );
  5702. this.center.copy( source.center );
  5703. this.rotation = source.rotation;
  5704. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5705. this.matrix.copy( source.matrix );
  5706. this.generateMipmaps = source.generateMipmaps;
  5707. this.premultiplyAlpha = source.premultiplyAlpha;
  5708. this.flipY = source.flipY;
  5709. this.unpackAlignment = source.unpackAlignment;
  5710. this.colorSpace = source.colorSpace;
  5711. this.renderTarget = source.renderTarget;
  5712. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5713. this.isArrayTexture = source.isArrayTexture;
  5714. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5715. this.needsUpdate = true;
  5716. return this;
  5717. }
  5718. /**
  5719. * Sets this texture's properties based on `values`.
  5720. * @param {Object} values - A container with texture parameters.
  5721. */
  5722. setValues( values ) {
  5723. for ( const key in values ) {
  5724. const newValue = values[ key ];
  5725. if ( newValue === undefined ) {
  5726. console.warn( `THREE.Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5727. continue;
  5728. }
  5729. const currentValue = this[ key ];
  5730. if ( currentValue === undefined ) {
  5731. console.warn( `THREE.Texture.setValues(): property '${ key }' does not exist.` );
  5732. continue;
  5733. }
  5734. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5735. currentValue.copy( newValue );
  5736. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5737. currentValue.copy( newValue );
  5738. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5739. currentValue.copy( newValue );
  5740. } else {
  5741. this[ key ] = newValue;
  5742. }
  5743. }
  5744. }
  5745. /**
  5746. * Serializes the texture into JSON.
  5747. *
  5748. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5749. * @return {Object} A JSON object representing the serialized texture.
  5750. * @see {@link ObjectLoader#parse}
  5751. */
  5752. toJSON( meta ) {
  5753. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5754. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5755. return meta.textures[ this.uuid ];
  5756. }
  5757. const output = {
  5758. metadata: {
  5759. version: 4.7,
  5760. type: 'Texture',
  5761. generator: 'Texture.toJSON'
  5762. },
  5763. uuid: this.uuid,
  5764. name: this.name,
  5765. image: this.source.toJSON( meta ).uuid,
  5766. mapping: this.mapping,
  5767. channel: this.channel,
  5768. repeat: [ this.repeat.x, this.repeat.y ],
  5769. offset: [ this.offset.x, this.offset.y ],
  5770. center: [ this.center.x, this.center.y ],
  5771. rotation: this.rotation,
  5772. wrap: [ this.wrapS, this.wrapT ],
  5773. format: this.format,
  5774. internalFormat: this.internalFormat,
  5775. type: this.type,
  5776. colorSpace: this.colorSpace,
  5777. minFilter: this.minFilter,
  5778. magFilter: this.magFilter,
  5779. anisotropy: this.anisotropy,
  5780. flipY: this.flipY,
  5781. generateMipmaps: this.generateMipmaps,
  5782. premultiplyAlpha: this.premultiplyAlpha,
  5783. unpackAlignment: this.unpackAlignment
  5784. };
  5785. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5786. if ( ! isRootObject ) {
  5787. meta.textures[ this.uuid ] = output;
  5788. }
  5789. return output;
  5790. }
  5791. /**
  5792. * Frees the GPU-related resources allocated by this instance. Call this
  5793. * method whenever this instance is no longer used in your app.
  5794. *
  5795. * @fires Texture#dispose
  5796. */
  5797. dispose() {
  5798. /**
  5799. * Fires when the texture has been disposed of.
  5800. *
  5801. * @event Texture#dispose
  5802. * @type {Object}
  5803. */
  5804. this.dispatchEvent( { type: 'dispose' } );
  5805. }
  5806. /**
  5807. * Transforms the given uv vector with the textures uv transformation matrix.
  5808. *
  5809. * @param {Vector2} uv - The uv vector.
  5810. * @return {Vector2} The transformed uv vector.
  5811. */
  5812. transformUv( uv ) {
  5813. if ( this.mapping !== UVMapping ) return uv;
  5814. uv.applyMatrix3( this.matrix );
  5815. if ( uv.x < 0 || uv.x > 1 ) {
  5816. switch ( this.wrapS ) {
  5817. case RepeatWrapping:
  5818. uv.x = uv.x - Math.floor( uv.x );
  5819. break;
  5820. case ClampToEdgeWrapping:
  5821. uv.x = uv.x < 0 ? 0 : 1;
  5822. break;
  5823. case MirroredRepeatWrapping:
  5824. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5825. uv.x = Math.ceil( uv.x ) - uv.x;
  5826. } else {
  5827. uv.x = uv.x - Math.floor( uv.x );
  5828. }
  5829. break;
  5830. }
  5831. }
  5832. if ( uv.y < 0 || uv.y > 1 ) {
  5833. switch ( this.wrapT ) {
  5834. case RepeatWrapping:
  5835. uv.y = uv.y - Math.floor( uv.y );
  5836. break;
  5837. case ClampToEdgeWrapping:
  5838. uv.y = uv.y < 0 ? 0 : 1;
  5839. break;
  5840. case MirroredRepeatWrapping:
  5841. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5842. uv.y = Math.ceil( uv.y ) - uv.y;
  5843. } else {
  5844. uv.y = uv.y - Math.floor( uv.y );
  5845. }
  5846. break;
  5847. }
  5848. }
  5849. if ( this.flipY ) {
  5850. uv.y = 1 - uv.y;
  5851. }
  5852. return uv;
  5853. }
  5854. /**
  5855. * Setting this property to `true` indicates the engine the texture
  5856. * must be updated in the next render. This triggers a texture upload
  5857. * to the GPU and ensures correct texture parameter configuration.
  5858. *
  5859. * @type {boolean}
  5860. * @default false
  5861. * @param {boolean} value
  5862. */
  5863. set needsUpdate( value ) {
  5864. if ( value === true ) {
  5865. this.version ++;
  5866. this.source.needsUpdate = true;
  5867. }
  5868. }
  5869. /**
  5870. * Setting this property to `true` indicates the engine the PMREM
  5871. * must be regenerated.
  5872. *
  5873. * @type {boolean}
  5874. * @default false
  5875. * @param {boolean} value
  5876. */
  5877. set needsPMREMUpdate( value ) {
  5878. if ( value === true ) {
  5879. this.pmremVersion ++;
  5880. }
  5881. }
  5882. }
  5883. /**
  5884. * The default image for all textures.
  5885. *
  5886. * @static
  5887. * @type {?Image}
  5888. * @default null
  5889. */
  5890. Texture.DEFAULT_IMAGE = null;
  5891. /**
  5892. * The default mapping for all textures.
  5893. *
  5894. * @static
  5895. * @type {number}
  5896. * @default UVMapping
  5897. */
  5898. Texture.DEFAULT_MAPPING = UVMapping;
  5899. /**
  5900. * The default anisotropy value for all textures.
  5901. *
  5902. * @static
  5903. * @type {number}
  5904. * @default 1
  5905. */
  5906. Texture.DEFAULT_ANISOTROPY = 1;
  5907. /**
  5908. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  5909. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  5910. *
  5911. * - A point in 4D space.
  5912. * - A direction and length in 4D space. In three.js the length will
  5913. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  5914. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  5915. * - Any arbitrary ordered quadruplet of numbers.
  5916. *
  5917. * There are other things a 4D vector can be used to represent, however these
  5918. * are the most common uses in *three.js*.
  5919. *
  5920. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  5921. * the corresponding order.
  5922. * ```js
  5923. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  5924. *
  5925. * //no arguments; will be initialised to (0, 0, 0, 1)
  5926. * const b = new THREE.Vector4( );
  5927. *
  5928. * const d = a.dot( b );
  5929. * ```
  5930. */
  5931. class Vector4 {
  5932. /**
  5933. * Constructs a new 4D vector.
  5934. *
  5935. * @param {number} [x=0] - The x value of this vector.
  5936. * @param {number} [y=0] - The y value of this vector.
  5937. * @param {number} [z=0] - The z value of this vector.
  5938. * @param {number} [w=1] - The w value of this vector.
  5939. */
  5940. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  5941. /**
  5942. * This flag can be used for type testing.
  5943. *
  5944. * @type {boolean}
  5945. * @readonly
  5946. * @default true
  5947. */
  5948. Vector4.prototype.isVector4 = true;
  5949. /**
  5950. * The x value of this vector.
  5951. *
  5952. * @type {number}
  5953. */
  5954. this.x = x;
  5955. /**
  5956. * The y value of this vector.
  5957. *
  5958. * @type {number}
  5959. */
  5960. this.y = y;
  5961. /**
  5962. * The z value of this vector.
  5963. *
  5964. * @type {number}
  5965. */
  5966. this.z = z;
  5967. /**
  5968. * The w value of this vector.
  5969. *
  5970. * @type {number}
  5971. */
  5972. this.w = w;
  5973. }
  5974. /**
  5975. * Alias for {@link Vector4#z}.
  5976. *
  5977. * @type {number}
  5978. */
  5979. get width() {
  5980. return this.z;
  5981. }
  5982. set width( value ) {
  5983. this.z = value;
  5984. }
  5985. /**
  5986. * Alias for {@link Vector4#w}.
  5987. *
  5988. * @type {number}
  5989. */
  5990. get height() {
  5991. return this.w;
  5992. }
  5993. set height( value ) {
  5994. this.w = value;
  5995. }
  5996. /**
  5997. * Sets the vector components.
  5998. *
  5999. * @param {number} x - The value of the x component.
  6000. * @param {number} y - The value of the y component.
  6001. * @param {number} z - The value of the z component.
  6002. * @param {number} w - The value of the w component.
  6003. * @return {Vector4} A reference to this vector.
  6004. */
  6005. set( x, y, z, w ) {
  6006. this.x = x;
  6007. this.y = y;
  6008. this.z = z;
  6009. this.w = w;
  6010. return this;
  6011. }
  6012. /**
  6013. * Sets the vector components to the same value.
  6014. *
  6015. * @param {number} scalar - The value to set for all vector components.
  6016. * @return {Vector4} A reference to this vector.
  6017. */
  6018. setScalar( scalar ) {
  6019. this.x = scalar;
  6020. this.y = scalar;
  6021. this.z = scalar;
  6022. this.w = scalar;
  6023. return this;
  6024. }
  6025. /**
  6026. * Sets the vector's x component to the given value
  6027. *
  6028. * @param {number} x - The value to set.
  6029. * @return {Vector4} A reference to this vector.
  6030. */
  6031. setX( x ) {
  6032. this.x = x;
  6033. return this;
  6034. }
  6035. /**
  6036. * Sets the vector's y component to the given value
  6037. *
  6038. * @param {number} y - The value to set.
  6039. * @return {Vector4} A reference to this vector.
  6040. */
  6041. setY( y ) {
  6042. this.y = y;
  6043. return this;
  6044. }
  6045. /**
  6046. * Sets the vector's z component to the given value
  6047. *
  6048. * @param {number} z - The value to set.
  6049. * @return {Vector4} A reference to this vector.
  6050. */
  6051. setZ( z ) {
  6052. this.z = z;
  6053. return this;
  6054. }
  6055. /**
  6056. * Sets the vector's w component to the given value
  6057. *
  6058. * @param {number} w - The value to set.
  6059. * @return {Vector4} A reference to this vector.
  6060. */
  6061. setW( w ) {
  6062. this.w = w;
  6063. return this;
  6064. }
  6065. /**
  6066. * Allows to set a vector component with an index.
  6067. *
  6068. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6069. * `2` equals to z, `3` equals to w.
  6070. * @param {number} value - The value to set.
  6071. * @return {Vector4} A reference to this vector.
  6072. */
  6073. setComponent( index, value ) {
  6074. switch ( index ) {
  6075. case 0: this.x = value; break;
  6076. case 1: this.y = value; break;
  6077. case 2: this.z = value; break;
  6078. case 3: this.w = value; break;
  6079. default: throw new Error( 'index is out of range: ' + index );
  6080. }
  6081. return this;
  6082. }
  6083. /**
  6084. * Returns the value of the vector component which matches the given index.
  6085. *
  6086. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6087. * `2` equals to z, `3` equals to w.
  6088. * @return {number} A vector component value.
  6089. */
  6090. getComponent( index ) {
  6091. switch ( index ) {
  6092. case 0: return this.x;
  6093. case 1: return this.y;
  6094. case 2: return this.z;
  6095. case 3: return this.w;
  6096. default: throw new Error( 'index is out of range: ' + index );
  6097. }
  6098. }
  6099. /**
  6100. * Returns a new vector with copied values from this instance.
  6101. *
  6102. * @return {Vector4} A clone of this instance.
  6103. */
  6104. clone() {
  6105. return new this.constructor( this.x, this.y, this.z, this.w );
  6106. }
  6107. /**
  6108. * Copies the values of the given vector to this instance.
  6109. *
  6110. * @param {Vector3|Vector4} v - The vector to copy.
  6111. * @return {Vector4} A reference to this vector.
  6112. */
  6113. copy( v ) {
  6114. this.x = v.x;
  6115. this.y = v.y;
  6116. this.z = v.z;
  6117. this.w = ( v.w !== undefined ) ? v.w : 1;
  6118. return this;
  6119. }
  6120. /**
  6121. * Adds the given vector to this instance.
  6122. *
  6123. * @param {Vector4} v - The vector to add.
  6124. * @return {Vector4} A reference to this vector.
  6125. */
  6126. add( v ) {
  6127. this.x += v.x;
  6128. this.y += v.y;
  6129. this.z += v.z;
  6130. this.w += v.w;
  6131. return this;
  6132. }
  6133. /**
  6134. * Adds the given scalar value to all components of this instance.
  6135. *
  6136. * @param {number} s - The scalar to add.
  6137. * @return {Vector4} A reference to this vector.
  6138. */
  6139. addScalar( s ) {
  6140. this.x += s;
  6141. this.y += s;
  6142. this.z += s;
  6143. this.w += s;
  6144. return this;
  6145. }
  6146. /**
  6147. * Adds the given vectors and stores the result in this instance.
  6148. *
  6149. * @param {Vector4} a - The first vector.
  6150. * @param {Vector4} b - The second vector.
  6151. * @return {Vector4} A reference to this vector.
  6152. */
  6153. addVectors( a, b ) {
  6154. this.x = a.x + b.x;
  6155. this.y = a.y + b.y;
  6156. this.z = a.z + b.z;
  6157. this.w = a.w + b.w;
  6158. return this;
  6159. }
  6160. /**
  6161. * Adds the given vector scaled by the given factor to this instance.
  6162. *
  6163. * @param {Vector4} v - The vector.
  6164. * @param {number} s - The factor that scales `v`.
  6165. * @return {Vector4} A reference to this vector.
  6166. */
  6167. addScaledVector( v, s ) {
  6168. this.x += v.x * s;
  6169. this.y += v.y * s;
  6170. this.z += v.z * s;
  6171. this.w += v.w * s;
  6172. return this;
  6173. }
  6174. /**
  6175. * Subtracts the given vector from this instance.
  6176. *
  6177. * @param {Vector4} v - The vector to subtract.
  6178. * @return {Vector4} A reference to this vector.
  6179. */
  6180. sub( v ) {
  6181. this.x -= v.x;
  6182. this.y -= v.y;
  6183. this.z -= v.z;
  6184. this.w -= v.w;
  6185. return this;
  6186. }
  6187. /**
  6188. * Subtracts the given scalar value from all components of this instance.
  6189. *
  6190. * @param {number} s - The scalar to subtract.
  6191. * @return {Vector4} A reference to this vector.
  6192. */
  6193. subScalar( s ) {
  6194. this.x -= s;
  6195. this.y -= s;
  6196. this.z -= s;
  6197. this.w -= s;
  6198. return this;
  6199. }
  6200. /**
  6201. * Subtracts the given vectors and stores the result in this instance.
  6202. *
  6203. * @param {Vector4} a - The first vector.
  6204. * @param {Vector4} b - The second vector.
  6205. * @return {Vector4} A reference to this vector.
  6206. */
  6207. subVectors( a, b ) {
  6208. this.x = a.x - b.x;
  6209. this.y = a.y - b.y;
  6210. this.z = a.z - b.z;
  6211. this.w = a.w - b.w;
  6212. return this;
  6213. }
  6214. /**
  6215. * Multiplies the given vector with this instance.
  6216. *
  6217. * @param {Vector4} v - The vector to multiply.
  6218. * @return {Vector4} A reference to this vector.
  6219. */
  6220. multiply( v ) {
  6221. this.x *= v.x;
  6222. this.y *= v.y;
  6223. this.z *= v.z;
  6224. this.w *= v.w;
  6225. return this;
  6226. }
  6227. /**
  6228. * Multiplies the given scalar value with all components of this instance.
  6229. *
  6230. * @param {number} scalar - The scalar to multiply.
  6231. * @return {Vector4} A reference to this vector.
  6232. */
  6233. multiplyScalar( scalar ) {
  6234. this.x *= scalar;
  6235. this.y *= scalar;
  6236. this.z *= scalar;
  6237. this.w *= scalar;
  6238. return this;
  6239. }
  6240. /**
  6241. * Multiplies this vector with the given 4x4 matrix.
  6242. *
  6243. * @param {Matrix4} m - The 4x4 matrix.
  6244. * @return {Vector4} A reference to this vector.
  6245. */
  6246. applyMatrix4( m ) {
  6247. const x = this.x, y = this.y, z = this.z, w = this.w;
  6248. const e = m.elements;
  6249. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6250. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6251. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6252. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6253. return this;
  6254. }
  6255. /**
  6256. * Divides this instance by the given vector.
  6257. *
  6258. * @param {Vector4} v - The vector to divide.
  6259. * @return {Vector4} A reference to this vector.
  6260. */
  6261. divide( v ) {
  6262. this.x /= v.x;
  6263. this.y /= v.y;
  6264. this.z /= v.z;
  6265. this.w /= v.w;
  6266. return this;
  6267. }
  6268. /**
  6269. * Divides this vector by the given scalar.
  6270. *
  6271. * @param {number} scalar - The scalar to divide.
  6272. * @return {Vector4} A reference to this vector.
  6273. */
  6274. divideScalar( scalar ) {
  6275. return this.multiplyScalar( 1 / scalar );
  6276. }
  6277. /**
  6278. * Sets the x, y and z components of this
  6279. * vector to the quaternion's axis and w to the angle.
  6280. *
  6281. * @param {Quaternion} q - The Quaternion to set.
  6282. * @return {Vector4} A reference to this vector.
  6283. */
  6284. setAxisAngleFromQuaternion( q ) {
  6285. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6286. // q is assumed to be normalized
  6287. this.w = 2 * Math.acos( q.w );
  6288. const s = Math.sqrt( 1 - q.w * q.w );
  6289. if ( s < 0.0001 ) {
  6290. this.x = 1;
  6291. this.y = 0;
  6292. this.z = 0;
  6293. } else {
  6294. this.x = q.x / s;
  6295. this.y = q.y / s;
  6296. this.z = q.z / s;
  6297. }
  6298. return this;
  6299. }
  6300. /**
  6301. * Sets the x, y and z components of this
  6302. * vector to the axis of rotation and w to the angle.
  6303. *
  6304. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6305. * @return {Vector4} A reference to this vector.
  6306. */
  6307. setAxisAngleFromRotationMatrix( m ) {
  6308. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6309. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6310. let angle, x, y, z; // variables for result
  6311. const epsilon = 0.01, // margin to allow for rounding errors
  6312. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6313. te = m.elements,
  6314. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6315. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6316. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6317. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6318. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6319. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6320. // singularity found
  6321. // first check for identity matrix which must have +1 for all terms
  6322. // in leading diagonal and zero in other terms
  6323. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6324. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6325. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6326. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6327. // this singularity is identity matrix so angle = 0
  6328. this.set( 1, 0, 0, 0 );
  6329. return this; // zero angle, arbitrary axis
  6330. }
  6331. // otherwise this singularity is angle = 180
  6332. angle = Math.PI;
  6333. const xx = ( m11 + 1 ) / 2;
  6334. const yy = ( m22 + 1 ) / 2;
  6335. const zz = ( m33 + 1 ) / 2;
  6336. const xy = ( m12 + m21 ) / 4;
  6337. const xz = ( m13 + m31 ) / 4;
  6338. const yz = ( m23 + m32 ) / 4;
  6339. if ( ( xx > yy ) && ( xx > zz ) ) {
  6340. // m11 is the largest diagonal term
  6341. if ( xx < epsilon ) {
  6342. x = 0;
  6343. y = 0.707106781;
  6344. z = 0.707106781;
  6345. } else {
  6346. x = Math.sqrt( xx );
  6347. y = xy / x;
  6348. z = xz / x;
  6349. }
  6350. } else if ( yy > zz ) {
  6351. // m22 is the largest diagonal term
  6352. if ( yy < epsilon ) {
  6353. x = 0.707106781;
  6354. y = 0;
  6355. z = 0.707106781;
  6356. } else {
  6357. y = Math.sqrt( yy );
  6358. x = xy / y;
  6359. z = yz / y;
  6360. }
  6361. } else {
  6362. // m33 is the largest diagonal term so base result on this
  6363. if ( zz < epsilon ) {
  6364. x = 0.707106781;
  6365. y = 0.707106781;
  6366. z = 0;
  6367. } else {
  6368. z = Math.sqrt( zz );
  6369. x = xz / z;
  6370. y = yz / z;
  6371. }
  6372. }
  6373. this.set( x, y, z, angle );
  6374. return this; // return 180 deg rotation
  6375. }
  6376. // as we have reached here there are no singularities so we can handle normally
  6377. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6378. ( m13 - m31 ) * ( m13 - m31 ) +
  6379. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6380. if ( Math.abs( s ) < 0.001 ) s = 1;
  6381. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6382. // caught by singularity test above, but I've left it in just in case
  6383. this.x = ( m32 - m23 ) / s;
  6384. this.y = ( m13 - m31 ) / s;
  6385. this.z = ( m21 - m12 ) / s;
  6386. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6387. return this;
  6388. }
  6389. /**
  6390. * Sets the vector components to the position elements of the
  6391. * given transformation matrix.
  6392. *
  6393. * @param {Matrix4} m - The 4x4 matrix.
  6394. * @return {Vector4} A reference to this vector.
  6395. */
  6396. setFromMatrixPosition( m ) {
  6397. const e = m.elements;
  6398. this.x = e[ 12 ];
  6399. this.y = e[ 13 ];
  6400. this.z = e[ 14 ];
  6401. this.w = e[ 15 ];
  6402. return this;
  6403. }
  6404. /**
  6405. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6406. * value, replace that value with the corresponding min value.
  6407. *
  6408. * @param {Vector4} v - The vector.
  6409. * @return {Vector4} A reference to this vector.
  6410. */
  6411. min( v ) {
  6412. this.x = Math.min( this.x, v.x );
  6413. this.y = Math.min( this.y, v.y );
  6414. this.z = Math.min( this.z, v.z );
  6415. this.w = Math.min( this.w, v.w );
  6416. return this;
  6417. }
  6418. /**
  6419. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6420. * value, replace that value with the corresponding max value.
  6421. *
  6422. * @param {Vector4} v - The vector.
  6423. * @return {Vector4} A reference to this vector.
  6424. */
  6425. max( v ) {
  6426. this.x = Math.max( this.x, v.x );
  6427. this.y = Math.max( this.y, v.y );
  6428. this.z = Math.max( this.z, v.z );
  6429. this.w = Math.max( this.w, v.w );
  6430. return this;
  6431. }
  6432. /**
  6433. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6434. * value, it is replaced by the corresponding value.
  6435. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6436. * it is replaced by the corresponding value.
  6437. *
  6438. * @param {Vector4} min - The minimum x, y and z values.
  6439. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6440. * @return {Vector4} A reference to this vector.
  6441. */
  6442. clamp( min, max ) {
  6443. // assumes min < max, componentwise
  6444. this.x = clamp( this.x, min.x, max.x );
  6445. this.y = clamp( this.y, min.y, max.y );
  6446. this.z = clamp( this.z, min.z, max.z );
  6447. this.w = clamp( this.w, min.w, max.w );
  6448. return this;
  6449. }
  6450. /**
  6451. * If this vector's x, y, z or w values are greater than the max value, they are
  6452. * replaced by the max value.
  6453. * If this vector's x, y, z or w values are less than the min value, they are
  6454. * replaced by the min value.
  6455. *
  6456. * @param {number} minVal - The minimum value the components will be clamped to.
  6457. * @param {number} maxVal - The maximum value the components will be clamped to.
  6458. * @return {Vector4} A reference to this vector.
  6459. */
  6460. clampScalar( minVal, maxVal ) {
  6461. this.x = clamp( this.x, minVal, maxVal );
  6462. this.y = clamp( this.y, minVal, maxVal );
  6463. this.z = clamp( this.z, minVal, maxVal );
  6464. this.w = clamp( this.w, minVal, maxVal );
  6465. return this;
  6466. }
  6467. /**
  6468. * If this vector's length is greater than the max value, it is replaced by
  6469. * the max value.
  6470. * If this vector's length is less than the min value, it is replaced by the
  6471. * min value.
  6472. *
  6473. * @param {number} min - The minimum value the vector length will be clamped to.
  6474. * @param {number} max - The maximum value the vector length will be clamped to.
  6475. * @return {Vector4} A reference to this vector.
  6476. */
  6477. clampLength( min, max ) {
  6478. const length = this.length();
  6479. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6480. }
  6481. /**
  6482. * The components of this vector are rounded down to the nearest integer value.
  6483. *
  6484. * @return {Vector4} A reference to this vector.
  6485. */
  6486. floor() {
  6487. this.x = Math.floor( this.x );
  6488. this.y = Math.floor( this.y );
  6489. this.z = Math.floor( this.z );
  6490. this.w = Math.floor( this.w );
  6491. return this;
  6492. }
  6493. /**
  6494. * The components of this vector are rounded up to the nearest integer value.
  6495. *
  6496. * @return {Vector4} A reference to this vector.
  6497. */
  6498. ceil() {
  6499. this.x = Math.ceil( this.x );
  6500. this.y = Math.ceil( this.y );
  6501. this.z = Math.ceil( this.z );
  6502. this.w = Math.ceil( this.w );
  6503. return this;
  6504. }
  6505. /**
  6506. * The components of this vector are rounded to the nearest integer value
  6507. *
  6508. * @return {Vector4} A reference to this vector.
  6509. */
  6510. round() {
  6511. this.x = Math.round( this.x );
  6512. this.y = Math.round( this.y );
  6513. this.z = Math.round( this.z );
  6514. this.w = Math.round( this.w );
  6515. return this;
  6516. }
  6517. /**
  6518. * The components of this vector are rounded towards zero (up if negative,
  6519. * down if positive) to an integer value.
  6520. *
  6521. * @return {Vector4} A reference to this vector.
  6522. */
  6523. roundToZero() {
  6524. this.x = Math.trunc( this.x );
  6525. this.y = Math.trunc( this.y );
  6526. this.z = Math.trunc( this.z );
  6527. this.w = Math.trunc( this.w );
  6528. return this;
  6529. }
  6530. /**
  6531. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6532. *
  6533. * @return {Vector4} A reference to this vector.
  6534. */
  6535. negate() {
  6536. this.x = - this.x;
  6537. this.y = - this.y;
  6538. this.z = - this.z;
  6539. this.w = - this.w;
  6540. return this;
  6541. }
  6542. /**
  6543. * Calculates the dot product of the given vector with this instance.
  6544. *
  6545. * @param {Vector4} v - The vector to compute the dot product with.
  6546. * @return {number} The result of the dot product.
  6547. */
  6548. dot( v ) {
  6549. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6550. }
  6551. /**
  6552. * Computes the square of the Euclidean length (straight-line length) from
  6553. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6554. * compare the length squared instead as it is slightly more efficient to calculate.
  6555. *
  6556. * @return {number} The square length of this vector.
  6557. */
  6558. lengthSq() {
  6559. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6560. }
  6561. /**
  6562. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6563. *
  6564. * @return {number} The length of this vector.
  6565. */
  6566. length() {
  6567. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6568. }
  6569. /**
  6570. * Computes the Manhattan length of this vector.
  6571. *
  6572. * @return {number} The length of this vector.
  6573. */
  6574. manhattanLength() {
  6575. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6576. }
  6577. /**
  6578. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6579. * with the same direction as this one, but with a vector length of `1`.
  6580. *
  6581. * @return {Vector4} A reference to this vector.
  6582. */
  6583. normalize() {
  6584. return this.divideScalar( this.length() || 1 );
  6585. }
  6586. /**
  6587. * Sets this vector to a vector with the same direction as this one, but
  6588. * with the specified length.
  6589. *
  6590. * @param {number} length - The new length of this vector.
  6591. * @return {Vector4} A reference to this vector.
  6592. */
  6593. setLength( length ) {
  6594. return this.normalize().multiplyScalar( length );
  6595. }
  6596. /**
  6597. * Linearly interpolates between the given vector and this instance, where
  6598. * alpha is the percent distance along the line - alpha = 0 will be this
  6599. * vector, and alpha = 1 will be the given one.
  6600. *
  6601. * @param {Vector4} v - The vector to interpolate towards.
  6602. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6603. * @return {Vector4} A reference to this vector.
  6604. */
  6605. lerp( v, alpha ) {
  6606. this.x += ( v.x - this.x ) * alpha;
  6607. this.y += ( v.y - this.y ) * alpha;
  6608. this.z += ( v.z - this.z ) * alpha;
  6609. this.w += ( v.w - this.w ) * alpha;
  6610. return this;
  6611. }
  6612. /**
  6613. * Linearly interpolates between the given vectors, where alpha is the percent
  6614. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6615. * be the second one. The result is stored in this instance.
  6616. *
  6617. * @param {Vector4} v1 - The first vector.
  6618. * @param {Vector4} v2 - The second vector.
  6619. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6620. * @return {Vector4} A reference to this vector.
  6621. */
  6622. lerpVectors( v1, v2, alpha ) {
  6623. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6624. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6625. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6626. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6627. return this;
  6628. }
  6629. /**
  6630. * Returns `true` if this vector is equal with the given one.
  6631. *
  6632. * @param {Vector4} v - The vector to test for equality.
  6633. * @return {boolean} Whether this vector is equal with the given one.
  6634. */
  6635. equals( v ) {
  6636. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6637. }
  6638. /**
  6639. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6640. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6641. *
  6642. * @param {Array<number>} array - An array holding the vector component values.
  6643. * @param {number} [offset=0] - The offset into the array.
  6644. * @return {Vector4} A reference to this vector.
  6645. */
  6646. fromArray( array, offset = 0 ) {
  6647. this.x = array[ offset ];
  6648. this.y = array[ offset + 1 ];
  6649. this.z = array[ offset + 2 ];
  6650. this.w = array[ offset + 3 ];
  6651. return this;
  6652. }
  6653. /**
  6654. * Writes the components of this vector to the given array. If no array is provided,
  6655. * the method returns a new instance.
  6656. *
  6657. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6658. * @param {number} [offset=0] - Index of the first element in the array.
  6659. * @return {Array<number>} The vector components.
  6660. */
  6661. toArray( array = [], offset = 0 ) {
  6662. array[ offset ] = this.x;
  6663. array[ offset + 1 ] = this.y;
  6664. array[ offset + 2 ] = this.z;
  6665. array[ offset + 3 ] = this.w;
  6666. return array;
  6667. }
  6668. /**
  6669. * Sets the components of this vector from the given buffer attribute.
  6670. *
  6671. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6672. * @param {number} index - The index into the attribute.
  6673. * @return {Vector4} A reference to this vector.
  6674. */
  6675. fromBufferAttribute( attribute, index ) {
  6676. this.x = attribute.getX( index );
  6677. this.y = attribute.getY( index );
  6678. this.z = attribute.getZ( index );
  6679. this.w = attribute.getW( index );
  6680. return this;
  6681. }
  6682. /**
  6683. * Sets each component of this vector to a pseudo-random value between `0` and
  6684. * `1`, excluding `1`.
  6685. *
  6686. * @return {Vector4} A reference to this vector.
  6687. */
  6688. random() {
  6689. this.x = Math.random();
  6690. this.y = Math.random();
  6691. this.z = Math.random();
  6692. this.w = Math.random();
  6693. return this;
  6694. }
  6695. *[ Symbol.iterator ]() {
  6696. yield this.x;
  6697. yield this.y;
  6698. yield this.z;
  6699. yield this.w;
  6700. }
  6701. }
  6702. /**
  6703. * A render target is a buffer where the video card draws pixels for a scene
  6704. * that is being rendered in the background. It is used in different effects,
  6705. * such as applying postprocessing to a rendered image before displaying it
  6706. * on the screen.
  6707. *
  6708. * @augments EventDispatcher
  6709. */
  6710. class RenderTarget extends EventDispatcher {
  6711. /**
  6712. * Render target options.
  6713. *
  6714. * @typedef {Object} RenderTarget~Options
  6715. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6716. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6717. * @property {number} [minFilter=LinearFilter] - The min filter.
  6718. * @property {number} [format=RGBAFormat] - The texture format.
  6719. * @property {number} [type=UnsignedByteType] - The texture type.
  6720. * @property {?string} [internalFormat=null] - The texture's internal format.
  6721. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6722. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6723. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6724. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6725. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6726. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6727. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6728. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6729. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6730. * @property {number} [samples=0] - The MSAA samples count.
  6731. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6732. * @property {number} [depth=1] - The texture depth.
  6733. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6734. */
  6735. /**
  6736. * Constructs a new render target.
  6737. *
  6738. * @param {number} [width=1] - The width of the render target.
  6739. * @param {number} [height=1] - The height of the render target.
  6740. * @param {RenderTarget~Options} [options] - The configuration object.
  6741. */
  6742. constructor( width = 1, height = 1, options = {} ) {
  6743. super();
  6744. options = Object.assign( {
  6745. generateMipmaps: false,
  6746. internalFormat: null,
  6747. minFilter: LinearFilter,
  6748. depthBuffer: true,
  6749. stencilBuffer: false,
  6750. resolveDepthBuffer: true,
  6751. resolveStencilBuffer: true,
  6752. depthTexture: null,
  6753. samples: 0,
  6754. count: 1,
  6755. depth: 1,
  6756. multiview: false
  6757. }, options );
  6758. /**
  6759. * This flag can be used for type testing.
  6760. *
  6761. * @type {boolean}
  6762. * @readonly
  6763. * @default true
  6764. */
  6765. this.isRenderTarget = true;
  6766. /**
  6767. * The width of the render target.
  6768. *
  6769. * @type {number}
  6770. * @default 1
  6771. */
  6772. this.width = width;
  6773. /**
  6774. * The height of the render target.
  6775. *
  6776. * @type {number}
  6777. * @default 1
  6778. */
  6779. this.height = height;
  6780. /**
  6781. * The depth of the render target.
  6782. *
  6783. * @type {number}
  6784. * @default 1
  6785. */
  6786. this.depth = options.depth;
  6787. /**
  6788. * A rectangular area inside the render target's viewport. Fragments that are
  6789. * outside the area will be discarded.
  6790. *
  6791. * @type {Vector4}
  6792. * @default (0,0,width,height)
  6793. */
  6794. this.scissor = new Vector4( 0, 0, width, height );
  6795. /**
  6796. * Indicates whether the scissor test should be enabled when rendering into
  6797. * this render target or not.
  6798. *
  6799. * @type {boolean}
  6800. * @default false
  6801. */
  6802. this.scissorTest = false;
  6803. /**
  6804. * A rectangular area representing the render target's viewport.
  6805. *
  6806. * @type {Vector4}
  6807. * @default (0,0,width,height)
  6808. */
  6809. this.viewport = new Vector4( 0, 0, width, height );
  6810. const image = { width: width, height: height, depth: options.depth };
  6811. const texture = new Texture( image );
  6812. /**
  6813. * An array of textures. Each color attachment is represented as a separate texture.
  6814. * Has at least a single entry for the default color attachment.
  6815. *
  6816. * @type {Array<Texture>}
  6817. */
  6818. this.textures = [];
  6819. const count = options.count;
  6820. for ( let i = 0; i < count; i ++ ) {
  6821. this.textures[ i ] = texture.clone();
  6822. this.textures[ i ].isRenderTargetTexture = true;
  6823. this.textures[ i ].renderTarget = this;
  6824. }
  6825. this._setTextureOptions( options );
  6826. /**
  6827. * Whether to allocate a depth buffer or not.
  6828. *
  6829. * @type {boolean}
  6830. * @default true
  6831. */
  6832. this.depthBuffer = options.depthBuffer;
  6833. /**
  6834. * Whether to allocate a stencil buffer or not.
  6835. *
  6836. * @type {boolean}
  6837. * @default false
  6838. */
  6839. this.stencilBuffer = options.stencilBuffer;
  6840. /**
  6841. * Whether to resolve the depth buffer or not.
  6842. *
  6843. * @type {boolean}
  6844. * @default true
  6845. */
  6846. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6847. /**
  6848. * Whether to resolve the stencil buffer or not.
  6849. *
  6850. * @type {boolean}
  6851. * @default true
  6852. */
  6853. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6854. this._depthTexture = null;
  6855. this.depthTexture = options.depthTexture;
  6856. /**
  6857. * The number of MSAA samples.
  6858. *
  6859. * A value of `0` disables MSAA.
  6860. *
  6861. * @type {number}
  6862. * @default 0
  6863. */
  6864. this.samples = options.samples;
  6865. /**
  6866. * Whether to this target is used in multiview rendering.
  6867. *
  6868. * @type {boolean}
  6869. * @default false
  6870. */
  6871. this.multiview = options.multiview;
  6872. }
  6873. _setTextureOptions( options = {} ) {
  6874. const values = {
  6875. minFilter: LinearFilter,
  6876. generateMipmaps: false,
  6877. flipY: false,
  6878. internalFormat: null
  6879. };
  6880. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6881. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6882. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6883. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6884. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6885. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6886. if ( options.format !== undefined ) values.format = options.format;
  6887. if ( options.type !== undefined ) values.type = options.type;
  6888. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6889. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6890. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6891. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6892. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6893. for ( let i = 0; i < this.textures.length; i ++ ) {
  6894. const texture = this.textures[ i ];
  6895. texture.setValues( values );
  6896. }
  6897. }
  6898. /**
  6899. * The texture representing the default color attachment.
  6900. *
  6901. * @type {Texture}
  6902. */
  6903. get texture() {
  6904. return this.textures[ 0 ];
  6905. }
  6906. set texture( value ) {
  6907. this.textures[ 0 ] = value;
  6908. }
  6909. set depthTexture( current ) {
  6910. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  6911. if ( current !== null ) current.renderTarget = this;
  6912. this._depthTexture = current;
  6913. }
  6914. /**
  6915. * Instead of saving the depth in a renderbuffer, a texture
  6916. * can be used instead which is useful for further processing
  6917. * e.g. in context of post-processing.
  6918. *
  6919. * @type {?DepthTexture}
  6920. * @default null
  6921. */
  6922. get depthTexture() {
  6923. return this._depthTexture;
  6924. }
  6925. /**
  6926. * Sets the size of this render target.
  6927. *
  6928. * @param {number} width - The width.
  6929. * @param {number} height - The height.
  6930. * @param {number} [depth=1] - The depth.
  6931. */
  6932. setSize( width, height, depth = 1 ) {
  6933. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  6934. this.width = width;
  6935. this.height = height;
  6936. this.depth = depth;
  6937. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  6938. this.textures[ i ].image.width = width;
  6939. this.textures[ i ].image.height = height;
  6940. this.textures[ i ].image.depth = depth;
  6941. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  6942. }
  6943. this.dispose();
  6944. }
  6945. this.viewport.set( 0, 0, width, height );
  6946. this.scissor.set( 0, 0, width, height );
  6947. }
  6948. /**
  6949. * Returns a new render target with copied values from this instance.
  6950. *
  6951. * @return {RenderTarget} A clone of this instance.
  6952. */
  6953. clone() {
  6954. return new this.constructor().copy( this );
  6955. }
  6956. /**
  6957. * Copies the settings of the given render target. This is a structural copy so
  6958. * no resources are shared between render targets after the copy. That includes
  6959. * all MRT textures and the depth texture.
  6960. *
  6961. * @param {RenderTarget} source - The render target to copy.
  6962. * @return {RenderTarget} A reference to this instance.
  6963. */
  6964. copy( source ) {
  6965. this.width = source.width;
  6966. this.height = source.height;
  6967. this.depth = source.depth;
  6968. this.scissor.copy( source.scissor );
  6969. this.scissorTest = source.scissorTest;
  6970. this.viewport.copy( source.viewport );
  6971. this.textures.length = 0;
  6972. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  6973. this.textures[ i ] = source.textures[ i ].clone();
  6974. this.textures[ i ].isRenderTargetTexture = true;
  6975. this.textures[ i ].renderTarget = this;
  6976. // ensure image object is not shared, see #20328
  6977. const image = Object.assign( {}, source.textures[ i ].image );
  6978. this.textures[ i ].source = new Source( image );
  6979. }
  6980. this.depthBuffer = source.depthBuffer;
  6981. this.stencilBuffer = source.stencilBuffer;
  6982. this.resolveDepthBuffer = source.resolveDepthBuffer;
  6983. this.resolveStencilBuffer = source.resolveStencilBuffer;
  6984. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  6985. this.samples = source.samples;
  6986. return this;
  6987. }
  6988. /**
  6989. * Frees the GPU-related resources allocated by this instance. Call this
  6990. * method whenever this instance is no longer used in your app.
  6991. *
  6992. * @fires RenderTarget#dispose
  6993. */
  6994. dispose() {
  6995. this.dispatchEvent( { type: 'dispose' } );
  6996. }
  6997. }
  6998. /**
  6999. * A render target used in context of {@link WebGLRenderer}.
  7000. *
  7001. * @augments RenderTarget
  7002. */
  7003. class WebGLRenderTarget extends RenderTarget {
  7004. /**
  7005. * Constructs a new 3D render target.
  7006. *
  7007. * @param {number} [width=1] - The width of the render target.
  7008. * @param {number} [height=1] - The height of the render target.
  7009. * @param {RenderTarget~Options} [options] - The configuration object.
  7010. */
  7011. constructor( width = 1, height = 1, options = {} ) {
  7012. super( width, height, options );
  7013. /**
  7014. * This flag can be used for type testing.
  7015. *
  7016. * @type {boolean}
  7017. * @readonly
  7018. * @default true
  7019. */
  7020. this.isWebGLRenderTarget = true;
  7021. }
  7022. }
  7023. /**
  7024. * Creates an array of textures directly from raw buffer data.
  7025. *
  7026. * @augments Texture
  7027. */
  7028. class DataArrayTexture extends Texture {
  7029. /**
  7030. * Constructs a new data array texture.
  7031. *
  7032. * @param {?TypedArray} [data=null] - The buffer data.
  7033. * @param {number} [width=1] - The width of the texture.
  7034. * @param {number} [height=1] - The height of the texture.
  7035. * @param {number} [depth=1] - The depth of the texture.
  7036. */
  7037. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7038. super( null );
  7039. /**
  7040. * This flag can be used for type testing.
  7041. *
  7042. * @type {boolean}
  7043. * @readonly
  7044. * @default true
  7045. */
  7046. this.isDataArrayTexture = true;
  7047. /**
  7048. * The image definition of a data texture.
  7049. *
  7050. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7051. */
  7052. this.image = { data, width, height, depth };
  7053. /**
  7054. * How the texture is sampled when a texel covers more than one pixel.
  7055. *
  7056. * Overwritten and set to `NearestFilter` by default.
  7057. *
  7058. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7059. * @default NearestFilter
  7060. */
  7061. this.magFilter = NearestFilter;
  7062. /**
  7063. * How the texture is sampled when a texel covers less than one pixel.
  7064. *
  7065. * Overwritten and set to `NearestFilter` by default.
  7066. *
  7067. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7068. * @default NearestFilter
  7069. */
  7070. this.minFilter = NearestFilter;
  7071. /**
  7072. * This defines how the texture is wrapped in the depth and corresponds to
  7073. * *W* in UVW mapping.
  7074. *
  7075. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7076. * @default ClampToEdgeWrapping
  7077. */
  7078. this.wrapR = ClampToEdgeWrapping;
  7079. /**
  7080. * Whether to generate mipmaps (if possible) for a texture.
  7081. *
  7082. * Overwritten and set to `false` by default.
  7083. *
  7084. * @type {boolean}
  7085. * @default false
  7086. */
  7087. this.generateMipmaps = false;
  7088. /**
  7089. * If set to `true`, the texture is flipped along the vertical axis when
  7090. * uploaded to the GPU.
  7091. *
  7092. * Overwritten and set to `false` by default.
  7093. *
  7094. * @type {boolean}
  7095. * @default false
  7096. */
  7097. this.flipY = false;
  7098. /**
  7099. * Specifies the alignment requirements for the start of each pixel row in memory.
  7100. *
  7101. * Overwritten and set to `1` by default.
  7102. *
  7103. * @type {boolean}
  7104. * @default 1
  7105. */
  7106. this.unpackAlignment = 1;
  7107. /**
  7108. * A set of all layers which need to be updated in the texture.
  7109. *
  7110. * @type {Set<number>}
  7111. */
  7112. this.layerUpdates = new Set();
  7113. }
  7114. /**
  7115. * Describes that a specific layer of the texture needs to be updated.
  7116. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7117. * entire data texture array is sent to the GPU. Marking specific
  7118. * layers will only transmit subsets of all mipmaps associated with a
  7119. * specific depth in the array which is often much more performant.
  7120. *
  7121. * @param {number} layerIndex - The layer index that should be updated.
  7122. */
  7123. addLayerUpdate( layerIndex ) {
  7124. this.layerUpdates.add( layerIndex );
  7125. }
  7126. /**
  7127. * Resets the layer updates registry.
  7128. */
  7129. clearLayerUpdates() {
  7130. this.layerUpdates.clear();
  7131. }
  7132. }
  7133. /**
  7134. * An array render target used in context of {@link WebGLRenderer}.
  7135. *
  7136. * @augments WebGLRenderTarget
  7137. */
  7138. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7139. /**
  7140. * Constructs a new array render target.
  7141. *
  7142. * @param {number} [width=1] - The width of the render target.
  7143. * @param {number} [height=1] - The height of the render target.
  7144. * @param {number} [depth=1] - The height of the render target.
  7145. * @param {RenderTarget~Options} [options] - The configuration object.
  7146. */
  7147. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7148. super( width, height, options );
  7149. /**
  7150. * This flag can be used for type testing.
  7151. *
  7152. * @type {boolean}
  7153. * @readonly
  7154. * @default true
  7155. */
  7156. this.isWebGLArrayRenderTarget = true;
  7157. this.depth = depth;
  7158. /**
  7159. * Overwritten with a different texture type.
  7160. *
  7161. * @type {DataArrayTexture}
  7162. */
  7163. this.texture = new DataArrayTexture( null, width, height, depth );
  7164. this._setTextureOptions( options );
  7165. this.texture.isRenderTargetTexture = true;
  7166. }
  7167. }
  7168. /**
  7169. * Creates a three-dimensional texture from raw data, with parameters to
  7170. * divide it into width, height, and depth.
  7171. *
  7172. * @augments Texture
  7173. */
  7174. class Data3DTexture extends Texture {
  7175. /**
  7176. * Constructs a new data array texture.
  7177. *
  7178. * @param {?TypedArray} [data=null] - The buffer data.
  7179. * @param {number} [width=1] - The width of the texture.
  7180. * @param {number} [height=1] - The height of the texture.
  7181. * @param {number} [depth=1] - The depth of the texture.
  7182. */
  7183. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7184. // We're going to add .setXXX() methods for setting properties later.
  7185. // Users can still set in Data3DTexture directly.
  7186. //
  7187. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7188. // texture.anisotropy = 16;
  7189. //
  7190. // See #14839
  7191. super( null );
  7192. /**
  7193. * This flag can be used for type testing.
  7194. *
  7195. * @type {boolean}
  7196. * @readonly
  7197. * @default true
  7198. */
  7199. this.isData3DTexture = true;
  7200. /**
  7201. * The image definition of a data texture.
  7202. *
  7203. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7204. */
  7205. this.image = { data, width, height, depth };
  7206. /**
  7207. * How the texture is sampled when a texel covers more than one pixel.
  7208. *
  7209. * Overwritten and set to `NearestFilter` by default.
  7210. *
  7211. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7212. * @default NearestFilter
  7213. */
  7214. this.magFilter = NearestFilter;
  7215. /**
  7216. * How the texture is sampled when a texel covers less than one pixel.
  7217. *
  7218. * Overwritten and set to `NearestFilter` by default.
  7219. *
  7220. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7221. * @default NearestFilter
  7222. */
  7223. this.minFilter = NearestFilter;
  7224. /**
  7225. * This defines how the texture is wrapped in the depth and corresponds to
  7226. * *W* in UVW mapping.
  7227. *
  7228. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7229. * @default ClampToEdgeWrapping
  7230. */
  7231. this.wrapR = ClampToEdgeWrapping;
  7232. /**
  7233. * Whether to generate mipmaps (if possible) for a texture.
  7234. *
  7235. * Overwritten and set to `false` by default.
  7236. *
  7237. * @type {boolean}
  7238. * @default false
  7239. */
  7240. this.generateMipmaps = false;
  7241. /**
  7242. * If set to `true`, the texture is flipped along the vertical axis when
  7243. * uploaded to the GPU.
  7244. *
  7245. * Overwritten and set to `false` by default.
  7246. *
  7247. * @type {boolean}
  7248. * @default false
  7249. */
  7250. this.flipY = false;
  7251. /**
  7252. * Specifies the alignment requirements for the start of each pixel row in memory.
  7253. *
  7254. * Overwritten and set to `1` by default.
  7255. *
  7256. * @type {boolean}
  7257. * @default 1
  7258. */
  7259. this.unpackAlignment = 1;
  7260. }
  7261. }
  7262. /**
  7263. * A 3D render target used in context of {@link WebGLRenderer}.
  7264. *
  7265. * @augments WebGLRenderTarget
  7266. */
  7267. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7268. /**
  7269. * Constructs a new 3D render target.
  7270. *
  7271. * @param {number} [width=1] - The width of the render target.
  7272. * @param {number} [height=1] - The height of the render target.
  7273. * @param {number} [depth=1] - The height of the render target.
  7274. * @param {RenderTarget~Options} [options] - The configuration object.
  7275. */
  7276. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7277. super( width, height, options );
  7278. /**
  7279. * This flag can be used for type testing.
  7280. *
  7281. * @type {boolean}
  7282. * @readonly
  7283. * @default true
  7284. */
  7285. this.isWebGL3DRenderTarget = true;
  7286. this.depth = depth;
  7287. /**
  7288. * Overwritten with a different texture type.
  7289. *
  7290. * @type {Data3DTexture}
  7291. */
  7292. this.texture = new Data3DTexture( null, width, height, depth );
  7293. this._setTextureOptions( options );
  7294. this.texture.isRenderTargetTexture = true;
  7295. }
  7296. }
  7297. /**
  7298. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7299. */
  7300. class Box3 {
  7301. /**
  7302. * Constructs a new bounding box.
  7303. *
  7304. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7305. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7306. */
  7307. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7308. /**
  7309. * This flag can be used for type testing.
  7310. *
  7311. * @type {boolean}
  7312. * @readonly
  7313. * @default true
  7314. */
  7315. this.isBox3 = true;
  7316. /**
  7317. * The lower boundary of the box.
  7318. *
  7319. * @type {Vector3}
  7320. */
  7321. this.min = min;
  7322. /**
  7323. * The upper boundary of the box.
  7324. *
  7325. * @type {Vector3}
  7326. */
  7327. this.max = max;
  7328. }
  7329. /**
  7330. * Sets the lower and upper boundaries of this box.
  7331. * Please note that this method only copies the values from the given objects.
  7332. *
  7333. * @param {Vector3} min - The lower boundary of the box.
  7334. * @param {Vector3} max - The upper boundary of the box.
  7335. * @return {Box3} A reference to this bounding box.
  7336. */
  7337. set( min, max ) {
  7338. this.min.copy( min );
  7339. this.max.copy( max );
  7340. return this;
  7341. }
  7342. /**
  7343. * Sets the upper and lower bounds of this box so it encloses the position data
  7344. * in the given array.
  7345. *
  7346. * @param {Array<number>} array - An array holding 3D position data.
  7347. * @return {Box3} A reference to this bounding box.
  7348. */
  7349. setFromArray( array ) {
  7350. this.makeEmpty();
  7351. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7352. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7353. }
  7354. return this;
  7355. }
  7356. /**
  7357. * Sets the upper and lower bounds of this box so it encloses the position data
  7358. * in the given buffer attribute.
  7359. *
  7360. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7361. * @return {Box3} A reference to this bounding box.
  7362. */
  7363. setFromBufferAttribute( attribute ) {
  7364. this.makeEmpty();
  7365. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7366. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7367. }
  7368. return this;
  7369. }
  7370. /**
  7371. * Sets the upper and lower bounds of this box so it encloses the position data
  7372. * in the given array.
  7373. *
  7374. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7375. * @return {Box3} A reference to this bounding box.
  7376. */
  7377. setFromPoints( points ) {
  7378. this.makeEmpty();
  7379. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7380. this.expandByPoint( points[ i ] );
  7381. }
  7382. return this;
  7383. }
  7384. /**
  7385. * Centers this box on the given center vector and sets this box's width, height and
  7386. * depth to the given size values.
  7387. *
  7388. * @param {Vector3} center - The center of the box.
  7389. * @param {Vector3} size - The x, y and z dimensions of the box.
  7390. * @return {Box3} A reference to this bounding box.
  7391. */
  7392. setFromCenterAndSize( center, size ) {
  7393. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7394. this.min.copy( center ).sub( halfSize );
  7395. this.max.copy( center ).add( halfSize );
  7396. return this;
  7397. }
  7398. /**
  7399. * Computes the world-axis-aligned bounding box for the given 3D object
  7400. * (including its children), accounting for the object's, and children's,
  7401. * world transforms. The function may result in a larger box than strictly necessary.
  7402. *
  7403. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7404. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7405. * world-axis-aligned bounding box at the expense of more computation.
  7406. * @return {Box3} A reference to this bounding box.
  7407. */
  7408. setFromObject( object, precise = false ) {
  7409. this.makeEmpty();
  7410. return this.expandByObject( object, precise );
  7411. }
  7412. /**
  7413. * Returns a new box with copied values from this instance.
  7414. *
  7415. * @return {Box3} A clone of this instance.
  7416. */
  7417. clone() {
  7418. return new this.constructor().copy( this );
  7419. }
  7420. /**
  7421. * Copies the values of the given box to this instance.
  7422. *
  7423. * @param {Box3} box - The box to copy.
  7424. * @return {Box3} A reference to this bounding box.
  7425. */
  7426. copy( box ) {
  7427. this.min.copy( box.min );
  7428. this.max.copy( box.max );
  7429. return this;
  7430. }
  7431. /**
  7432. * Makes this box empty which means in encloses a zero space in 3D.
  7433. *
  7434. * @return {Box3} A reference to this bounding box.
  7435. */
  7436. makeEmpty() {
  7437. this.min.x = this.min.y = this.min.z = + Infinity;
  7438. this.max.x = this.max.y = this.max.z = - Infinity;
  7439. return this;
  7440. }
  7441. /**
  7442. * Returns true if this box includes zero points within its bounds.
  7443. * Note that a box with equal lower and upper bounds still includes one
  7444. * point, the one both bounds share.
  7445. *
  7446. * @return {boolean} Whether this box is empty or not.
  7447. */
  7448. isEmpty() {
  7449. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7450. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7451. }
  7452. /**
  7453. * Returns the center point of this box.
  7454. *
  7455. * @param {Vector3} target - The target vector that is used to store the method's result.
  7456. * @return {Vector3} The center point.
  7457. */
  7458. getCenter( target ) {
  7459. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7460. }
  7461. /**
  7462. * Returns the dimensions of this box.
  7463. *
  7464. * @param {Vector3} target - The target vector that is used to store the method's result.
  7465. * @return {Vector3} The size.
  7466. */
  7467. getSize( target ) {
  7468. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7469. }
  7470. /**
  7471. * Expands the boundaries of this box to include the given point.
  7472. *
  7473. * @param {Vector3} point - The point that should be included by the bounding box.
  7474. * @return {Box3} A reference to this bounding box.
  7475. */
  7476. expandByPoint( point ) {
  7477. this.min.min( point );
  7478. this.max.max( point );
  7479. return this;
  7480. }
  7481. /**
  7482. * Expands this box equilaterally by the given vector. The width of this
  7483. * box will be expanded by the x component of the vector in both
  7484. * directions. The height of this box will be expanded by the y component of
  7485. * the vector in both directions. The depth of this box will be
  7486. * expanded by the z component of the vector in both directions.
  7487. *
  7488. * @param {Vector3} vector - The vector that should expand the bounding box.
  7489. * @return {Box3} A reference to this bounding box.
  7490. */
  7491. expandByVector( vector ) {
  7492. this.min.sub( vector );
  7493. this.max.add( vector );
  7494. return this;
  7495. }
  7496. /**
  7497. * Expands each dimension of the box by the given scalar. If negative, the
  7498. * dimensions of the box will be contracted.
  7499. *
  7500. * @param {number} scalar - The scalar value that should expand the bounding box.
  7501. * @return {Box3} A reference to this bounding box.
  7502. */
  7503. expandByScalar( scalar ) {
  7504. this.min.addScalar( - scalar );
  7505. this.max.addScalar( scalar );
  7506. return this;
  7507. }
  7508. /**
  7509. * Expands the boundaries of this box to include the given 3D object and
  7510. * its children, accounting for the object's, and children's, world
  7511. * transforms. The function may result in a larger box than strictly
  7512. * necessary (unless the precise parameter is set to true).
  7513. *
  7514. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7515. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7516. * as little as necessary at the expense of more computation.
  7517. * @return {Box3} A reference to this bounding box.
  7518. */
  7519. expandByObject( object, precise = false ) {
  7520. // Computes the world-axis-aligned bounding box of an object (including its children),
  7521. // accounting for both the object's, and children's, world transforms
  7522. object.updateWorldMatrix( false, false );
  7523. const geometry = object.geometry;
  7524. if ( geometry !== undefined ) {
  7525. const positionAttribute = geometry.getAttribute( 'position' );
  7526. // precise AABB computation based on vertex data requires at least a position attribute.
  7527. // instancing isn't supported so far and uses the normal (conservative) code path.
  7528. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7529. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7530. if ( object.isMesh === true ) {
  7531. object.getVertexPosition( i, _vector$b );
  7532. } else {
  7533. _vector$b.fromBufferAttribute( positionAttribute, i );
  7534. }
  7535. _vector$b.applyMatrix4( object.matrixWorld );
  7536. this.expandByPoint( _vector$b );
  7537. }
  7538. } else {
  7539. if ( object.boundingBox !== undefined ) {
  7540. // object-level bounding box
  7541. if ( object.boundingBox === null ) {
  7542. object.computeBoundingBox();
  7543. }
  7544. _box$4.copy( object.boundingBox );
  7545. } else {
  7546. // geometry-level bounding box
  7547. if ( geometry.boundingBox === null ) {
  7548. geometry.computeBoundingBox();
  7549. }
  7550. _box$4.copy( geometry.boundingBox );
  7551. }
  7552. _box$4.applyMatrix4( object.matrixWorld );
  7553. this.union( _box$4 );
  7554. }
  7555. }
  7556. const children = object.children;
  7557. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7558. this.expandByObject( children[ i ], precise );
  7559. }
  7560. return this;
  7561. }
  7562. /**
  7563. * Returns `true` if the given point lies within or on the boundaries of this box.
  7564. *
  7565. * @param {Vector3} point - The point to test.
  7566. * @return {boolean} Whether the bounding box contains the given point or not.
  7567. */
  7568. containsPoint( point ) {
  7569. return point.x >= this.min.x && point.x <= this.max.x &&
  7570. point.y >= this.min.y && point.y <= this.max.y &&
  7571. point.z >= this.min.z && point.z <= this.max.z;
  7572. }
  7573. /**
  7574. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7575. * If this box and the given one are identical, this function also returns `true`.
  7576. *
  7577. * @param {Box3} box - The bounding box to test.
  7578. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7579. */
  7580. containsBox( box ) {
  7581. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7582. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7583. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7584. }
  7585. /**
  7586. * Returns a point as a proportion of this box's width, height and depth.
  7587. *
  7588. * @param {Vector3} point - A point in 3D space.
  7589. * @param {Vector3} target - The target vector that is used to store the method's result.
  7590. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7591. */
  7592. getParameter( point, target ) {
  7593. // This can potentially have a divide by zero if the box
  7594. // has a size dimension of 0.
  7595. return target.set(
  7596. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7597. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7598. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7599. );
  7600. }
  7601. /**
  7602. * Returns `true` if the given bounding box intersects with this bounding box.
  7603. *
  7604. * @param {Box3} box - The bounding box to test.
  7605. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7606. */
  7607. intersectsBox( box ) {
  7608. // using 6 splitting planes to rule out intersections.
  7609. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7610. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7611. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7612. }
  7613. /**
  7614. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7615. *
  7616. * @param {Sphere} sphere - The bounding sphere to test.
  7617. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7618. */
  7619. intersectsSphere( sphere ) {
  7620. // Find the point on the AABB closest to the sphere center.
  7621. this.clampPoint( sphere.center, _vector$b );
  7622. // If that point is inside the sphere, the AABB and sphere intersect.
  7623. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7624. }
  7625. /**
  7626. * Returns `true` if the given plane intersects with this bounding box.
  7627. *
  7628. * @param {Plane} plane - The plane to test.
  7629. * @return {boolean} Whether the given plane intersects with this bounding box.
  7630. */
  7631. intersectsPlane( plane ) {
  7632. // We compute the minimum and maximum dot product values. If those values
  7633. // are on the same side (back or front) of the plane, then there is no intersection.
  7634. let min, max;
  7635. if ( plane.normal.x > 0 ) {
  7636. min = plane.normal.x * this.min.x;
  7637. max = plane.normal.x * this.max.x;
  7638. } else {
  7639. min = plane.normal.x * this.max.x;
  7640. max = plane.normal.x * this.min.x;
  7641. }
  7642. if ( plane.normal.y > 0 ) {
  7643. min += plane.normal.y * this.min.y;
  7644. max += plane.normal.y * this.max.y;
  7645. } else {
  7646. min += plane.normal.y * this.max.y;
  7647. max += plane.normal.y * this.min.y;
  7648. }
  7649. if ( plane.normal.z > 0 ) {
  7650. min += plane.normal.z * this.min.z;
  7651. max += plane.normal.z * this.max.z;
  7652. } else {
  7653. min += plane.normal.z * this.max.z;
  7654. max += plane.normal.z * this.min.z;
  7655. }
  7656. return ( min <= - plane.constant && max >= - plane.constant );
  7657. }
  7658. /**
  7659. * Returns `true` if the given triangle intersects with this bounding box.
  7660. *
  7661. * @param {Triangle} triangle - The triangle to test.
  7662. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7663. */
  7664. intersectsTriangle( triangle ) {
  7665. if ( this.isEmpty() ) {
  7666. return false;
  7667. }
  7668. // compute box center and extents
  7669. this.getCenter( _center );
  7670. _extents.subVectors( this.max, _center );
  7671. // translate triangle to aabb origin
  7672. _v0$2.subVectors( triangle.a, _center );
  7673. _v1$7.subVectors( triangle.b, _center );
  7674. _v2$4.subVectors( triangle.c, _center );
  7675. // compute edge vectors for triangle
  7676. _f0.subVectors( _v1$7, _v0$2 );
  7677. _f1.subVectors( _v2$4, _v1$7 );
  7678. _f2.subVectors( _v0$2, _v2$4 );
  7679. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7680. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  7681. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7682. let axes = [
  7683. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7684. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7685. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7686. ];
  7687. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7688. return false;
  7689. }
  7690. // test 3 face normals from the aabb
  7691. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7692. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7693. return false;
  7694. }
  7695. // finally testing the face normal of the triangle
  7696. // use already existing triangle edge vectors here
  7697. _triangleNormal.crossVectors( _f0, _f1 );
  7698. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7699. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  7700. }
  7701. /**
  7702. * Clamps the given point within the bounds of this box.
  7703. *
  7704. * @param {Vector3} point - The point to clamp.
  7705. * @param {Vector3} target - The target vector that is used to store the method's result.
  7706. * @return {Vector3} The clamped point.
  7707. */
  7708. clampPoint( point, target ) {
  7709. return target.copy( point ).clamp( this.min, this.max );
  7710. }
  7711. /**
  7712. * Returns the euclidean distance from any edge of this box to the specified point. If
  7713. * the given point lies inside of this box, the distance will be `0`.
  7714. *
  7715. * @param {Vector3} point - The point to compute the distance to.
  7716. * @return {number} The euclidean distance.
  7717. */
  7718. distanceToPoint( point ) {
  7719. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7720. }
  7721. /**
  7722. * Returns a bounding sphere that encloses this bounding box.
  7723. *
  7724. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7725. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7726. */
  7727. getBoundingSphere( target ) {
  7728. if ( this.isEmpty() ) {
  7729. target.makeEmpty();
  7730. } else {
  7731. this.getCenter( target.center );
  7732. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7733. }
  7734. return target;
  7735. }
  7736. /**
  7737. * Computes the intersection of this bounding box and the given one, setting the upper
  7738. * bound of this box to the lesser of the two boxes' upper bounds and the
  7739. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7740. * there's no overlap, makes this box empty.
  7741. *
  7742. * @param {Box3} box - The bounding box to intersect with.
  7743. * @return {Box3} A reference to this bounding box.
  7744. */
  7745. intersect( box ) {
  7746. this.min.max( box.min );
  7747. this.max.min( box.max );
  7748. // 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.
  7749. if ( this.isEmpty() ) this.makeEmpty();
  7750. return this;
  7751. }
  7752. /**
  7753. * Computes the union of this box and another and the given one, setting the upper
  7754. * bound of this box to the greater of the two boxes' upper bounds and the
  7755. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7756. *
  7757. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7758. * @return {Box3} A reference to this bounding box.
  7759. */
  7760. union( box ) {
  7761. this.min.min( box.min );
  7762. this.max.max( box.max );
  7763. return this;
  7764. }
  7765. /**
  7766. * Transforms this bounding box by the given 4x4 transformation matrix.
  7767. *
  7768. * @param {Matrix4} matrix - The transformation matrix.
  7769. * @return {Box3} A reference to this bounding box.
  7770. */
  7771. applyMatrix4( matrix ) {
  7772. // transform of empty box is an empty box.
  7773. if ( this.isEmpty() ) return this;
  7774. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7775. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7776. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7777. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7778. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7779. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7780. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7781. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7782. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7783. this.setFromPoints( _points );
  7784. return this;
  7785. }
  7786. /**
  7787. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7788. * effectively moving it in 3D space.
  7789. *
  7790. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7791. * @return {Box3} A reference to this bounding box.
  7792. */
  7793. translate( offset ) {
  7794. this.min.add( offset );
  7795. this.max.add( offset );
  7796. return this;
  7797. }
  7798. /**
  7799. * Returns `true` if this bounding box is equal with the given one.
  7800. *
  7801. * @param {Box3} box - The box to test for equality.
  7802. * @return {boolean} Whether this bounding box is equal with the given one.
  7803. */
  7804. equals( box ) {
  7805. return box.min.equals( this.min ) && box.max.equals( this.max );
  7806. }
  7807. /**
  7808. * Returns a serialized structure of the bounding box.
  7809. *
  7810. * @return {Object} Serialized structure with fields representing the object state.
  7811. */
  7812. toJSON() {
  7813. return {
  7814. min: this.min.toArray(),
  7815. max: this.max.toArray()
  7816. };
  7817. }
  7818. /**
  7819. * Returns a serialized structure of the bounding box.
  7820. *
  7821. * @param {Object} json - The serialized json to set the box from.
  7822. * @return {Box3} A reference to this bounding box.
  7823. */
  7824. fromJSON( json ) {
  7825. this.min.fromArray( json.min );
  7826. this.max.fromArray( json.max );
  7827. return this;
  7828. }
  7829. }
  7830. const _points = [
  7831. /*@__PURE__*/ new Vector3(),
  7832. /*@__PURE__*/ new Vector3(),
  7833. /*@__PURE__*/ new Vector3(),
  7834. /*@__PURE__*/ new Vector3(),
  7835. /*@__PURE__*/ new Vector3(),
  7836. /*@__PURE__*/ new Vector3(),
  7837. /*@__PURE__*/ new Vector3(),
  7838. /*@__PURE__*/ new Vector3()
  7839. ];
  7840. const _vector$b = /*@__PURE__*/ new Vector3();
  7841. const _box$4 = /*@__PURE__*/ new Box3();
  7842. // triangle centered vertices
  7843. const _v0$2 = /*@__PURE__*/ new Vector3();
  7844. const _v1$7 = /*@__PURE__*/ new Vector3();
  7845. const _v2$4 = /*@__PURE__*/ new Vector3();
  7846. // triangle edge vectors
  7847. const _f0 = /*@__PURE__*/ new Vector3();
  7848. const _f1 = /*@__PURE__*/ new Vector3();
  7849. const _f2 = /*@__PURE__*/ new Vector3();
  7850. const _center = /*@__PURE__*/ new Vector3();
  7851. const _extents = /*@__PURE__*/ new Vector3();
  7852. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7853. const _testAxis = /*@__PURE__*/ new Vector3();
  7854. function satForAxes( axes, v0, v1, v2, extents ) {
  7855. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7856. _testAxis.fromArray( axes, i );
  7857. // project the aabb onto the separating axis
  7858. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7859. // project all 3 vertices of the triangle onto the separating axis
  7860. const p0 = v0.dot( _testAxis );
  7861. const p1 = v1.dot( _testAxis );
  7862. const p2 = v2.dot( _testAxis );
  7863. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7864. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7865. // points of the projected triangle are outside the projected half-length of the aabb
  7866. // the axis is separating and we can exit
  7867. return false;
  7868. }
  7869. }
  7870. return true;
  7871. }
  7872. const _box$3 = /*@__PURE__*/ new Box3();
  7873. const _v1$6 = /*@__PURE__*/ new Vector3();
  7874. const _v2$3 = /*@__PURE__*/ new Vector3();
  7875. /**
  7876. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7877. * used as a Bounding Sphere for 3D objects.
  7878. */
  7879. class Sphere {
  7880. /**
  7881. * Constructs a new sphere.
  7882. *
  7883. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7884. * @param {number} [radius=-1] - The radius of the sphere.
  7885. */
  7886. constructor( center = new Vector3(), radius = -1 ) {
  7887. /**
  7888. * This flag can be used for type testing.
  7889. *
  7890. * @type {boolean}
  7891. * @readonly
  7892. * @default true
  7893. */
  7894. this.isSphere = true;
  7895. /**
  7896. * The center of the sphere
  7897. *
  7898. * @type {Vector3}
  7899. */
  7900. this.center = center;
  7901. /**
  7902. * The radius of the sphere.
  7903. *
  7904. * @type {number}
  7905. */
  7906. this.radius = radius;
  7907. }
  7908. /**
  7909. * Sets the sphere's components by copying the given values.
  7910. *
  7911. * @param {Vector3} center - The center.
  7912. * @param {number} radius - The radius.
  7913. * @return {Sphere} A reference to this sphere.
  7914. */
  7915. set( center, radius ) {
  7916. this.center.copy( center );
  7917. this.radius = radius;
  7918. return this;
  7919. }
  7920. /**
  7921. * Computes the minimum bounding sphere for list of points.
  7922. * If the optional center point is given, it is used as the sphere's
  7923. * center. Otherwise, the center of the axis-aligned bounding box
  7924. * encompassing the points is calculated.
  7925. *
  7926. * @param {Array<Vector3>} points - A list of points in 3D space.
  7927. * @param {Vector3} [optionalCenter] - The center of the sphere.
  7928. * @return {Sphere} A reference to this sphere.
  7929. */
  7930. setFromPoints( points, optionalCenter ) {
  7931. const center = this.center;
  7932. if ( optionalCenter !== undefined ) {
  7933. center.copy( optionalCenter );
  7934. } else {
  7935. _box$3.setFromPoints( points ).getCenter( center );
  7936. }
  7937. let maxRadiusSq = 0;
  7938. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7939. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7940. }
  7941. this.radius = Math.sqrt( maxRadiusSq );
  7942. return this;
  7943. }
  7944. /**
  7945. * Copies the values of the given sphere to this instance.
  7946. *
  7947. * @param {Sphere} sphere - The sphere to copy.
  7948. * @return {Sphere} A reference to this sphere.
  7949. */
  7950. copy( sphere ) {
  7951. this.center.copy( sphere.center );
  7952. this.radius = sphere.radius;
  7953. return this;
  7954. }
  7955. /**
  7956. * Returns `true` if the sphere is empty (the radius set to a negative number).
  7957. *
  7958. * Spheres with a radius of `0` contain only their center point and are not
  7959. * considered to be empty.
  7960. *
  7961. * @return {boolean} Whether this sphere is empty or not.
  7962. */
  7963. isEmpty() {
  7964. return ( this.radius < 0 );
  7965. }
  7966. /**
  7967. * Makes this sphere empty which means in encloses a zero space in 3D.
  7968. *
  7969. * @return {Sphere} A reference to this sphere.
  7970. */
  7971. makeEmpty() {
  7972. this.center.set( 0, 0, 0 );
  7973. this.radius = -1;
  7974. return this;
  7975. }
  7976. /**
  7977. * Returns `true` if this sphere contains the given point inclusive of
  7978. * the surface of the sphere.
  7979. *
  7980. * @param {Vector3} point - The point to check.
  7981. * @return {boolean} Whether this sphere contains the given point or not.
  7982. */
  7983. containsPoint( point ) {
  7984. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7985. }
  7986. /**
  7987. * Returns the closest distance from the boundary of the sphere to the
  7988. * given point. If the sphere contains the point, the distance will
  7989. * be negative.
  7990. *
  7991. * @param {Vector3} point - The point to compute the distance to.
  7992. * @return {number} The distance to the point.
  7993. */
  7994. distanceToPoint( point ) {
  7995. return ( point.distanceTo( this.center ) - this.radius );
  7996. }
  7997. /**
  7998. * Returns `true` if this sphere intersects with the given one.
  7999. *
  8000. * @param {Sphere} sphere - The sphere to test.
  8001. * @return {boolean} Whether this sphere intersects with the given one or not.
  8002. */
  8003. intersectsSphere( sphere ) {
  8004. const radiusSum = this.radius + sphere.radius;
  8005. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8006. }
  8007. /**
  8008. * Returns `true` if this sphere intersects with the given box.
  8009. *
  8010. * @param {Box3} box - The box to test.
  8011. * @return {boolean} Whether this sphere intersects with the given box or not.
  8012. */
  8013. intersectsBox( box ) {
  8014. return box.intersectsSphere( this );
  8015. }
  8016. /**
  8017. * Returns `true` if this sphere intersects with the given plane.
  8018. *
  8019. * @param {Plane} plane - The plane to test.
  8020. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8021. */
  8022. intersectsPlane( plane ) {
  8023. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8024. }
  8025. /**
  8026. * Clamps a point within the sphere. If the point is outside the sphere, it
  8027. * will clamp it to the closest point on the edge of the sphere. Points
  8028. * already inside the sphere will not be affected.
  8029. *
  8030. * @param {Vector3} point - The plane to clamp.
  8031. * @param {Vector3} target - The target vector that is used to store the method's result.
  8032. * @return {Vector3} The clamped point.
  8033. */
  8034. clampPoint( point, target ) {
  8035. const deltaLengthSq = this.center.distanceToSquared( point );
  8036. target.copy( point );
  8037. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8038. target.sub( this.center ).normalize();
  8039. target.multiplyScalar( this.radius ).add( this.center );
  8040. }
  8041. return target;
  8042. }
  8043. /**
  8044. * Returns a bounding box that encloses this sphere.
  8045. *
  8046. * @param {Box3} target - The target box that is used to store the method's result.
  8047. * @return {Box3} The bounding box that encloses this sphere.
  8048. */
  8049. getBoundingBox( target ) {
  8050. if ( this.isEmpty() ) {
  8051. // Empty sphere produces empty bounding box
  8052. target.makeEmpty();
  8053. return target;
  8054. }
  8055. target.set( this.center, this.center );
  8056. target.expandByScalar( this.radius );
  8057. return target;
  8058. }
  8059. /**
  8060. * Transforms this sphere with the given 4x4 transformation matrix.
  8061. *
  8062. * @param {Matrix4} matrix - The transformation matrix.
  8063. * @return {Sphere} A reference to this sphere.
  8064. */
  8065. applyMatrix4( matrix ) {
  8066. this.center.applyMatrix4( matrix );
  8067. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8068. return this;
  8069. }
  8070. /**
  8071. * Translates the sphere's center by the given offset.
  8072. *
  8073. * @param {Vector3} offset - The offset.
  8074. * @return {Sphere} A reference to this sphere.
  8075. */
  8076. translate( offset ) {
  8077. this.center.add( offset );
  8078. return this;
  8079. }
  8080. /**
  8081. * Expands the boundaries of this sphere to include the given point.
  8082. *
  8083. * @param {Vector3} point - The point to include.
  8084. * @return {Sphere} A reference to this sphere.
  8085. */
  8086. expandByPoint( point ) {
  8087. if ( this.isEmpty() ) {
  8088. this.center.copy( point );
  8089. this.radius = 0;
  8090. return this;
  8091. }
  8092. _v1$6.subVectors( point, this.center );
  8093. const lengthSq = _v1$6.lengthSq();
  8094. if ( lengthSq > ( this.radius * this.radius ) ) {
  8095. // calculate the minimal sphere
  8096. const length = Math.sqrt( lengthSq );
  8097. const delta = ( length - this.radius ) * 0.5;
  8098. this.center.addScaledVector( _v1$6, delta / length );
  8099. this.radius += delta;
  8100. }
  8101. return this;
  8102. }
  8103. /**
  8104. * Expands this sphere to enclose both the original sphere and the given sphere.
  8105. *
  8106. * @param {Sphere} sphere - The sphere to include.
  8107. * @return {Sphere} A reference to this sphere.
  8108. */
  8109. union( sphere ) {
  8110. if ( sphere.isEmpty() ) {
  8111. return this;
  8112. }
  8113. if ( this.isEmpty() ) {
  8114. this.copy( sphere );
  8115. return this;
  8116. }
  8117. if ( this.center.equals( sphere.center ) === true ) {
  8118. this.radius = Math.max( this.radius, sphere.radius );
  8119. } else {
  8120. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8121. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8122. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8123. }
  8124. return this;
  8125. }
  8126. /**
  8127. * Returns `true` if this sphere is equal with the given one.
  8128. *
  8129. * @param {Sphere} sphere - The sphere to test for equality.
  8130. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8131. */
  8132. equals( sphere ) {
  8133. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8134. }
  8135. /**
  8136. * Returns a new sphere with copied values from this instance.
  8137. *
  8138. * @return {Sphere} A clone of this instance.
  8139. */
  8140. clone() {
  8141. return new this.constructor().copy( this );
  8142. }
  8143. /**
  8144. * Returns a serialized structure of the bounding sphere.
  8145. *
  8146. * @return {Object} Serialized structure with fields representing the object state.
  8147. */
  8148. toJSON() {
  8149. return {
  8150. radius: this.radius,
  8151. center: this.center.toArray()
  8152. };
  8153. }
  8154. /**
  8155. * Returns a serialized structure of the bounding sphere.
  8156. *
  8157. * @param {Object} json - The serialized json to set the sphere from.
  8158. * @return {Box3} A reference to this bounding sphere.
  8159. */
  8160. fromJSON( json ) {
  8161. this.radius = json.radius;
  8162. this.center.fromArray( json.center );
  8163. return this;
  8164. }
  8165. }
  8166. const _vector$a = /*@__PURE__*/ new Vector3();
  8167. const _segCenter = /*@__PURE__*/ new Vector3();
  8168. const _segDir = /*@__PURE__*/ new Vector3();
  8169. const _diff = /*@__PURE__*/ new Vector3();
  8170. const _edge1 = /*@__PURE__*/ new Vector3();
  8171. const _edge2 = /*@__PURE__*/ new Vector3();
  8172. const _normal$1 = /*@__PURE__*/ new Vector3();
  8173. /**
  8174. * A ray that emits from an origin in a certain direction. The class is used by
  8175. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8176. * mouse picking (working out what objects in the 3D space the mouse is over)
  8177. * amongst other things.
  8178. */
  8179. class Ray {
  8180. /**
  8181. * Constructs a new ray.
  8182. *
  8183. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8184. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8185. */
  8186. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8187. /**
  8188. * The origin of the ray.
  8189. *
  8190. * @type {Vector3}
  8191. */
  8192. this.origin = origin;
  8193. /**
  8194. * The (normalized) direction of the ray.
  8195. *
  8196. * @type {Vector3}
  8197. */
  8198. this.direction = direction;
  8199. }
  8200. /**
  8201. * Sets the ray's components by copying the given values.
  8202. *
  8203. * @param {Vector3} origin - The origin.
  8204. * @param {Vector3} direction - The direction.
  8205. * @return {Ray} A reference to this ray.
  8206. */
  8207. set( origin, direction ) {
  8208. this.origin.copy( origin );
  8209. this.direction.copy( direction );
  8210. return this;
  8211. }
  8212. /**
  8213. * Copies the values of the given ray to this instance.
  8214. *
  8215. * @param {Ray} ray - The ray to copy.
  8216. * @return {Ray} A reference to this ray.
  8217. */
  8218. copy( ray ) {
  8219. this.origin.copy( ray.origin );
  8220. this.direction.copy( ray.direction );
  8221. return this;
  8222. }
  8223. /**
  8224. * Returns a vector that is located at a given distance along this ray.
  8225. *
  8226. * @param {number} t - The distance along the ray to retrieve a position for.
  8227. * @param {Vector3} target - The target vector that is used to store the method's result.
  8228. * @return {Vector3} A position on the ray.
  8229. */
  8230. at( t, target ) {
  8231. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8232. }
  8233. /**
  8234. * Adjusts the direction of the ray to point at the given vector in world space.
  8235. *
  8236. * @param {Vector3} v - The target position.
  8237. * @return {Ray} A reference to this ray.
  8238. */
  8239. lookAt( v ) {
  8240. this.direction.copy( v ).sub( this.origin ).normalize();
  8241. return this;
  8242. }
  8243. /**
  8244. * Shift the origin of this ray along its direction by the given distance.
  8245. *
  8246. * @param {number} t - The distance along the ray to interpolate.
  8247. * @return {Ray} A reference to this ray.
  8248. */
  8249. recast( t ) {
  8250. this.origin.copy( this.at( t, _vector$a ) );
  8251. return this;
  8252. }
  8253. /**
  8254. * Returns the point along this ray that is closest to the given point.
  8255. *
  8256. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8257. * @param {Vector3} target - The target vector that is used to store the method's result.
  8258. * @return {Vector3} The closest point on this ray.
  8259. */
  8260. closestPointToPoint( point, target ) {
  8261. target.subVectors( point, this.origin );
  8262. const directionDistance = target.dot( this.direction );
  8263. if ( directionDistance < 0 ) {
  8264. return target.copy( this.origin );
  8265. }
  8266. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8267. }
  8268. /**
  8269. * Returns the distance of the closest approach between this ray and the given point.
  8270. *
  8271. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8272. * @return {number} The distance.
  8273. */
  8274. distanceToPoint( point ) {
  8275. return Math.sqrt( this.distanceSqToPoint( point ) );
  8276. }
  8277. /**
  8278. * Returns the squared distance of the closest approach between this ray and the given point.
  8279. *
  8280. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8281. * @return {number} The squared distance.
  8282. */
  8283. distanceSqToPoint( point ) {
  8284. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8285. // point behind the ray
  8286. if ( directionDistance < 0 ) {
  8287. return this.origin.distanceToSquared( point );
  8288. }
  8289. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8290. return _vector$a.distanceToSquared( point );
  8291. }
  8292. /**
  8293. * Returns the squared distance between this ray and the given line segment.
  8294. *
  8295. * @param {Vector3} v0 - The start point of the line segment.
  8296. * @param {Vector3} v1 - The end point of the line segment.
  8297. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8298. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8299. * @return {number} The squared distance.
  8300. */
  8301. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8302. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8303. // It returns the min distance between the ray and the segment
  8304. // defined by v0 and v1
  8305. // It can also set two optional targets :
  8306. // - The closest point on the ray
  8307. // - The closest point on the segment
  8308. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8309. _segDir.copy( v1 ).sub( v0 ).normalize();
  8310. _diff.copy( this.origin ).sub( _segCenter );
  8311. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8312. const a01 = - this.direction.dot( _segDir );
  8313. const b0 = _diff.dot( this.direction );
  8314. const b1 = - _diff.dot( _segDir );
  8315. const c = _diff.lengthSq();
  8316. const det = Math.abs( 1 - a01 * a01 );
  8317. let s0, s1, sqrDist, extDet;
  8318. if ( det > 0 ) {
  8319. // The ray and segment are not parallel.
  8320. s0 = a01 * b1 - b0;
  8321. s1 = a01 * b0 - b1;
  8322. extDet = segExtent * det;
  8323. if ( s0 >= 0 ) {
  8324. if ( s1 >= - extDet ) {
  8325. if ( s1 <= extDet ) {
  8326. // region 0
  8327. // Minimum at interior points of ray and segment.
  8328. const invDet = 1 / det;
  8329. s0 *= invDet;
  8330. s1 *= invDet;
  8331. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8332. } else {
  8333. // region 1
  8334. s1 = segExtent;
  8335. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8336. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8337. }
  8338. } else {
  8339. // region 5
  8340. s1 = - segExtent;
  8341. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8342. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8343. }
  8344. } else {
  8345. if ( s1 <= - extDet ) {
  8346. // region 4
  8347. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8348. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8349. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8350. } else if ( s1 <= extDet ) {
  8351. // region 3
  8352. s0 = 0;
  8353. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8354. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8355. } else {
  8356. // region 2
  8357. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8358. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8359. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8360. }
  8361. }
  8362. } else {
  8363. // Ray and segment are parallel.
  8364. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8365. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8366. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8367. }
  8368. if ( optionalPointOnRay ) {
  8369. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8370. }
  8371. if ( optionalPointOnSegment ) {
  8372. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8373. }
  8374. return sqrDist;
  8375. }
  8376. /**
  8377. * Intersects this ray with the given sphere, returning the intersection
  8378. * point or `null` if there is no intersection.
  8379. *
  8380. * @param {Sphere} sphere - The sphere to intersect.
  8381. * @param {Vector3} target - The target vector that is used to store the method's result.
  8382. * @return {?Vector3} The intersection point.
  8383. */
  8384. intersectSphere( sphere, target ) {
  8385. _vector$a.subVectors( sphere.center, this.origin );
  8386. const tca = _vector$a.dot( this.direction );
  8387. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8388. const radius2 = sphere.radius * sphere.radius;
  8389. if ( d2 > radius2 ) return null;
  8390. const thc = Math.sqrt( radius2 - d2 );
  8391. // t0 = first intersect point - entrance on front of sphere
  8392. const t0 = tca - thc;
  8393. // t1 = second intersect point - exit point on back of sphere
  8394. const t1 = tca + thc;
  8395. // test to see if t1 is behind the ray - if so, return null
  8396. if ( t1 < 0 ) return null;
  8397. // test to see if t0 is behind the ray:
  8398. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8399. // in order to always return an intersect point that is in front of the ray.
  8400. if ( t0 < 0 ) return this.at( t1, target );
  8401. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8402. return this.at( t0, target );
  8403. }
  8404. /**
  8405. * Returns `true` if this ray intersects with the given sphere.
  8406. *
  8407. * @param {Sphere} sphere - The sphere to intersect.
  8408. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8409. */
  8410. intersectsSphere( sphere ) {
  8411. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8412. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8413. }
  8414. /**
  8415. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8416. * does not intersect with the plane.
  8417. *
  8418. * @param {Plane} plane - The plane to compute the distance to.
  8419. * @return {?number} Whether this ray intersects with the given sphere or not.
  8420. */
  8421. distanceToPlane( plane ) {
  8422. const denominator = plane.normal.dot( this.direction );
  8423. if ( denominator === 0 ) {
  8424. // line is coplanar, return origin
  8425. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8426. return 0;
  8427. }
  8428. // Null is preferable to undefined since undefined means.... it is undefined
  8429. return null;
  8430. }
  8431. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8432. // Return if the ray never intersects the plane
  8433. return t >= 0 ? t : null;
  8434. }
  8435. /**
  8436. * Intersects this ray with the given plane, returning the intersection
  8437. * point or `null` if there is no intersection.
  8438. *
  8439. * @param {Plane} plane - The plane to intersect.
  8440. * @param {Vector3} target - The target vector that is used to store the method's result.
  8441. * @return {?Vector3} The intersection point.
  8442. */
  8443. intersectPlane( plane, target ) {
  8444. const t = this.distanceToPlane( plane );
  8445. if ( t === null ) {
  8446. return null;
  8447. }
  8448. return this.at( t, target );
  8449. }
  8450. /**
  8451. * Returns `true` if this ray intersects with the given plane.
  8452. *
  8453. * @param {Plane} plane - The plane to intersect.
  8454. * @return {boolean} Whether this ray intersects with the given plane or not.
  8455. */
  8456. intersectsPlane( plane ) {
  8457. // check if the ray lies on the plane first
  8458. const distToPoint = plane.distanceToPoint( this.origin );
  8459. if ( distToPoint === 0 ) {
  8460. return true;
  8461. }
  8462. const denominator = plane.normal.dot( this.direction );
  8463. if ( denominator * distToPoint < 0 ) {
  8464. return true;
  8465. }
  8466. // ray origin is behind the plane (and is pointing behind it)
  8467. return false;
  8468. }
  8469. /**
  8470. * Intersects this ray with the given bounding box, returning the intersection
  8471. * point or `null` if there is no intersection.
  8472. *
  8473. * @param {Box3} box - The box to intersect.
  8474. * @param {Vector3} target - The target vector that is used to store the method's result.
  8475. * @return {?Vector3} The intersection point.
  8476. */
  8477. intersectBox( box, target ) {
  8478. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8479. const invdirx = 1 / this.direction.x,
  8480. invdiry = 1 / this.direction.y,
  8481. invdirz = 1 / this.direction.z;
  8482. const origin = this.origin;
  8483. if ( invdirx >= 0 ) {
  8484. tmin = ( box.min.x - origin.x ) * invdirx;
  8485. tmax = ( box.max.x - origin.x ) * invdirx;
  8486. } else {
  8487. tmin = ( box.max.x - origin.x ) * invdirx;
  8488. tmax = ( box.min.x - origin.x ) * invdirx;
  8489. }
  8490. if ( invdiry >= 0 ) {
  8491. tymin = ( box.min.y - origin.y ) * invdiry;
  8492. tymax = ( box.max.y - origin.y ) * invdiry;
  8493. } else {
  8494. tymin = ( box.max.y - origin.y ) * invdiry;
  8495. tymax = ( box.min.y - origin.y ) * invdiry;
  8496. }
  8497. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8498. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8499. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8500. if ( invdirz >= 0 ) {
  8501. tzmin = ( box.min.z - origin.z ) * invdirz;
  8502. tzmax = ( box.max.z - origin.z ) * invdirz;
  8503. } else {
  8504. tzmin = ( box.max.z - origin.z ) * invdirz;
  8505. tzmax = ( box.min.z - origin.z ) * invdirz;
  8506. }
  8507. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8508. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8509. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8510. //return point closest to the ray (positive side)
  8511. if ( tmax < 0 ) return null;
  8512. return this.at( tmin >= 0 ? tmin : tmax, target );
  8513. }
  8514. /**
  8515. * Returns `true` if this ray intersects with the given box.
  8516. *
  8517. * @param {Box3} box - The box to intersect.
  8518. * @return {boolean} Whether this ray intersects with the given box or not.
  8519. */
  8520. intersectsBox( box ) {
  8521. return this.intersectBox( box, _vector$a ) !== null;
  8522. }
  8523. /**
  8524. * Intersects this ray with the given triangle, returning the intersection
  8525. * point or `null` if there is no intersection.
  8526. *
  8527. * @param {Vector3} a - The first vertex of the triangle.
  8528. * @param {Vector3} b - The second vertex of the triangle.
  8529. * @param {Vector3} c - The third vertex of the triangle.
  8530. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8531. * @param {Vector3} target - The target vector that is used to store the method's result.
  8532. * @return {?Vector3} The intersection point.
  8533. */
  8534. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8535. // Compute the offset origin, edges, and normal.
  8536. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8537. _edge1.subVectors( b, a );
  8538. _edge2.subVectors( c, a );
  8539. _normal$1.crossVectors( _edge1, _edge2 );
  8540. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8541. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8542. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8543. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8544. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8545. let DdN = this.direction.dot( _normal$1 );
  8546. let sign;
  8547. if ( DdN > 0 ) {
  8548. if ( backfaceCulling ) return null;
  8549. sign = 1;
  8550. } else if ( DdN < 0 ) {
  8551. sign = -1;
  8552. DdN = - DdN;
  8553. } else {
  8554. return null;
  8555. }
  8556. _diff.subVectors( this.origin, a );
  8557. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8558. // b1 < 0, no intersection
  8559. if ( DdQxE2 < 0 ) {
  8560. return null;
  8561. }
  8562. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8563. // b2 < 0, no intersection
  8564. if ( DdE1xQ < 0 ) {
  8565. return null;
  8566. }
  8567. // b1+b2 > 1, no intersection
  8568. if ( DdQxE2 + DdE1xQ > DdN ) {
  8569. return null;
  8570. }
  8571. // Line intersects triangle, check if ray does.
  8572. const QdN = - sign * _diff.dot( _normal$1 );
  8573. // t < 0, no intersection
  8574. if ( QdN < 0 ) {
  8575. return null;
  8576. }
  8577. // Ray intersects triangle.
  8578. return this.at( QdN / DdN, target );
  8579. }
  8580. /**
  8581. * Transforms this ray with the given 4x4 transformation matrix.
  8582. *
  8583. * @param {Matrix4} matrix4 - The transformation matrix.
  8584. * @return {Ray} A reference to this ray.
  8585. */
  8586. applyMatrix4( matrix4 ) {
  8587. this.origin.applyMatrix4( matrix4 );
  8588. this.direction.transformDirection( matrix4 );
  8589. return this;
  8590. }
  8591. /**
  8592. * Returns `true` if this ray is equal with the given one.
  8593. *
  8594. * @param {Ray} ray - The ray to test for equality.
  8595. * @return {boolean} Whether this ray is equal with the given one.
  8596. */
  8597. equals( ray ) {
  8598. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8599. }
  8600. /**
  8601. * Returns a new ray with copied values from this instance.
  8602. *
  8603. * @return {Ray} A clone of this instance.
  8604. */
  8605. clone() {
  8606. return new this.constructor().copy( this );
  8607. }
  8608. }
  8609. /**
  8610. * Represents a 4x4 matrix.
  8611. *
  8612. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8613. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial]{@link https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices}
  8614. *
  8615. * This allows a 3D vector representing a point in 3D space to undergo
  8616. * transformations such as translation, rotation, shear, scale, reflection,
  8617. * orthogonal or perspective projection and so on, by being multiplied by the
  8618. * matrix. This is known as `applying` the matrix to the vector.
  8619. *
  8620. * A Note on Row-Major and Column-Major Ordering:
  8621. *
  8622. * The constructor and {@link Matrix3#set} method take arguments in
  8623. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  8624. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8625. * This means that calling:
  8626. * ```js
  8627. * const m = new THREE.Matrix4();
  8628. * m.set( 11, 12, 13, 14,
  8629. * 21, 22, 23, 24,
  8630. * 31, 32, 33, 34,
  8631. * 41, 42, 43, 44 );
  8632. * ```
  8633. * will result in the elements array containing:
  8634. * ```js
  8635. * m.elements = [ 11, 21, 31, 41,
  8636. * 12, 22, 32, 42,
  8637. * 13, 23, 33, 43,
  8638. * 14, 24, 34, 44 ];
  8639. * ```
  8640. * and internally all calculations are performed using column-major ordering.
  8641. * However, as the actual ordering makes no difference mathematically and
  8642. * most people are used to thinking about matrices in row-major order, the
  8643. * three.js documentation shows matrices in row-major order. Just bear in
  8644. * mind that if you are reading the source code, you'll have to take the
  8645. * transpose of any matrices outlined here to make sense of the calculations.
  8646. */
  8647. class Matrix4 {
  8648. /**
  8649. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8650. * in row-major order. If no arguments are provided, the constructor
  8651. * initializes the matrix as an identity matrix.
  8652. *
  8653. * @param {number} [n11] - 1-1 matrix element.
  8654. * @param {number} [n12] - 1-2 matrix element.
  8655. * @param {number} [n13] - 1-3 matrix element.
  8656. * @param {number} [n14] - 1-4 matrix element.
  8657. * @param {number} [n21] - 2-1 matrix element.
  8658. * @param {number} [n22] - 2-2 matrix element.
  8659. * @param {number} [n23] - 2-3 matrix element.
  8660. * @param {number} [n24] - 2-4 matrix element.
  8661. * @param {number} [n31] - 3-1 matrix element.
  8662. * @param {number} [n32] - 3-2 matrix element.
  8663. * @param {number} [n33] - 3-3 matrix element.
  8664. * @param {number} [n34] - 3-4 matrix element.
  8665. * @param {number} [n41] - 4-1 matrix element.
  8666. * @param {number} [n42] - 4-2 matrix element.
  8667. * @param {number} [n43] - 4-3 matrix element.
  8668. * @param {number} [n44] - 4-4 matrix element.
  8669. */
  8670. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8671. /**
  8672. * This flag can be used for type testing.
  8673. *
  8674. * @type {boolean}
  8675. * @readonly
  8676. * @default true
  8677. */
  8678. Matrix4.prototype.isMatrix4 = true;
  8679. /**
  8680. * A column-major list of matrix values.
  8681. *
  8682. * @type {Array<number>}
  8683. */
  8684. this.elements = [
  8685. 1, 0, 0, 0,
  8686. 0, 1, 0, 0,
  8687. 0, 0, 1, 0,
  8688. 0, 0, 0, 1
  8689. ];
  8690. if ( n11 !== undefined ) {
  8691. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8692. }
  8693. }
  8694. /**
  8695. * Sets the elements of the matrix.The arguments are supposed to be
  8696. * in row-major order.
  8697. *
  8698. * @param {number} [n11] - 1-1 matrix element.
  8699. * @param {number} [n12] - 1-2 matrix element.
  8700. * @param {number} [n13] - 1-3 matrix element.
  8701. * @param {number} [n14] - 1-4 matrix element.
  8702. * @param {number} [n21] - 2-1 matrix element.
  8703. * @param {number} [n22] - 2-2 matrix element.
  8704. * @param {number} [n23] - 2-3 matrix element.
  8705. * @param {number} [n24] - 2-4 matrix element.
  8706. * @param {number} [n31] - 3-1 matrix element.
  8707. * @param {number} [n32] - 3-2 matrix element.
  8708. * @param {number} [n33] - 3-3 matrix element.
  8709. * @param {number} [n34] - 3-4 matrix element.
  8710. * @param {number} [n41] - 4-1 matrix element.
  8711. * @param {number} [n42] - 4-2 matrix element.
  8712. * @param {number} [n43] - 4-3 matrix element.
  8713. * @param {number} [n44] - 4-4 matrix element.
  8714. * @return {Matrix4} A reference to this matrix.
  8715. */
  8716. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8717. const te = this.elements;
  8718. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8719. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8720. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8721. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8722. return this;
  8723. }
  8724. /**
  8725. * Sets this matrix to the 4x4 identity matrix.
  8726. *
  8727. * @return {Matrix4} A reference to this matrix.
  8728. */
  8729. identity() {
  8730. this.set(
  8731. 1, 0, 0, 0,
  8732. 0, 1, 0, 0,
  8733. 0, 0, 1, 0,
  8734. 0, 0, 0, 1
  8735. );
  8736. return this;
  8737. }
  8738. /**
  8739. * Returns a matrix with copied values from this instance.
  8740. *
  8741. * @return {Matrix4} A clone of this instance.
  8742. */
  8743. clone() {
  8744. return new Matrix4().fromArray( this.elements );
  8745. }
  8746. /**
  8747. * Copies the values of the given matrix to this instance.
  8748. *
  8749. * @param {Matrix4} m - The matrix to copy.
  8750. * @return {Matrix4} A reference to this matrix.
  8751. */
  8752. copy( m ) {
  8753. const te = this.elements;
  8754. const me = m.elements;
  8755. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8756. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8757. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8758. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8759. return this;
  8760. }
  8761. /**
  8762. * Copies the translation component of the given matrix
  8763. * into this matrix's translation component.
  8764. *
  8765. * @param {Matrix4} m - The matrix to copy the translation component.
  8766. * @return {Matrix4} A reference to this matrix.
  8767. */
  8768. copyPosition( m ) {
  8769. const te = this.elements, me = m.elements;
  8770. te[ 12 ] = me[ 12 ];
  8771. te[ 13 ] = me[ 13 ];
  8772. te[ 14 ] = me[ 14 ];
  8773. return this;
  8774. }
  8775. /**
  8776. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8777. *
  8778. * @param {Matrix3} m - The 3x3 matrix.
  8779. * @return {Matrix4} A reference to this matrix.
  8780. */
  8781. setFromMatrix3( m ) {
  8782. const me = m.elements;
  8783. this.set(
  8784. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8785. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8786. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8787. 0, 0, 0, 1
  8788. );
  8789. return this;
  8790. }
  8791. /**
  8792. * Extracts the basis of this matrix into the three axis vectors provided.
  8793. *
  8794. * @param {Vector3} xAxis - The basis's x axis.
  8795. * @param {Vector3} yAxis - The basis's y axis.
  8796. * @param {Vector3} zAxis - The basis's z axis.
  8797. * @return {Matrix4} A reference to this matrix.
  8798. */
  8799. extractBasis( xAxis, yAxis, zAxis ) {
  8800. xAxis.setFromMatrixColumn( this, 0 );
  8801. yAxis.setFromMatrixColumn( this, 1 );
  8802. zAxis.setFromMatrixColumn( this, 2 );
  8803. return this;
  8804. }
  8805. /**
  8806. * Sets the given basis vectors to this matrix.
  8807. *
  8808. * @param {Vector3} xAxis - The basis's x axis.
  8809. * @param {Vector3} yAxis - The basis's y axis.
  8810. * @param {Vector3} zAxis - The basis's z axis.
  8811. * @return {Matrix4} A reference to this matrix.
  8812. */
  8813. makeBasis( xAxis, yAxis, zAxis ) {
  8814. this.set(
  8815. xAxis.x, yAxis.x, zAxis.x, 0,
  8816. xAxis.y, yAxis.y, zAxis.y, 0,
  8817. xAxis.z, yAxis.z, zAxis.z, 0,
  8818. 0, 0, 0, 1
  8819. );
  8820. return this;
  8821. }
  8822. /**
  8823. * Extracts the rotation component of the given matrix
  8824. * into this matrix's rotation component.
  8825. *
  8826. * Note: This method does not support reflection matrices.
  8827. *
  8828. * @param {Matrix4} m - The matrix.
  8829. * @return {Matrix4} A reference to this matrix.
  8830. */
  8831. extractRotation( m ) {
  8832. const te = this.elements;
  8833. const me = m.elements;
  8834. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8835. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8836. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8837. te[ 0 ] = me[ 0 ] * scaleX;
  8838. te[ 1 ] = me[ 1 ] * scaleX;
  8839. te[ 2 ] = me[ 2 ] * scaleX;
  8840. te[ 3 ] = 0;
  8841. te[ 4 ] = me[ 4 ] * scaleY;
  8842. te[ 5 ] = me[ 5 ] * scaleY;
  8843. te[ 6 ] = me[ 6 ] * scaleY;
  8844. te[ 7 ] = 0;
  8845. te[ 8 ] = me[ 8 ] * scaleZ;
  8846. te[ 9 ] = me[ 9 ] * scaleZ;
  8847. te[ 10 ] = me[ 10 ] * scaleZ;
  8848. te[ 11 ] = 0;
  8849. te[ 12 ] = 0;
  8850. te[ 13 ] = 0;
  8851. te[ 14 ] = 0;
  8852. te[ 15 ] = 1;
  8853. return this;
  8854. }
  8855. /**
  8856. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8857. * the rotation specified by the given Euler angles. The rest of
  8858. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8859. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  8860. * for a complete list.
  8861. *
  8862. * @param {Euler} euler - The Euler angles.
  8863. * @return {Matrix4} A reference to this matrix.
  8864. */
  8865. makeRotationFromEuler( euler ) {
  8866. const te = this.elements;
  8867. const x = euler.x, y = euler.y, z = euler.z;
  8868. const a = Math.cos( x ), b = Math.sin( x );
  8869. const c = Math.cos( y ), d = Math.sin( y );
  8870. const e = Math.cos( z ), f = Math.sin( z );
  8871. if ( euler.order === 'XYZ' ) {
  8872. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8873. te[ 0 ] = c * e;
  8874. te[ 4 ] = - c * f;
  8875. te[ 8 ] = d;
  8876. te[ 1 ] = af + be * d;
  8877. te[ 5 ] = ae - bf * d;
  8878. te[ 9 ] = - b * c;
  8879. te[ 2 ] = bf - ae * d;
  8880. te[ 6 ] = be + af * d;
  8881. te[ 10 ] = a * c;
  8882. } else if ( euler.order === 'YXZ' ) {
  8883. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8884. te[ 0 ] = ce + df * b;
  8885. te[ 4 ] = de * b - cf;
  8886. te[ 8 ] = a * d;
  8887. te[ 1 ] = a * f;
  8888. te[ 5 ] = a * e;
  8889. te[ 9 ] = - b;
  8890. te[ 2 ] = cf * b - de;
  8891. te[ 6 ] = df + ce * b;
  8892. te[ 10 ] = a * c;
  8893. } else if ( euler.order === 'ZXY' ) {
  8894. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8895. te[ 0 ] = ce - df * b;
  8896. te[ 4 ] = - a * f;
  8897. te[ 8 ] = de + cf * b;
  8898. te[ 1 ] = cf + de * b;
  8899. te[ 5 ] = a * e;
  8900. te[ 9 ] = df - ce * b;
  8901. te[ 2 ] = - a * d;
  8902. te[ 6 ] = b;
  8903. te[ 10 ] = a * c;
  8904. } else if ( euler.order === 'ZYX' ) {
  8905. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8906. te[ 0 ] = c * e;
  8907. te[ 4 ] = be * d - af;
  8908. te[ 8 ] = ae * d + bf;
  8909. te[ 1 ] = c * f;
  8910. te[ 5 ] = bf * d + ae;
  8911. te[ 9 ] = af * d - be;
  8912. te[ 2 ] = - d;
  8913. te[ 6 ] = b * c;
  8914. te[ 10 ] = a * c;
  8915. } else if ( euler.order === 'YZX' ) {
  8916. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8917. te[ 0 ] = c * e;
  8918. te[ 4 ] = bd - ac * f;
  8919. te[ 8 ] = bc * f + ad;
  8920. te[ 1 ] = f;
  8921. te[ 5 ] = a * e;
  8922. te[ 9 ] = - b * e;
  8923. te[ 2 ] = - d * e;
  8924. te[ 6 ] = ad * f + bc;
  8925. te[ 10 ] = ac - bd * f;
  8926. } else if ( euler.order === 'XZY' ) {
  8927. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8928. te[ 0 ] = c * e;
  8929. te[ 4 ] = - f;
  8930. te[ 8 ] = d * e;
  8931. te[ 1 ] = ac * f + bd;
  8932. te[ 5 ] = a * e;
  8933. te[ 9 ] = ad * f - bc;
  8934. te[ 2 ] = bc * f - ad;
  8935. te[ 6 ] = b * e;
  8936. te[ 10 ] = bd * f + ac;
  8937. }
  8938. // bottom row
  8939. te[ 3 ] = 0;
  8940. te[ 7 ] = 0;
  8941. te[ 11 ] = 0;
  8942. // last column
  8943. te[ 12 ] = 0;
  8944. te[ 13 ] = 0;
  8945. te[ 14 ] = 0;
  8946. te[ 15 ] = 1;
  8947. return this;
  8948. }
  8949. /**
  8950. * Sets the rotation component of this matrix to the rotation specified by
  8951. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  8952. * The rest of the matrix is set to the identity.
  8953. *
  8954. * @param {Quaternion} q - The Quaternion.
  8955. * @return {Matrix4} A reference to this matrix.
  8956. */
  8957. makeRotationFromQuaternion( q ) {
  8958. return this.compose( _zero, q, _one );
  8959. }
  8960. /**
  8961. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  8962. * `target`, and oriented by the up-direction.
  8963. *
  8964. * @param {Vector3} eye - The eye vector.
  8965. * @param {Vector3} target - The target vector.
  8966. * @param {Vector3} up - The up vector.
  8967. * @return {Matrix4} A reference to this matrix.
  8968. */
  8969. lookAt( eye, target, up ) {
  8970. const te = this.elements;
  8971. _z.subVectors( eye, target );
  8972. if ( _z.lengthSq() === 0 ) {
  8973. // eye and target are in the same position
  8974. _z.z = 1;
  8975. }
  8976. _z.normalize();
  8977. _x.crossVectors( up, _z );
  8978. if ( _x.lengthSq() === 0 ) {
  8979. // up and z are parallel
  8980. if ( Math.abs( up.z ) === 1 ) {
  8981. _z.x += 0.0001;
  8982. } else {
  8983. _z.z += 0.0001;
  8984. }
  8985. _z.normalize();
  8986. _x.crossVectors( up, _z );
  8987. }
  8988. _x.normalize();
  8989. _y.crossVectors( _z, _x );
  8990. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8991. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8992. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8993. return this;
  8994. }
  8995. /**
  8996. * Post-multiplies this matrix by the given 4x4 matrix.
  8997. *
  8998. * @param {Matrix4} m - The matrix to multiply with.
  8999. * @return {Matrix4} A reference to this matrix.
  9000. */
  9001. multiply( m ) {
  9002. return this.multiplyMatrices( this, m );
  9003. }
  9004. /**
  9005. * Pre-multiplies this matrix by the given 4x4 matrix.
  9006. *
  9007. * @param {Matrix4} m - The matrix to multiply with.
  9008. * @return {Matrix4} A reference to this matrix.
  9009. */
  9010. premultiply( m ) {
  9011. return this.multiplyMatrices( m, this );
  9012. }
  9013. /**
  9014. * Multiples the given 4x4 matrices and stores the result
  9015. * in this matrix.
  9016. *
  9017. * @param {Matrix4} a - The first matrix.
  9018. * @param {Matrix4} b - The second matrix.
  9019. * @return {Matrix4} A reference to this matrix.
  9020. */
  9021. multiplyMatrices( a, b ) {
  9022. const ae = a.elements;
  9023. const be = b.elements;
  9024. const te = this.elements;
  9025. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9026. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9027. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9028. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9029. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9030. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9031. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9032. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9033. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9034. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9035. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9036. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9037. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9038. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9039. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9040. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9041. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9042. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9043. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9044. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9045. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9046. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9047. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9048. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9049. return this;
  9050. }
  9051. /**
  9052. * Multiplies every component of the matrix by the given scalar.
  9053. *
  9054. * @param {number} s - The scalar.
  9055. * @return {Matrix4} A reference to this matrix.
  9056. */
  9057. multiplyScalar( s ) {
  9058. const te = this.elements;
  9059. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9060. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9061. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9062. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9063. return this;
  9064. }
  9065. /**
  9066. * Computes and returns the determinant of this matrix.
  9067. *
  9068. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  9069. *
  9070. * @return {number} The determinant.
  9071. */
  9072. determinant() {
  9073. const te = this.elements;
  9074. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9075. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9076. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9077. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9078. //TODO: make this more efficient
  9079. return (
  9080. n41 * (
  9081. + n14 * n23 * n32
  9082. - n13 * n24 * n32
  9083. - n14 * n22 * n33
  9084. + n12 * n24 * n33
  9085. + n13 * n22 * n34
  9086. - n12 * n23 * n34
  9087. ) +
  9088. n42 * (
  9089. + n11 * n23 * n34
  9090. - n11 * n24 * n33
  9091. + n14 * n21 * n33
  9092. - n13 * n21 * n34
  9093. + n13 * n24 * n31
  9094. - n14 * n23 * n31
  9095. ) +
  9096. n43 * (
  9097. + n11 * n24 * n32
  9098. - n11 * n22 * n34
  9099. - n14 * n21 * n32
  9100. + n12 * n21 * n34
  9101. + n14 * n22 * n31
  9102. - n12 * n24 * n31
  9103. ) +
  9104. n44 * (
  9105. - n13 * n22 * n31
  9106. - n11 * n23 * n32
  9107. + n11 * n22 * n33
  9108. + n13 * n21 * n32
  9109. - n12 * n21 * n33
  9110. + n12 * n23 * n31
  9111. )
  9112. );
  9113. }
  9114. /**
  9115. * Transposes this matrix in place.
  9116. *
  9117. * @return {Matrix4} A reference to this matrix.
  9118. */
  9119. transpose() {
  9120. const te = this.elements;
  9121. let tmp;
  9122. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9123. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9124. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9125. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9126. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9127. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9128. return this;
  9129. }
  9130. /**
  9131. * Sets the position component for this matrix from the given vector,
  9132. * without affecting the rest of the matrix.
  9133. *
  9134. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9135. * @param {number} y - The y component of the vector.
  9136. * @param {number} z - The z component of the vector.
  9137. * @return {Matrix4} A reference to this matrix.
  9138. */
  9139. setPosition( x, y, z ) {
  9140. const te = this.elements;
  9141. if ( x.isVector3 ) {
  9142. te[ 12 ] = x.x;
  9143. te[ 13 ] = x.y;
  9144. te[ 14 ] = x.z;
  9145. } else {
  9146. te[ 12 ] = x;
  9147. te[ 13 ] = y;
  9148. te[ 14 ] = z;
  9149. }
  9150. return this;
  9151. }
  9152. /**
  9153. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  9154. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9155. * a zero matrix instead.
  9156. *
  9157. * @return {Matrix4} A reference to this matrix.
  9158. */
  9159. invert() {
  9160. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9161. const te = this.elements,
  9162. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9163. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9164. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9165. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9166. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9167. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9168. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9169. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9170. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9171. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9172. const detInv = 1 / det;
  9173. te[ 0 ] = t11 * detInv;
  9174. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9175. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9176. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9177. te[ 4 ] = t12 * detInv;
  9178. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9179. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9180. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9181. te[ 8 ] = t13 * detInv;
  9182. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9183. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9184. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9185. te[ 12 ] = t14 * detInv;
  9186. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9187. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9188. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9189. return this;
  9190. }
  9191. /**
  9192. * Multiplies the columns of this matrix by the given vector.
  9193. *
  9194. * @param {Vector3} v - The scale vector.
  9195. * @return {Matrix4} A reference to this matrix.
  9196. */
  9197. scale( v ) {
  9198. const te = this.elements;
  9199. const x = v.x, y = v.y, z = v.z;
  9200. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9201. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9202. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9203. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9204. return this;
  9205. }
  9206. /**
  9207. * Gets the maximum scale value of the three axes.
  9208. *
  9209. * @return {number} The maximum scale.
  9210. */
  9211. getMaxScaleOnAxis() {
  9212. const te = this.elements;
  9213. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9214. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9215. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9216. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9217. }
  9218. /**
  9219. * Sets this matrix as a translation transform from the given vector.
  9220. *
  9221. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9222. * @param {number} y - The amount to translate in the Y axis.
  9223. * @param {number} z - The amount to translate in the z axis.
  9224. * @return {Matrix4} A reference to this matrix.
  9225. */
  9226. makeTranslation( x, y, z ) {
  9227. if ( x.isVector3 ) {
  9228. this.set(
  9229. 1, 0, 0, x.x,
  9230. 0, 1, 0, x.y,
  9231. 0, 0, 1, x.z,
  9232. 0, 0, 0, 1
  9233. );
  9234. } else {
  9235. this.set(
  9236. 1, 0, 0, x,
  9237. 0, 1, 0, y,
  9238. 0, 0, 1, z,
  9239. 0, 0, 0, 1
  9240. );
  9241. }
  9242. return this;
  9243. }
  9244. /**
  9245. * Sets this matrix as a rotational transformation around the X axis by
  9246. * the given angle.
  9247. *
  9248. * @param {number} theta - The rotation in radians.
  9249. * @return {Matrix4} A reference to this matrix.
  9250. */
  9251. makeRotationX( theta ) {
  9252. const c = Math.cos( theta ), s = Math.sin( theta );
  9253. this.set(
  9254. 1, 0, 0, 0,
  9255. 0, c, - s, 0,
  9256. 0, s, c, 0,
  9257. 0, 0, 0, 1
  9258. );
  9259. return this;
  9260. }
  9261. /**
  9262. * Sets this matrix as a rotational transformation around the Y axis by
  9263. * the given angle.
  9264. *
  9265. * @param {number} theta - The rotation in radians.
  9266. * @return {Matrix4} A reference to this matrix.
  9267. */
  9268. makeRotationY( theta ) {
  9269. const c = Math.cos( theta ), s = Math.sin( theta );
  9270. this.set(
  9271. c, 0, s, 0,
  9272. 0, 1, 0, 0,
  9273. - s, 0, c, 0,
  9274. 0, 0, 0, 1
  9275. );
  9276. return this;
  9277. }
  9278. /**
  9279. * Sets this matrix as a rotational transformation around the Z axis by
  9280. * the given angle.
  9281. *
  9282. * @param {number} theta - The rotation in radians.
  9283. * @return {Matrix4} A reference to this matrix.
  9284. */
  9285. makeRotationZ( theta ) {
  9286. const c = Math.cos( theta ), s = Math.sin( theta );
  9287. this.set(
  9288. c, - s, 0, 0,
  9289. s, c, 0, 0,
  9290. 0, 0, 1, 0,
  9291. 0, 0, 0, 1
  9292. );
  9293. return this;
  9294. }
  9295. /**
  9296. * Sets this matrix as a rotational transformation around the given axis by
  9297. * the given angle.
  9298. *
  9299. * This is a somewhat controversial but mathematically sound alternative to
  9300. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  9301. *
  9302. * @param {Vector3} axis - The normalized rotation axis.
  9303. * @param {number} angle - The rotation in radians.
  9304. * @return {Matrix4} A reference to this matrix.
  9305. */
  9306. makeRotationAxis( axis, angle ) {
  9307. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9308. const c = Math.cos( angle );
  9309. const s = Math.sin( angle );
  9310. const t = 1 - c;
  9311. const x = axis.x, y = axis.y, z = axis.z;
  9312. const tx = t * x, ty = t * y;
  9313. this.set(
  9314. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9315. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9316. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9317. 0, 0, 0, 1
  9318. );
  9319. return this;
  9320. }
  9321. /**
  9322. * Sets this matrix as a scale transformation.
  9323. *
  9324. * @param {number} x - The amount to scale in the X axis.
  9325. * @param {number} y - The amount to scale in the Y axis.
  9326. * @param {number} z - The amount to scale in the Z axis.
  9327. * @return {Matrix4} A reference to this matrix.
  9328. */
  9329. makeScale( x, y, z ) {
  9330. this.set(
  9331. x, 0, 0, 0,
  9332. 0, y, 0, 0,
  9333. 0, 0, z, 0,
  9334. 0, 0, 0, 1
  9335. );
  9336. return this;
  9337. }
  9338. /**
  9339. * Sets this matrix as a shear transformation.
  9340. *
  9341. * @param {number} xy - The amount to shear X by Y.
  9342. * @param {number} xz - The amount to shear X by Z.
  9343. * @param {number} yx - The amount to shear Y by X.
  9344. * @param {number} yz - The amount to shear Y by Z.
  9345. * @param {number} zx - The amount to shear Z by X.
  9346. * @param {number} zy - The amount to shear Z by Y.
  9347. * @return {Matrix4} A reference to this matrix.
  9348. */
  9349. makeShear( xy, xz, yx, yz, zx, zy ) {
  9350. this.set(
  9351. 1, yx, zx, 0,
  9352. xy, 1, zy, 0,
  9353. xz, yz, 1, 0,
  9354. 0, 0, 0, 1
  9355. );
  9356. return this;
  9357. }
  9358. /**
  9359. * Sets this matrix to the transformation composed of the given position,
  9360. * rotation (Quaternion) and scale.
  9361. *
  9362. * @param {Vector3} position - The position vector.
  9363. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9364. * @param {Vector3} scale - The scale vector.
  9365. * @return {Matrix4} A reference to this matrix.
  9366. */
  9367. compose( position, quaternion, scale ) {
  9368. const te = this.elements;
  9369. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9370. const x2 = x + x, y2 = y + y, z2 = z + z;
  9371. const xx = x * x2, xy = x * y2, xz = x * z2;
  9372. const yy = y * y2, yz = y * z2, zz = z * z2;
  9373. const wx = w * x2, wy = w * y2, wz = w * z2;
  9374. const sx = scale.x, sy = scale.y, sz = scale.z;
  9375. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9376. te[ 1 ] = ( xy + wz ) * sx;
  9377. te[ 2 ] = ( xz - wy ) * sx;
  9378. te[ 3 ] = 0;
  9379. te[ 4 ] = ( xy - wz ) * sy;
  9380. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9381. te[ 6 ] = ( yz + wx ) * sy;
  9382. te[ 7 ] = 0;
  9383. te[ 8 ] = ( xz + wy ) * sz;
  9384. te[ 9 ] = ( yz - wx ) * sz;
  9385. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9386. te[ 11 ] = 0;
  9387. te[ 12 ] = position.x;
  9388. te[ 13 ] = position.y;
  9389. te[ 14 ] = position.z;
  9390. te[ 15 ] = 1;
  9391. return this;
  9392. }
  9393. /**
  9394. * Decomposes this matrix into its position, rotation and scale components
  9395. * and provides the result in the given objects.
  9396. *
  9397. * Note: Not all matrices are decomposable in this way. For example, if an
  9398. * object has a non-uniformly scaled parent, then the object's world matrix
  9399. * may not be decomposable, and this method may not be appropriate.
  9400. *
  9401. * @param {Vector3} position - The position vector.
  9402. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9403. * @param {Vector3} scale - The scale vector.
  9404. * @return {Matrix4} A reference to this matrix.
  9405. */
  9406. decompose( position, quaternion, scale ) {
  9407. const te = this.elements;
  9408. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9409. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9410. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9411. // if determine is negative, we need to invert one scale
  9412. const det = this.determinant();
  9413. if ( det < 0 ) sx = - sx;
  9414. position.x = te[ 12 ];
  9415. position.y = te[ 13 ];
  9416. position.z = te[ 14 ];
  9417. // scale the rotation part
  9418. _m1$2.copy( this );
  9419. const invSX = 1 / sx;
  9420. const invSY = 1 / sy;
  9421. const invSZ = 1 / sz;
  9422. _m1$2.elements[ 0 ] *= invSX;
  9423. _m1$2.elements[ 1 ] *= invSX;
  9424. _m1$2.elements[ 2 ] *= invSX;
  9425. _m1$2.elements[ 4 ] *= invSY;
  9426. _m1$2.elements[ 5 ] *= invSY;
  9427. _m1$2.elements[ 6 ] *= invSY;
  9428. _m1$2.elements[ 8 ] *= invSZ;
  9429. _m1$2.elements[ 9 ] *= invSZ;
  9430. _m1$2.elements[ 10 ] *= invSZ;
  9431. quaternion.setFromRotationMatrix( _m1$2 );
  9432. scale.x = sx;
  9433. scale.y = sy;
  9434. scale.z = sz;
  9435. return this;
  9436. }
  9437. /**
  9438. * Creates a perspective projection matrix. This is used internally by
  9439. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9440. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9441. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9442. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9443. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9444. * @param {number} near - The distance from the camera to the near plane.
  9445. * @param {number} far - The distance from the camera to the far plane.
  9446. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9447. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9448. * @return {Matrix4} A reference to this matrix.
  9449. */
  9450. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9451. const te = this.elements;
  9452. const x = 2 * near / ( right - left );
  9453. const y = 2 * near / ( top - bottom );
  9454. const a = ( right + left ) / ( right - left );
  9455. const b = ( top + bottom ) / ( top - bottom );
  9456. let c, d;
  9457. if ( reversedDepth ) {
  9458. c = near / ( far - near );
  9459. d = ( far * near ) / ( far - near );
  9460. } else {
  9461. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9462. c = - ( far + near ) / ( far - near );
  9463. d = ( -2 * far * near ) / ( far - near );
  9464. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9465. c = - far / ( far - near );
  9466. d = ( - far * near ) / ( far - near );
  9467. } else {
  9468. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9469. }
  9470. }
  9471. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9472. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9473. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9474. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9475. return this;
  9476. }
  9477. /**
  9478. * Creates a orthographic projection matrix. This is used internally by
  9479. * {@link OrthographicCamera#updateProjectionMatrix}.
  9480. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9481. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9482. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9483. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9484. * @param {number} near - The distance from the camera to the near plane.
  9485. * @param {number} far - The distance from the camera to the far plane.
  9486. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9487. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9488. * @return {Matrix4} A reference to this matrix.
  9489. */
  9490. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9491. const te = this.elements;
  9492. const x = 2 / ( right - left );
  9493. const y = 2 / ( top - bottom );
  9494. const a = - ( right + left ) / ( right - left );
  9495. const b = - ( top + bottom ) / ( top - bottom );
  9496. let c, d;
  9497. if ( reversedDepth ) {
  9498. c = 1 / ( far - near );
  9499. d = far / ( far - near );
  9500. } else {
  9501. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9502. c = -2 / ( far - near );
  9503. d = - ( far + near ) / ( far - near );
  9504. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9505. c = -1 / ( far - near );
  9506. d = - near / ( far - near );
  9507. } else {
  9508. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9509. }
  9510. }
  9511. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9512. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9513. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9514. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9515. return this;
  9516. }
  9517. /**
  9518. * Returns `true` if this matrix is equal with the given one.
  9519. *
  9520. * @param {Matrix4} matrix - The matrix to test for equality.
  9521. * @return {boolean} Whether this matrix is equal with the given one.
  9522. */
  9523. equals( matrix ) {
  9524. const te = this.elements;
  9525. const me = matrix.elements;
  9526. for ( let i = 0; i < 16; i ++ ) {
  9527. if ( te[ i ] !== me[ i ] ) return false;
  9528. }
  9529. return true;
  9530. }
  9531. /**
  9532. * Sets the elements of the matrix from the given array.
  9533. *
  9534. * @param {Array<number>} array - The matrix elements in column-major order.
  9535. * @param {number} [offset=0] - Index of the first element in the array.
  9536. * @return {Matrix4} A reference to this matrix.
  9537. */
  9538. fromArray( array, offset = 0 ) {
  9539. for ( let i = 0; i < 16; i ++ ) {
  9540. this.elements[ i ] = array[ i + offset ];
  9541. }
  9542. return this;
  9543. }
  9544. /**
  9545. * Writes the elements of this matrix to the given array. If no array is provided,
  9546. * the method returns a new instance.
  9547. *
  9548. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9549. * @param {number} [offset=0] - Index of the first element in the array.
  9550. * @return {Array<number>} The matrix elements in column-major order.
  9551. */
  9552. toArray( array = [], offset = 0 ) {
  9553. const te = this.elements;
  9554. array[ offset ] = te[ 0 ];
  9555. array[ offset + 1 ] = te[ 1 ];
  9556. array[ offset + 2 ] = te[ 2 ];
  9557. array[ offset + 3 ] = te[ 3 ];
  9558. array[ offset + 4 ] = te[ 4 ];
  9559. array[ offset + 5 ] = te[ 5 ];
  9560. array[ offset + 6 ] = te[ 6 ];
  9561. array[ offset + 7 ] = te[ 7 ];
  9562. array[ offset + 8 ] = te[ 8 ];
  9563. array[ offset + 9 ] = te[ 9 ];
  9564. array[ offset + 10 ] = te[ 10 ];
  9565. array[ offset + 11 ] = te[ 11 ];
  9566. array[ offset + 12 ] = te[ 12 ];
  9567. array[ offset + 13 ] = te[ 13 ];
  9568. array[ offset + 14 ] = te[ 14 ];
  9569. array[ offset + 15 ] = te[ 15 ];
  9570. return array;
  9571. }
  9572. }
  9573. const _v1$5 = /*@__PURE__*/ new Vector3();
  9574. const _m1$2 = /*@__PURE__*/ new Matrix4();
  9575. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9576. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9577. const _x = /*@__PURE__*/ new Vector3();
  9578. const _y = /*@__PURE__*/ new Vector3();
  9579. const _z = /*@__PURE__*/ new Vector3();
  9580. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9581. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9582. /**
  9583. * A class representing Euler angles.
  9584. *
  9585. * Euler angles describe a rotational transformation by rotating an object on
  9586. * its various axes in specified amounts per axis, and a specified axis
  9587. * order.
  9588. *
  9589. * Iterating through an instance will yield its components (x, y, z,
  9590. * order) in the corresponding order.
  9591. *
  9592. * ```js
  9593. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9594. * const b = new THREE.Vector3( 1, 0, 1 );
  9595. * b.applyEuler(a);
  9596. * ```
  9597. */
  9598. class Euler {
  9599. /**
  9600. * Constructs a new euler instance.
  9601. *
  9602. * @param {number} [x=0] - The angle of the x axis in radians.
  9603. * @param {number} [y=0] - The angle of the y axis in radians.
  9604. * @param {number} [z=0] - The angle of the z axis in radians.
  9605. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9606. */
  9607. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9608. /**
  9609. * This flag can be used for type testing.
  9610. *
  9611. * @type {boolean}
  9612. * @readonly
  9613. * @default true
  9614. */
  9615. this.isEuler = true;
  9616. this._x = x;
  9617. this._y = y;
  9618. this._z = z;
  9619. this._order = order;
  9620. }
  9621. /**
  9622. * The angle of the x axis in radians.
  9623. *
  9624. * @type {number}
  9625. * @default 0
  9626. */
  9627. get x() {
  9628. return this._x;
  9629. }
  9630. set x( value ) {
  9631. this._x = value;
  9632. this._onChangeCallback();
  9633. }
  9634. /**
  9635. * The angle of the y axis in radians.
  9636. *
  9637. * @type {number}
  9638. * @default 0
  9639. */
  9640. get y() {
  9641. return this._y;
  9642. }
  9643. set y( value ) {
  9644. this._y = value;
  9645. this._onChangeCallback();
  9646. }
  9647. /**
  9648. * The angle of the z axis in radians.
  9649. *
  9650. * @type {number}
  9651. * @default 0
  9652. */
  9653. get z() {
  9654. return this._z;
  9655. }
  9656. set z( value ) {
  9657. this._z = value;
  9658. this._onChangeCallback();
  9659. }
  9660. /**
  9661. * A string representing the order that the rotations are applied.
  9662. *
  9663. * @type {string}
  9664. * @default 'XYZ'
  9665. */
  9666. get order() {
  9667. return this._order;
  9668. }
  9669. set order( value ) {
  9670. this._order = value;
  9671. this._onChangeCallback();
  9672. }
  9673. /**
  9674. * Sets the Euler components.
  9675. *
  9676. * @param {number} x - The angle of the x axis in radians.
  9677. * @param {number} y - The angle of the y axis in radians.
  9678. * @param {number} z - The angle of the z axis in radians.
  9679. * @param {string} [order] - A string representing the order that the rotations are applied.
  9680. * @return {Euler} A reference to this Euler instance.
  9681. */
  9682. set( x, y, z, order = this._order ) {
  9683. this._x = x;
  9684. this._y = y;
  9685. this._z = z;
  9686. this._order = order;
  9687. this._onChangeCallback();
  9688. return this;
  9689. }
  9690. /**
  9691. * Returns a new Euler instance with copied values from this instance.
  9692. *
  9693. * @return {Euler} A clone of this instance.
  9694. */
  9695. clone() {
  9696. return new this.constructor( this._x, this._y, this._z, this._order );
  9697. }
  9698. /**
  9699. * Copies the values of the given Euler instance to this instance.
  9700. *
  9701. * @param {Euler} euler - The Euler instance to copy.
  9702. * @return {Euler} A reference to this Euler instance.
  9703. */
  9704. copy( euler ) {
  9705. this._x = euler._x;
  9706. this._y = euler._y;
  9707. this._z = euler._z;
  9708. this._order = euler._order;
  9709. this._onChangeCallback();
  9710. return this;
  9711. }
  9712. /**
  9713. * Sets the angles of this Euler instance from a pure rotation matrix.
  9714. *
  9715. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9716. * @param {string} [order] - A string representing the order that the rotations are applied.
  9717. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9718. * @return {Euler} A reference to this Euler instance.
  9719. */
  9720. setFromRotationMatrix( m, order = this._order, update = true ) {
  9721. const te = m.elements;
  9722. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9723. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9724. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9725. switch ( order ) {
  9726. case 'XYZ':
  9727. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9728. if ( Math.abs( m13 ) < 0.9999999 ) {
  9729. this._x = Math.atan2( - m23, m33 );
  9730. this._z = Math.atan2( - m12, m11 );
  9731. } else {
  9732. this._x = Math.atan2( m32, m22 );
  9733. this._z = 0;
  9734. }
  9735. break;
  9736. case 'YXZ':
  9737. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9738. if ( Math.abs( m23 ) < 0.9999999 ) {
  9739. this._y = Math.atan2( m13, m33 );
  9740. this._z = Math.atan2( m21, m22 );
  9741. } else {
  9742. this._y = Math.atan2( - m31, m11 );
  9743. this._z = 0;
  9744. }
  9745. break;
  9746. case 'ZXY':
  9747. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9748. if ( Math.abs( m32 ) < 0.9999999 ) {
  9749. this._y = Math.atan2( - m31, m33 );
  9750. this._z = Math.atan2( - m12, m22 );
  9751. } else {
  9752. this._y = 0;
  9753. this._z = Math.atan2( m21, m11 );
  9754. }
  9755. break;
  9756. case 'ZYX':
  9757. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9758. if ( Math.abs( m31 ) < 0.9999999 ) {
  9759. this._x = Math.atan2( m32, m33 );
  9760. this._z = Math.atan2( m21, m11 );
  9761. } else {
  9762. this._x = 0;
  9763. this._z = Math.atan2( - m12, m22 );
  9764. }
  9765. break;
  9766. case 'YZX':
  9767. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9768. if ( Math.abs( m21 ) < 0.9999999 ) {
  9769. this._x = Math.atan2( - m23, m22 );
  9770. this._y = Math.atan2( - m31, m11 );
  9771. } else {
  9772. this._x = 0;
  9773. this._y = Math.atan2( m13, m33 );
  9774. }
  9775. break;
  9776. case 'XZY':
  9777. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9778. if ( Math.abs( m12 ) < 0.9999999 ) {
  9779. this._x = Math.atan2( m32, m22 );
  9780. this._y = Math.atan2( m13, m11 );
  9781. } else {
  9782. this._x = Math.atan2( - m23, m33 );
  9783. this._y = 0;
  9784. }
  9785. break;
  9786. default:
  9787. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9788. }
  9789. this._order = order;
  9790. if ( update === true ) this._onChangeCallback();
  9791. return this;
  9792. }
  9793. /**
  9794. * Sets the angles of this Euler instance from a normalized quaternion.
  9795. *
  9796. * @param {Quaternion} q - A normalized Quaternion.
  9797. * @param {string} [order] - A string representing the order that the rotations are applied.
  9798. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9799. * @return {Euler} A reference to this Euler instance.
  9800. */
  9801. setFromQuaternion( q, order, update ) {
  9802. _matrix$2.makeRotationFromQuaternion( q );
  9803. return this.setFromRotationMatrix( _matrix$2, order, update );
  9804. }
  9805. /**
  9806. * Sets the angles of this Euler instance from the given vector.
  9807. *
  9808. * @param {Vector3} v - The vector.
  9809. * @param {string} [order] - A string representing the order that the rotations are applied.
  9810. * @return {Euler} A reference to this Euler instance.
  9811. */
  9812. setFromVector3( v, order = this._order ) {
  9813. return this.set( v.x, v.y, v.z, order );
  9814. }
  9815. /**
  9816. * Resets the euler angle with a new order by creating a quaternion from this
  9817. * euler angle and then setting this euler angle with the quaternion and the
  9818. * new order.
  9819. *
  9820. * Warning: This discards revolution information.
  9821. *
  9822. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9823. * @return {Euler} A reference to this Euler instance.
  9824. */
  9825. reorder( newOrder ) {
  9826. _quaternion$3.setFromEuler( this );
  9827. return this.setFromQuaternion( _quaternion$3, newOrder );
  9828. }
  9829. /**
  9830. * Returns `true` if this Euler instance is equal with the given one.
  9831. *
  9832. * @param {Euler} euler - The Euler instance to test for equality.
  9833. * @return {boolean} Whether this Euler instance is equal with the given one.
  9834. */
  9835. equals( euler ) {
  9836. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9837. }
  9838. /**
  9839. * Sets this Euler instance's components to values from the given array. The first three
  9840. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9841. * defines the Euler order.
  9842. *
  9843. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9844. * @return {Euler} A reference to this Euler instance.
  9845. */
  9846. fromArray( array ) {
  9847. this._x = array[ 0 ];
  9848. this._y = array[ 1 ];
  9849. this._z = array[ 2 ];
  9850. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9851. this._onChangeCallback();
  9852. return this;
  9853. }
  9854. /**
  9855. * Writes the components of this Euler instance to the given array. If no array is provided,
  9856. * the method returns a new instance.
  9857. *
  9858. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9859. * @param {number} [offset=0] - Index of the first element in the array.
  9860. * @return {Array<number,number,number,string>} The Euler components.
  9861. */
  9862. toArray( array = [], offset = 0 ) {
  9863. array[ offset ] = this._x;
  9864. array[ offset + 1 ] = this._y;
  9865. array[ offset + 2 ] = this._z;
  9866. array[ offset + 3 ] = this._order;
  9867. return array;
  9868. }
  9869. _onChange( callback ) {
  9870. this._onChangeCallback = callback;
  9871. return this;
  9872. }
  9873. _onChangeCallback() {}
  9874. *[ Symbol.iterator ]() {
  9875. yield this._x;
  9876. yield this._y;
  9877. yield this._z;
  9878. yield this._order;
  9879. }
  9880. }
  9881. /**
  9882. * The default Euler angle order.
  9883. *
  9884. * @static
  9885. * @type {string}
  9886. * @default 'XYZ'
  9887. */
  9888. Euler.DEFAULT_ORDER = 'XYZ';
  9889. /**
  9890. * A layers object assigns an 3D object to 1 or more of 32
  9891. * layers numbered `0` to `31` - internally the layers are stored as a
  9892. * bit mask], and by default all 3D objects are a member of layer `0`.
  9893. *
  9894. * This can be used to control visibility - an object must share a layer with
  9895. * a camera to be visible when that camera's view is
  9896. * rendered.
  9897. *
  9898. * All classes that inherit from {@link Object3D} have an `layers` property which
  9899. * is an instance of this class.
  9900. */
  9901. class Layers {
  9902. /**
  9903. * Constructs a new layers instance, with membership
  9904. * initially set to layer `0`.
  9905. */
  9906. constructor() {
  9907. /**
  9908. * A bit mask storing which of the 32 layers this layers object is currently
  9909. * a member of.
  9910. *
  9911. * @type {number}
  9912. */
  9913. this.mask = 1 | 0;
  9914. }
  9915. /**
  9916. * Sets membership to the given layer, and remove membership all other layers.
  9917. *
  9918. * @param {number} layer - The layer to set.
  9919. */
  9920. set( layer ) {
  9921. this.mask = ( 1 << layer | 0 ) >>> 0;
  9922. }
  9923. /**
  9924. * Adds membership of the given layer.
  9925. *
  9926. * @param {number} layer - The layer to enable.
  9927. */
  9928. enable( layer ) {
  9929. this.mask |= 1 << layer | 0;
  9930. }
  9931. /**
  9932. * Adds membership to all layers.
  9933. */
  9934. enableAll() {
  9935. this.mask = 0xffffffff | 0;
  9936. }
  9937. /**
  9938. * Toggles the membership of the given layer.
  9939. *
  9940. * @param {number} layer - The layer to toggle.
  9941. */
  9942. toggle( layer ) {
  9943. this.mask ^= 1 << layer | 0;
  9944. }
  9945. /**
  9946. * Removes membership of the given layer.
  9947. *
  9948. * @param {number} layer - The layer to enable.
  9949. */
  9950. disable( layer ) {
  9951. this.mask &= ~ ( 1 << layer | 0 );
  9952. }
  9953. /**
  9954. * Removes the membership from all layers.
  9955. */
  9956. disableAll() {
  9957. this.mask = 0;
  9958. }
  9959. /**
  9960. * Returns `true` if this and the given layers object have at least one
  9961. * layer in common.
  9962. *
  9963. * @param {Layers} layers - The layers to test.
  9964. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  9965. */
  9966. test( layers ) {
  9967. return ( this.mask & layers.mask ) !== 0;
  9968. }
  9969. /**
  9970. * Returns `true` if the given layer is enabled.
  9971. *
  9972. * @param {number} layer - The layer to test.
  9973. * @return {boolean } Whether the given layer is enabled or not.
  9974. */
  9975. isEnabled( layer ) {
  9976. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  9977. }
  9978. }
  9979. let _object3DId = 0;
  9980. const _v1$4 = /*@__PURE__*/ new Vector3();
  9981. const _q1 = /*@__PURE__*/ new Quaternion();
  9982. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9983. const _target = /*@__PURE__*/ new Vector3();
  9984. const _position$3 = /*@__PURE__*/ new Vector3();
  9985. const _scale$2 = /*@__PURE__*/ new Vector3();
  9986. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  9987. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  9988. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  9989. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  9990. /**
  9991. * Fires when the object has been added to its parent object.
  9992. *
  9993. * @event Object3D#added
  9994. * @type {Object}
  9995. */
  9996. const _addedEvent = { type: 'added' };
  9997. /**
  9998. * Fires when the object has been removed from its parent object.
  9999. *
  10000. * @event Object3D#removed
  10001. * @type {Object}
  10002. */
  10003. const _removedEvent = { type: 'removed' };
  10004. /**
  10005. * Fires when a new child object has been added.
  10006. *
  10007. * @event Object3D#childadded
  10008. * @type {Object}
  10009. */
  10010. const _childaddedEvent = { type: 'childadded', child: null };
  10011. /**
  10012. * Fires when a child object has been removed.
  10013. *
  10014. * @event Object3D#childremoved
  10015. * @type {Object}
  10016. */
  10017. const _childremovedEvent = { type: 'childremoved', child: null };
  10018. /**
  10019. * This is the base class for most objects in three.js and provides a set of
  10020. * properties and methods for manipulating objects in 3D space.
  10021. *
  10022. * @augments EventDispatcher
  10023. */
  10024. class Object3D extends EventDispatcher {
  10025. /**
  10026. * Constructs a new 3D object.
  10027. */
  10028. constructor() {
  10029. super();
  10030. /**
  10031. * This flag can be used for type testing.
  10032. *
  10033. * @type {boolean}
  10034. * @readonly
  10035. * @default true
  10036. */
  10037. this.isObject3D = true;
  10038. /**
  10039. * The ID of the 3D object.
  10040. *
  10041. * @name Object3D#id
  10042. * @type {number}
  10043. * @readonly
  10044. */
  10045. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10046. /**
  10047. * The UUID of the 3D object.
  10048. *
  10049. * @type {string}
  10050. * @readonly
  10051. */
  10052. this.uuid = generateUUID();
  10053. /**
  10054. * The name of the 3D object.
  10055. *
  10056. * @type {string}
  10057. */
  10058. this.name = '';
  10059. /**
  10060. * The type property is used for detecting the object type
  10061. * in context of serialization/deserialization.
  10062. *
  10063. * @type {string}
  10064. * @readonly
  10065. */
  10066. this.type = 'Object3D';
  10067. /**
  10068. * A reference to the parent object.
  10069. *
  10070. * @type {?Object3D}
  10071. * @default null
  10072. */
  10073. this.parent = null;
  10074. /**
  10075. * An array holding the child 3D objects of this instance.
  10076. *
  10077. * @type {Array<Object3D>}
  10078. */
  10079. this.children = [];
  10080. /**
  10081. * Defines the `up` direction of the 3D object which influences
  10082. * the orientation via methods like {@link Object3D#lookAt}.
  10083. *
  10084. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10085. *
  10086. * @type {Vector3}
  10087. */
  10088. this.up = Object3D.DEFAULT_UP.clone();
  10089. const position = new Vector3();
  10090. const rotation = new Euler();
  10091. const quaternion = new Quaternion();
  10092. const scale = new Vector3( 1, 1, 1 );
  10093. function onRotationChange() {
  10094. quaternion.setFromEuler( rotation, false );
  10095. }
  10096. function onQuaternionChange() {
  10097. rotation.setFromQuaternion( quaternion, undefined, false );
  10098. }
  10099. rotation._onChange( onRotationChange );
  10100. quaternion._onChange( onQuaternionChange );
  10101. Object.defineProperties( this, {
  10102. /**
  10103. * Represents the object's local position.
  10104. *
  10105. * @name Object3D#position
  10106. * @type {Vector3}
  10107. * @default (0,0,0)
  10108. */
  10109. position: {
  10110. configurable: true,
  10111. enumerable: true,
  10112. value: position
  10113. },
  10114. /**
  10115. * Represents the object's local rotation as Euler angles, in radians.
  10116. *
  10117. * @name Object3D#rotation
  10118. * @type {Euler}
  10119. * @default (0,0,0)
  10120. */
  10121. rotation: {
  10122. configurable: true,
  10123. enumerable: true,
  10124. value: rotation
  10125. },
  10126. /**
  10127. * Represents the object's local rotation as Quaternions.
  10128. *
  10129. * @name Object3D#quaternion
  10130. * @type {Quaternion}
  10131. */
  10132. quaternion: {
  10133. configurable: true,
  10134. enumerable: true,
  10135. value: quaternion
  10136. },
  10137. /**
  10138. * Represents the object's local scale.
  10139. *
  10140. * @name Object3D#scale
  10141. * @type {Vector3}
  10142. * @default (1,1,1)
  10143. */
  10144. scale: {
  10145. configurable: true,
  10146. enumerable: true,
  10147. value: scale
  10148. },
  10149. /**
  10150. * Represents the object's model-view matrix.
  10151. *
  10152. * @name Object3D#modelViewMatrix
  10153. * @type {Matrix4}
  10154. */
  10155. modelViewMatrix: {
  10156. value: new Matrix4()
  10157. },
  10158. /**
  10159. * Represents the object's normal matrix.
  10160. *
  10161. * @name Object3D#normalMatrix
  10162. * @type {Matrix3}
  10163. */
  10164. normalMatrix: {
  10165. value: new Matrix3()
  10166. }
  10167. } );
  10168. /**
  10169. * Represents the object's transformation matrix in local space.
  10170. *
  10171. * @type {Matrix4}
  10172. */
  10173. this.matrix = new Matrix4();
  10174. /**
  10175. * Represents the object's transformation matrix in world space.
  10176. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10177. *
  10178. * @type {Matrix4}
  10179. */
  10180. this.matrixWorld = new Matrix4();
  10181. /**
  10182. * When set to `true`, the engine automatically computes the local matrix from position,
  10183. * rotation and scale every frame.
  10184. *
  10185. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10186. *
  10187. * @type {boolean}
  10188. * @default true
  10189. */
  10190. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10191. /**
  10192. * When set to `true`, the engine automatically computes the world matrix from the current local
  10193. * matrix and the object's transformation hierarchy.
  10194. *
  10195. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10196. *
  10197. * @type {boolean}
  10198. * @default true
  10199. */
  10200. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10201. /**
  10202. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10203. * to `false`.
  10204. *
  10205. * @type {boolean}
  10206. * @default false
  10207. */
  10208. this.matrixWorldNeedsUpdate = false;
  10209. /**
  10210. * The layer membership of the 3D object. The 3D object is only visible if it has
  10211. * at least one layer in common with the camera in use. This property can also be
  10212. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10213. *
  10214. * @type {Layers}
  10215. */
  10216. this.layers = new Layers();
  10217. /**
  10218. * When set to `true`, the 3D object gets rendered.
  10219. *
  10220. * @type {boolean}
  10221. * @default true
  10222. */
  10223. this.visible = true;
  10224. /**
  10225. * When set to `true`, the 3D object gets rendered into shadow maps.
  10226. *
  10227. * @type {boolean}
  10228. * @default false
  10229. */
  10230. this.castShadow = false;
  10231. /**
  10232. * When set to `true`, the 3D object is affected by shadows in the scene.
  10233. *
  10234. * @type {boolean}
  10235. * @default false
  10236. */
  10237. this.receiveShadow = false;
  10238. /**
  10239. * When set to `true`, the 3D object is honored by view frustum culling.
  10240. *
  10241. * @type {boolean}
  10242. * @default true
  10243. */
  10244. this.frustumCulled = true;
  10245. /**
  10246. * This value allows the default rendering order of scene graph objects to be
  10247. * overridden although opaque and transparent objects remain sorted independently.
  10248. * When this property is set for an instance of {@link Group},all descendants
  10249. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10250. * render order.
  10251. *
  10252. * @type {number}
  10253. * @default 0
  10254. */
  10255. this.renderOrder = 0;
  10256. /**
  10257. * An array holding the animation clips of the 3D object.
  10258. *
  10259. * @type {Array<AnimationClip>}
  10260. */
  10261. this.animations = [];
  10262. /**
  10263. * Custom depth material to be used when rendering to the depth map. Can only be used
  10264. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10265. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10266. * material for proper shadows.
  10267. *
  10268. * Only relevant in context of {@link WebGLRenderer}.
  10269. *
  10270. * @type {(Material|undefined)}
  10271. * @default undefined
  10272. */
  10273. this.customDepthMaterial = undefined;
  10274. /**
  10275. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10276. *
  10277. * Only relevant in context of {@link WebGLRenderer}.
  10278. *
  10279. * @type {(Material|undefined)}
  10280. * @default undefined
  10281. */
  10282. this.customDistanceMaterial = undefined;
  10283. /**
  10284. * An object that can be used to store custom data about the 3D object. It
  10285. * should not hold references to functions as these will not be cloned.
  10286. *
  10287. * @type {Object}
  10288. */
  10289. this.userData = {};
  10290. }
  10291. /**
  10292. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10293. *
  10294. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10295. * @param {Object3D} object - The 3D object.
  10296. * @param {Camera} camera - The camera that is used to render the scene.
  10297. * @param {Camera} shadowCamera - The shadow camera.
  10298. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10299. * @param {Material} depthMaterial - The depth material.
  10300. * @param {Object} group - The geometry group data.
  10301. */
  10302. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10303. /**
  10304. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10305. *
  10306. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10307. * @param {Object3D} object - The 3D object.
  10308. * @param {Camera} camera - The camera that is used to render the scene.
  10309. * @param {Camera} shadowCamera - The shadow camera.
  10310. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10311. * @param {Material} depthMaterial - The depth material.
  10312. * @param {Object} group - The geometry group data.
  10313. */
  10314. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10315. /**
  10316. * A callback that is executed immediately before a 3D object is rendered.
  10317. *
  10318. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10319. * @param {Object3D} object - The 3D object.
  10320. * @param {Camera} camera - The camera that is used to render the scene.
  10321. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10322. * @param {Material} material - The 3D object's material.
  10323. * @param {Object} group - The geometry group data.
  10324. */
  10325. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10326. /**
  10327. * A callback that is executed immediately after a 3D object is rendered.
  10328. *
  10329. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10330. * @param {Object3D} object - The 3D object.
  10331. * @param {Camera} camera - The camera that is used to render the scene.
  10332. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10333. * @param {Material} material - The 3D object's material.
  10334. * @param {Object} group - The geometry group data.
  10335. */
  10336. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10337. /**
  10338. * Applies the given transformation matrix to the object and updates the object's position,
  10339. * rotation and scale.
  10340. *
  10341. * @param {Matrix4} matrix - The transformation matrix.
  10342. */
  10343. applyMatrix4( matrix ) {
  10344. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10345. this.matrix.premultiply( matrix );
  10346. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10347. }
  10348. /**
  10349. * Applies a rotation represented by given the quaternion to the 3D object.
  10350. *
  10351. * @param {Quaternion} q - The quaternion.
  10352. * @return {Object3D} A reference to this instance.
  10353. */
  10354. applyQuaternion( q ) {
  10355. this.quaternion.premultiply( q );
  10356. return this;
  10357. }
  10358. /**
  10359. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10360. *
  10361. * @param {Vector3} axis - The (normalized) axis vector.
  10362. * @param {number} angle - The angle in radians.
  10363. */
  10364. setRotationFromAxisAngle( axis, angle ) {
  10365. // assumes axis is normalized
  10366. this.quaternion.setFromAxisAngle( axis, angle );
  10367. }
  10368. /**
  10369. * Sets the given rotation represented as Euler angles to the 3D object.
  10370. *
  10371. * @param {Euler} euler - The Euler angles.
  10372. */
  10373. setRotationFromEuler( euler ) {
  10374. this.quaternion.setFromEuler( euler, true );
  10375. }
  10376. /**
  10377. * Sets the given rotation represented as rotation matrix to the 3D object.
  10378. *
  10379. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10380. * a pure rotation matrix (i.e, unscaled).
  10381. */
  10382. setRotationFromMatrix( m ) {
  10383. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10384. this.quaternion.setFromRotationMatrix( m );
  10385. }
  10386. /**
  10387. * Sets the given rotation represented as a Quaternion to the 3D object.
  10388. *
  10389. * @param {Quaternion} q - The Quaternion
  10390. */
  10391. setRotationFromQuaternion( q ) {
  10392. // assumes q is normalized
  10393. this.quaternion.copy( q );
  10394. }
  10395. /**
  10396. * Rotates the 3D object along an axis in local space.
  10397. *
  10398. * @param {Vector3} axis - The (normalized) axis vector.
  10399. * @param {number} angle - The angle in radians.
  10400. * @return {Object3D} A reference to this instance.
  10401. */
  10402. rotateOnAxis( axis, angle ) {
  10403. // rotate object on axis in object space
  10404. // axis is assumed to be normalized
  10405. _q1.setFromAxisAngle( axis, angle );
  10406. this.quaternion.multiply( _q1 );
  10407. return this;
  10408. }
  10409. /**
  10410. * Rotates the 3D object along an axis in world space.
  10411. *
  10412. * @param {Vector3} axis - The (normalized) axis vector.
  10413. * @param {number} angle - The angle in radians.
  10414. * @return {Object3D} A reference to this instance.
  10415. */
  10416. rotateOnWorldAxis( axis, angle ) {
  10417. // rotate object on axis in world space
  10418. // axis is assumed to be normalized
  10419. // method assumes no rotated parent
  10420. _q1.setFromAxisAngle( axis, angle );
  10421. this.quaternion.premultiply( _q1 );
  10422. return this;
  10423. }
  10424. /**
  10425. * Rotates the 3D object around its X axis in local space.
  10426. *
  10427. * @param {number} angle - The angle in radians.
  10428. * @return {Object3D} A reference to this instance.
  10429. */
  10430. rotateX( angle ) {
  10431. return this.rotateOnAxis( _xAxis, angle );
  10432. }
  10433. /**
  10434. * Rotates the 3D object around its Y axis in local space.
  10435. *
  10436. * @param {number} angle - The angle in radians.
  10437. * @return {Object3D} A reference to this instance.
  10438. */
  10439. rotateY( angle ) {
  10440. return this.rotateOnAxis( _yAxis, angle );
  10441. }
  10442. /**
  10443. * Rotates the 3D object around its Z axis in local space.
  10444. *
  10445. * @param {number} angle - The angle in radians.
  10446. * @return {Object3D} A reference to this instance.
  10447. */
  10448. rotateZ( angle ) {
  10449. return this.rotateOnAxis( _zAxis, angle );
  10450. }
  10451. /**
  10452. * Translate the 3D object by a distance along the given axis in local space.
  10453. *
  10454. * @param {Vector3} axis - The (normalized) axis vector.
  10455. * @param {number} distance - The distance in world units.
  10456. * @return {Object3D} A reference to this instance.
  10457. */
  10458. translateOnAxis( axis, distance ) {
  10459. // translate object by distance along axis in object space
  10460. // axis is assumed to be normalized
  10461. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10462. this.position.add( _v1$4.multiplyScalar( distance ) );
  10463. return this;
  10464. }
  10465. /**
  10466. * Translate the 3D object by a distance along its X-axis in local space.
  10467. *
  10468. * @param {number} distance - The distance in world units.
  10469. * @return {Object3D} A reference to this instance.
  10470. */
  10471. translateX( distance ) {
  10472. return this.translateOnAxis( _xAxis, distance );
  10473. }
  10474. /**
  10475. * Translate the 3D object by a distance along its Y-axis in local space.
  10476. *
  10477. * @param {number} distance - The distance in world units.
  10478. * @return {Object3D} A reference to this instance.
  10479. */
  10480. translateY( distance ) {
  10481. return this.translateOnAxis( _yAxis, distance );
  10482. }
  10483. /**
  10484. * Translate the 3D object by a distance along its Z-axis in local space.
  10485. *
  10486. * @param {number} distance - The distance in world units.
  10487. * @return {Object3D} A reference to this instance.
  10488. */
  10489. translateZ( distance ) {
  10490. return this.translateOnAxis( _zAxis, distance );
  10491. }
  10492. /**
  10493. * Converts the given vector from this 3D object's local space to world space.
  10494. *
  10495. * @param {Vector3} vector - The vector to convert.
  10496. * @return {Vector3} The converted vector.
  10497. */
  10498. localToWorld( vector ) {
  10499. this.updateWorldMatrix( true, false );
  10500. return vector.applyMatrix4( this.matrixWorld );
  10501. }
  10502. /**
  10503. * Converts the given vector from this 3D object's word space to local space.
  10504. *
  10505. * @param {Vector3} vector - The vector to convert.
  10506. * @return {Vector3} The converted vector.
  10507. */
  10508. worldToLocal( vector ) {
  10509. this.updateWorldMatrix( true, false );
  10510. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  10511. }
  10512. /**
  10513. * Rotates the object to face a point in world space.
  10514. *
  10515. * This method does not support objects having non-uniformly-scaled parent(s).
  10516. *
  10517. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10518. * @param {number} [y] - The y coordinate in world space.
  10519. * @param {number} [z] - The z coordinate in world space.
  10520. */
  10521. lookAt( x, y, z ) {
  10522. // This method does not support objects having non-uniformly-scaled parent(s)
  10523. if ( x.isVector3 ) {
  10524. _target.copy( x );
  10525. } else {
  10526. _target.set( x, y, z );
  10527. }
  10528. const parent = this.parent;
  10529. this.updateWorldMatrix( true, false );
  10530. _position$3.setFromMatrixPosition( this.matrixWorld );
  10531. if ( this.isCamera || this.isLight ) {
  10532. _m1$1.lookAt( _position$3, _target, this.up );
  10533. } else {
  10534. _m1$1.lookAt( _target, _position$3, this.up );
  10535. }
  10536. this.quaternion.setFromRotationMatrix( _m1$1 );
  10537. if ( parent ) {
  10538. _m1$1.extractRotation( parent.matrixWorld );
  10539. _q1.setFromRotationMatrix( _m1$1 );
  10540. this.quaternion.premultiply( _q1.invert() );
  10541. }
  10542. }
  10543. /**
  10544. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10545. * objects may be added. Any current parent on an object passed in here will be
  10546. * removed, since an object can have at most one parent.
  10547. *
  10548. * @fires Object3D#added
  10549. * @fires Object3D#childadded
  10550. * @param {Object3D} object - The 3D object to add.
  10551. * @return {Object3D} A reference to this instance.
  10552. */
  10553. add( object ) {
  10554. if ( arguments.length > 1 ) {
  10555. for ( let i = 0; i < arguments.length; i ++ ) {
  10556. this.add( arguments[ i ] );
  10557. }
  10558. return this;
  10559. }
  10560. if ( object === this ) {
  10561. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  10562. return this;
  10563. }
  10564. if ( object && object.isObject3D ) {
  10565. object.removeFromParent();
  10566. object.parent = this;
  10567. this.children.push( object );
  10568. object.dispatchEvent( _addedEvent );
  10569. _childaddedEvent.child = object;
  10570. this.dispatchEvent( _childaddedEvent );
  10571. _childaddedEvent.child = null;
  10572. } else {
  10573. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  10574. }
  10575. return this;
  10576. }
  10577. /**
  10578. * Removes the given 3D object as child from this 3D object.
  10579. * An arbitrary number of objects may be removed.
  10580. *
  10581. * @fires Object3D#removed
  10582. * @fires Object3D#childremoved
  10583. * @param {Object3D} object - The 3D object to remove.
  10584. * @return {Object3D} A reference to this instance.
  10585. */
  10586. remove( object ) {
  10587. if ( arguments.length > 1 ) {
  10588. for ( let i = 0; i < arguments.length; i ++ ) {
  10589. this.remove( arguments[ i ] );
  10590. }
  10591. return this;
  10592. }
  10593. const index = this.children.indexOf( object );
  10594. if ( index !== -1 ) {
  10595. object.parent = null;
  10596. this.children.splice( index, 1 );
  10597. object.dispatchEvent( _removedEvent );
  10598. _childremovedEvent.child = object;
  10599. this.dispatchEvent( _childremovedEvent );
  10600. _childremovedEvent.child = null;
  10601. }
  10602. return this;
  10603. }
  10604. /**
  10605. * Removes this 3D object from its current parent.
  10606. *
  10607. * @fires Object3D#removed
  10608. * @fires Object3D#childremoved
  10609. * @return {Object3D} A reference to this instance.
  10610. */
  10611. removeFromParent() {
  10612. const parent = this.parent;
  10613. if ( parent !== null ) {
  10614. parent.remove( this );
  10615. }
  10616. return this;
  10617. }
  10618. /**
  10619. * Removes all child objects.
  10620. *
  10621. * @fires Object3D#removed
  10622. * @fires Object3D#childremoved
  10623. * @return {Object3D} A reference to this instance.
  10624. */
  10625. clear() {
  10626. return this.remove( ... this.children );
  10627. }
  10628. /**
  10629. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10630. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10631. *
  10632. * @fires Object3D#added
  10633. * @fires Object3D#childadded
  10634. * @param {Object3D} object - The 3D object to attach.
  10635. * @return {Object3D} A reference to this instance.
  10636. */
  10637. attach( object ) {
  10638. // adds object as a child of this, while maintaining the object's world transform
  10639. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10640. this.updateWorldMatrix( true, false );
  10641. _m1$1.copy( this.matrixWorld ).invert();
  10642. if ( object.parent !== null ) {
  10643. object.parent.updateWorldMatrix( true, false );
  10644. _m1$1.multiply( object.parent.matrixWorld );
  10645. }
  10646. object.applyMatrix4( _m1$1 );
  10647. object.removeFromParent();
  10648. object.parent = this;
  10649. this.children.push( object );
  10650. object.updateWorldMatrix( false, true );
  10651. object.dispatchEvent( _addedEvent );
  10652. _childaddedEvent.child = object;
  10653. this.dispatchEvent( _childaddedEvent );
  10654. _childaddedEvent.child = null;
  10655. return this;
  10656. }
  10657. /**
  10658. * Searches through the 3D object and its children, starting with the 3D object
  10659. * itself, and returns the first with a matching ID.
  10660. *
  10661. * @param {number} id - The id.
  10662. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10663. */
  10664. getObjectById( id ) {
  10665. return this.getObjectByProperty( 'id', id );
  10666. }
  10667. /**
  10668. * Searches through the 3D object and its children, starting with the 3D object
  10669. * itself, and returns the first with a matching name.
  10670. *
  10671. * @param {string} name - The name.
  10672. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10673. */
  10674. getObjectByName( name ) {
  10675. return this.getObjectByProperty( 'name', name );
  10676. }
  10677. /**
  10678. * Searches through the 3D object and its children, starting with the 3D object
  10679. * itself, and returns the first with a matching property value.
  10680. *
  10681. * @param {string} name - The name of the property.
  10682. * @param {any} value - The value.
  10683. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10684. */
  10685. getObjectByProperty( name, value ) {
  10686. if ( this[ name ] === value ) return this;
  10687. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10688. const child = this.children[ i ];
  10689. const object = child.getObjectByProperty( name, value );
  10690. if ( object !== undefined ) {
  10691. return object;
  10692. }
  10693. }
  10694. return undefined;
  10695. }
  10696. /**
  10697. * Searches through the 3D object and its children, starting with the 3D object
  10698. * itself, and returns all 3D objects with a matching property value.
  10699. *
  10700. * @param {string} name - The name of the property.
  10701. * @param {any} value - The value.
  10702. * @param {Array<Object3D>} result - The method stores the result in this array.
  10703. * @return {Array<Object3D>} The found 3D objects.
  10704. */
  10705. getObjectsByProperty( name, value, result = [] ) {
  10706. if ( this[ name ] === value ) result.push( this );
  10707. const children = this.children;
  10708. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10709. children[ i ].getObjectsByProperty( name, value, result );
  10710. }
  10711. return result;
  10712. }
  10713. /**
  10714. * Returns a vector representing the position of the 3D object in world space.
  10715. *
  10716. * @param {Vector3} target - The target vector the result is stored to.
  10717. * @return {Vector3} The 3D object's position in world space.
  10718. */
  10719. getWorldPosition( target ) {
  10720. this.updateWorldMatrix( true, false );
  10721. return target.setFromMatrixPosition( this.matrixWorld );
  10722. }
  10723. /**
  10724. * Returns a Quaternion representing the position of the 3D object in world space.
  10725. *
  10726. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10727. * @return {Quaternion} The 3D object's rotation in world space.
  10728. */
  10729. getWorldQuaternion( target ) {
  10730. this.updateWorldMatrix( true, false );
  10731. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10732. return target;
  10733. }
  10734. /**
  10735. * Returns a vector representing the scale of the 3D object in world space.
  10736. *
  10737. * @param {Vector3} target - The target vector the result is stored to.
  10738. * @return {Vector3} The 3D object's scale in world space.
  10739. */
  10740. getWorldScale( target ) {
  10741. this.updateWorldMatrix( true, false );
  10742. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10743. return target;
  10744. }
  10745. /**
  10746. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10747. *
  10748. * @param {Vector3} target - The target vector the result is stored to.
  10749. * @return {Vector3} The 3D object's direction in world space.
  10750. */
  10751. getWorldDirection( target ) {
  10752. this.updateWorldMatrix( true, false );
  10753. const e = this.matrixWorld.elements;
  10754. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10755. }
  10756. /**
  10757. * Abstract method to get intersections between a casted ray and this
  10758. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10759. * implement this method in order to use raycasting.
  10760. *
  10761. * @abstract
  10762. * @param {Raycaster} raycaster - The raycaster.
  10763. * @param {Array<Object>} intersects - An array holding the result of the method.
  10764. */
  10765. raycast( /* raycaster, intersects */ ) {}
  10766. /**
  10767. * Executes the callback on this 3D object and all descendants.
  10768. *
  10769. * Note: Modifying the scene graph inside the callback is discouraged.
  10770. *
  10771. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10772. */
  10773. traverse( callback ) {
  10774. callback( this );
  10775. const children = this.children;
  10776. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10777. children[ i ].traverse( callback );
  10778. }
  10779. }
  10780. /**
  10781. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10782. * Descendants of invisible 3D objects are not traversed.
  10783. *
  10784. * Note: Modifying the scene graph inside the callback is discouraged.
  10785. *
  10786. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10787. */
  10788. traverseVisible( callback ) {
  10789. if ( this.visible === false ) return;
  10790. callback( this );
  10791. const children = this.children;
  10792. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10793. children[ i ].traverseVisible( callback );
  10794. }
  10795. }
  10796. /**
  10797. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10798. *
  10799. * Note: Modifying the scene graph inside the callback is discouraged.
  10800. *
  10801. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10802. */
  10803. traverseAncestors( callback ) {
  10804. const parent = this.parent;
  10805. if ( parent !== null ) {
  10806. callback( parent );
  10807. parent.traverseAncestors( callback );
  10808. }
  10809. }
  10810. /**
  10811. * Updates the transformation matrix in local space by computing it from the current
  10812. * position, rotation and scale values.
  10813. */
  10814. updateMatrix() {
  10815. this.matrix.compose( this.position, this.quaternion, this.scale );
  10816. this.matrixWorldNeedsUpdate = true;
  10817. }
  10818. /**
  10819. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10820. *
  10821. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10822. * local space. The computation of the local and world matrix can be controlled with the
  10823. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10824. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10825. *
  10826. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10827. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10828. */
  10829. updateMatrixWorld( force ) {
  10830. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10831. if ( this.matrixWorldNeedsUpdate || force ) {
  10832. if ( this.matrixWorldAutoUpdate === true ) {
  10833. if ( this.parent === null ) {
  10834. this.matrixWorld.copy( this.matrix );
  10835. } else {
  10836. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10837. }
  10838. }
  10839. this.matrixWorldNeedsUpdate = false;
  10840. force = true;
  10841. }
  10842. // make sure descendants are updated if required
  10843. const children = this.children;
  10844. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10845. const child = children[ i ];
  10846. child.updateMatrixWorld( force );
  10847. }
  10848. }
  10849. /**
  10850. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10851. * update of ancestor and descendant nodes.
  10852. *
  10853. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10854. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10855. */
  10856. updateWorldMatrix( updateParents, updateChildren ) {
  10857. const parent = this.parent;
  10858. if ( updateParents === true && parent !== null ) {
  10859. parent.updateWorldMatrix( true, false );
  10860. }
  10861. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10862. if ( this.matrixWorldAutoUpdate === true ) {
  10863. if ( this.parent === null ) {
  10864. this.matrixWorld.copy( this.matrix );
  10865. } else {
  10866. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10867. }
  10868. }
  10869. // make sure descendants are updated
  10870. if ( updateChildren === true ) {
  10871. const children = this.children;
  10872. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10873. const child = children[ i ];
  10874. child.updateWorldMatrix( false, true );
  10875. }
  10876. }
  10877. }
  10878. /**
  10879. * Serializes the 3D object into JSON.
  10880. *
  10881. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10882. * @return {Object} A JSON object representing the serialized 3D object.
  10883. * @see {@link ObjectLoader#parse}
  10884. */
  10885. toJSON( meta ) {
  10886. // meta is a string when called from JSON.stringify
  10887. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10888. const output = {};
  10889. // meta is a hash used to collect geometries, materials.
  10890. // not providing it implies that this is the root object
  10891. // being serialized.
  10892. if ( isRootObject ) {
  10893. // initialize meta obj
  10894. meta = {
  10895. geometries: {},
  10896. materials: {},
  10897. textures: {},
  10898. images: {},
  10899. shapes: {},
  10900. skeletons: {},
  10901. animations: {},
  10902. nodes: {}
  10903. };
  10904. output.metadata = {
  10905. version: 4.7,
  10906. type: 'Object',
  10907. generator: 'Object3D.toJSON'
  10908. };
  10909. }
  10910. // standard Object3D serialization
  10911. const object = {};
  10912. object.uuid = this.uuid;
  10913. object.type = this.type;
  10914. if ( this.name !== '' ) object.name = this.name;
  10915. if ( this.castShadow === true ) object.castShadow = true;
  10916. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10917. if ( this.visible === false ) object.visible = false;
  10918. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10919. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10920. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10921. object.layers = this.layers.mask;
  10922. object.matrix = this.matrix.toArray();
  10923. object.up = this.up.toArray();
  10924. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10925. // object specific properties
  10926. if ( this.isInstancedMesh ) {
  10927. object.type = 'InstancedMesh';
  10928. object.count = this.count;
  10929. object.instanceMatrix = this.instanceMatrix.toJSON();
  10930. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10931. }
  10932. if ( this.isBatchedMesh ) {
  10933. object.type = 'BatchedMesh';
  10934. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10935. object.sortObjects = this.sortObjects;
  10936. object.drawRanges = this._drawRanges;
  10937. object.reservedRanges = this._reservedRanges;
  10938. object.geometryInfo = this._geometryInfo.map( info => ( {
  10939. ...info,
  10940. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  10941. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  10942. } ) );
  10943. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  10944. object.availableInstanceIds = this._availableInstanceIds.slice();
  10945. object.availableGeometryIds = this._availableGeometryIds.slice();
  10946. object.nextIndexStart = this._nextIndexStart;
  10947. object.nextVertexStart = this._nextVertexStart;
  10948. object.geometryCount = this._geometryCount;
  10949. object.maxInstanceCount = this._maxInstanceCount;
  10950. object.maxVertexCount = this._maxVertexCount;
  10951. object.maxIndexCount = this._maxIndexCount;
  10952. object.geometryInitialized = this._geometryInitialized;
  10953. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10954. object.indirectTexture = this._indirectTexture.toJSON( meta );
  10955. if ( this._colorsTexture !== null ) {
  10956. object.colorsTexture = this._colorsTexture.toJSON( meta );
  10957. }
  10958. if ( this.boundingSphere !== null ) {
  10959. object.boundingSphere = this.boundingSphere.toJSON();
  10960. }
  10961. if ( this.boundingBox !== null ) {
  10962. object.boundingBox = this.boundingBox.toJSON();
  10963. }
  10964. }
  10965. //
  10966. function serialize( library, element ) {
  10967. if ( library[ element.uuid ] === undefined ) {
  10968. library[ element.uuid ] = element.toJSON( meta );
  10969. }
  10970. return element.uuid;
  10971. }
  10972. if ( this.isScene ) {
  10973. if ( this.background ) {
  10974. if ( this.background.isColor ) {
  10975. object.background = this.background.toJSON();
  10976. } else if ( this.background.isTexture ) {
  10977. object.background = this.background.toJSON( meta ).uuid;
  10978. }
  10979. }
  10980. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10981. object.environment = this.environment.toJSON( meta ).uuid;
  10982. }
  10983. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10984. object.geometry = serialize( meta.geometries, this.geometry );
  10985. const parameters = this.geometry.parameters;
  10986. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10987. const shapes = parameters.shapes;
  10988. if ( Array.isArray( shapes ) ) {
  10989. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10990. const shape = shapes[ i ];
  10991. serialize( meta.shapes, shape );
  10992. }
  10993. } else {
  10994. serialize( meta.shapes, shapes );
  10995. }
  10996. }
  10997. }
  10998. if ( this.isSkinnedMesh ) {
  10999. object.bindMode = this.bindMode;
  11000. object.bindMatrix = this.bindMatrix.toArray();
  11001. if ( this.skeleton !== undefined ) {
  11002. serialize( meta.skeletons, this.skeleton );
  11003. object.skeleton = this.skeleton.uuid;
  11004. }
  11005. }
  11006. if ( this.material !== undefined ) {
  11007. if ( Array.isArray( this.material ) ) {
  11008. const uuids = [];
  11009. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11010. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11011. }
  11012. object.material = uuids;
  11013. } else {
  11014. object.material = serialize( meta.materials, this.material );
  11015. }
  11016. }
  11017. //
  11018. if ( this.children.length > 0 ) {
  11019. object.children = [];
  11020. for ( let i = 0; i < this.children.length; i ++ ) {
  11021. object.children.push( this.children[ i ].toJSON( meta ).object );
  11022. }
  11023. }
  11024. //
  11025. if ( this.animations.length > 0 ) {
  11026. object.animations = [];
  11027. for ( let i = 0; i < this.animations.length; i ++ ) {
  11028. const animation = this.animations[ i ];
  11029. object.animations.push( serialize( meta.animations, animation ) );
  11030. }
  11031. }
  11032. if ( isRootObject ) {
  11033. const geometries = extractFromCache( meta.geometries );
  11034. const materials = extractFromCache( meta.materials );
  11035. const textures = extractFromCache( meta.textures );
  11036. const images = extractFromCache( meta.images );
  11037. const shapes = extractFromCache( meta.shapes );
  11038. const skeletons = extractFromCache( meta.skeletons );
  11039. const animations = extractFromCache( meta.animations );
  11040. const nodes = extractFromCache( meta.nodes );
  11041. if ( geometries.length > 0 ) output.geometries = geometries;
  11042. if ( materials.length > 0 ) output.materials = materials;
  11043. if ( textures.length > 0 ) output.textures = textures;
  11044. if ( images.length > 0 ) output.images = images;
  11045. if ( shapes.length > 0 ) output.shapes = shapes;
  11046. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11047. if ( animations.length > 0 ) output.animations = animations;
  11048. if ( nodes.length > 0 ) output.nodes = nodes;
  11049. }
  11050. output.object = object;
  11051. return output;
  11052. // extract data from the cache hash
  11053. // remove metadata on each item
  11054. // and return as array
  11055. function extractFromCache( cache ) {
  11056. const values = [];
  11057. for ( const key in cache ) {
  11058. const data = cache[ key ];
  11059. delete data.metadata;
  11060. values.push( data );
  11061. }
  11062. return values;
  11063. }
  11064. }
  11065. /**
  11066. * Returns a new 3D object with copied values from this instance.
  11067. *
  11068. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11069. * @return {Object3D} A clone of this instance.
  11070. */
  11071. clone( recursive ) {
  11072. return new this.constructor().copy( this, recursive );
  11073. }
  11074. /**
  11075. * Copies the values of the given 3D object to this instance.
  11076. *
  11077. * @param {Object3D} source - The 3D object to copy.
  11078. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11079. * @return {Object3D} A reference to this instance.
  11080. */
  11081. copy( source, recursive = true ) {
  11082. this.name = source.name;
  11083. this.up.copy( source.up );
  11084. this.position.copy( source.position );
  11085. this.rotation.order = source.rotation.order;
  11086. this.quaternion.copy( source.quaternion );
  11087. this.scale.copy( source.scale );
  11088. this.matrix.copy( source.matrix );
  11089. this.matrixWorld.copy( source.matrixWorld );
  11090. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11091. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11092. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11093. this.layers.mask = source.layers.mask;
  11094. this.visible = source.visible;
  11095. this.castShadow = source.castShadow;
  11096. this.receiveShadow = source.receiveShadow;
  11097. this.frustumCulled = source.frustumCulled;
  11098. this.renderOrder = source.renderOrder;
  11099. this.animations = source.animations.slice();
  11100. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11101. if ( recursive === true ) {
  11102. for ( let i = 0; i < source.children.length; i ++ ) {
  11103. const child = source.children[ i ];
  11104. this.add( child.clone() );
  11105. }
  11106. }
  11107. return this;
  11108. }
  11109. }
  11110. /**
  11111. * The default up direction for objects, also used as the default
  11112. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11113. *
  11114. * @static
  11115. * @type {Vector3}
  11116. * @default (0,1,0)
  11117. */
  11118. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11119. /**
  11120. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11121. * newly created 3D objects.
  11122. *
  11123. * @static
  11124. * @type {boolean}
  11125. * @default true
  11126. */
  11127. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11128. /**
  11129. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11130. * newly created 3D objects.
  11131. *
  11132. * @static
  11133. * @type {boolean}
  11134. * @default true
  11135. */
  11136. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11137. const _v0$1 = /*@__PURE__*/ new Vector3();
  11138. const _v1$3 = /*@__PURE__*/ new Vector3();
  11139. const _v2$2 = /*@__PURE__*/ new Vector3();
  11140. const _v3$2 = /*@__PURE__*/ new Vector3();
  11141. const _vab = /*@__PURE__*/ new Vector3();
  11142. const _vac = /*@__PURE__*/ new Vector3();
  11143. const _vbc = /*@__PURE__*/ new Vector3();
  11144. const _vap = /*@__PURE__*/ new Vector3();
  11145. const _vbp = /*@__PURE__*/ new Vector3();
  11146. const _vcp = /*@__PURE__*/ new Vector3();
  11147. const _v40 = /*@__PURE__*/ new Vector4();
  11148. const _v41 = /*@__PURE__*/ new Vector4();
  11149. const _v42 = /*@__PURE__*/ new Vector4();
  11150. /**
  11151. * A geometric triangle as defined by three vectors representing its three corners.
  11152. */
  11153. class Triangle {
  11154. /**
  11155. * Constructs a new triangle.
  11156. *
  11157. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11158. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11159. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11160. */
  11161. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11162. /**
  11163. * The first corner of the triangle.
  11164. *
  11165. * @type {Vector3}
  11166. */
  11167. this.a = a;
  11168. /**
  11169. * The second corner of the triangle.
  11170. *
  11171. * @type {Vector3}
  11172. */
  11173. this.b = b;
  11174. /**
  11175. * The third corner of the triangle.
  11176. *
  11177. * @type {Vector3}
  11178. */
  11179. this.c = c;
  11180. }
  11181. /**
  11182. * Computes the normal vector of a triangle.
  11183. *
  11184. * @param {Vector3} a - The first corner of the triangle.
  11185. * @param {Vector3} b - The second corner of the triangle.
  11186. * @param {Vector3} c - The third corner of the triangle.
  11187. * @param {Vector3} target - The target vector that is used to store the method's result.
  11188. * @return {Vector3} The triangle's normal.
  11189. */
  11190. static getNormal( a, b, c, target ) {
  11191. target.subVectors( c, b );
  11192. _v0$1.subVectors( a, b );
  11193. target.cross( _v0$1 );
  11194. const targetLengthSq = target.lengthSq();
  11195. if ( targetLengthSq > 0 ) {
  11196. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11197. }
  11198. return target.set( 0, 0, 0 );
  11199. }
  11200. /**
  11201. * Computes a barycentric coordinates from the given vector.
  11202. * Returns `null` if the triangle is degenerate.
  11203. *
  11204. * @param {Vector3} point - A point in 3D space.
  11205. * @param {Vector3} a - The first corner of the triangle.
  11206. * @param {Vector3} b - The second corner of the triangle.
  11207. * @param {Vector3} c - The third corner of the triangle.
  11208. * @param {Vector3} target - The target vector that is used to store the method's result.
  11209. * @return {?Vector3} The barycentric coordinates for the given point
  11210. */
  11211. static getBarycoord( point, a, b, c, target ) {
  11212. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11213. _v0$1.subVectors( c, a );
  11214. _v1$3.subVectors( b, a );
  11215. _v2$2.subVectors( point, a );
  11216. const dot00 = _v0$1.dot( _v0$1 );
  11217. const dot01 = _v0$1.dot( _v1$3 );
  11218. const dot02 = _v0$1.dot( _v2$2 );
  11219. const dot11 = _v1$3.dot( _v1$3 );
  11220. const dot12 = _v1$3.dot( _v2$2 );
  11221. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11222. // collinear or singular triangle
  11223. if ( denom === 0 ) {
  11224. target.set( 0, 0, 0 );
  11225. return null;
  11226. }
  11227. const invDenom = 1 / denom;
  11228. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11229. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11230. // barycentric coordinates must always sum to 1
  11231. return target.set( 1 - u - v, v, u );
  11232. }
  11233. /**
  11234. * Returns `true` if the given point, when projected onto the plane of the
  11235. * triangle, lies within the triangle.
  11236. *
  11237. * @param {Vector3} point - The point in 3D space to test.
  11238. * @param {Vector3} a - The first corner of the triangle.
  11239. * @param {Vector3} b - The second corner of the triangle.
  11240. * @param {Vector3} c - The third corner of the triangle.
  11241. * @return {boolean} Whether the given point, when projected onto the plane of the
  11242. * triangle, lies within the triangle or not.
  11243. */
  11244. static containsPoint( point, a, b, c ) {
  11245. // if the triangle is degenerate then we can't contain a point
  11246. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11247. return false;
  11248. }
  11249. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11250. }
  11251. /**
  11252. * Computes the value barycentrically interpolated for the given point on the
  11253. * triangle. Returns `null` if the triangle is degenerate.
  11254. *
  11255. * @param {Vector3} point - Position of interpolated point.
  11256. * @param {Vector3} p1 - The first corner of the triangle.
  11257. * @param {Vector3} p2 - The second corner of the triangle.
  11258. * @param {Vector3} p3 - The third corner of the triangle.
  11259. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11260. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11261. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11262. * @param {Vector3} target - The target vector that is used to store the method's result.
  11263. * @return {?Vector3} The interpolated value.
  11264. */
  11265. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11266. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11267. target.x = 0;
  11268. target.y = 0;
  11269. if ( 'z' in target ) target.z = 0;
  11270. if ( 'w' in target ) target.w = 0;
  11271. return null;
  11272. }
  11273. target.setScalar( 0 );
  11274. target.addScaledVector( v1, _v3$2.x );
  11275. target.addScaledVector( v2, _v3$2.y );
  11276. target.addScaledVector( v3, _v3$2.z );
  11277. return target;
  11278. }
  11279. /**
  11280. * Computes the value barycentrically interpolated for the given attribute and indices.
  11281. *
  11282. * @param {BufferAttribute} attr - The attribute to interpolate.
  11283. * @param {number} i1 - Index of first vertex.
  11284. * @param {number} i2 - Index of second vertex.
  11285. * @param {number} i3 - Index of third vertex.
  11286. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11287. * @param {Vector3} target - The target vector that is used to store the method's result.
  11288. * @return {Vector3} The interpolated attribute value.
  11289. */
  11290. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11291. _v40.setScalar( 0 );
  11292. _v41.setScalar( 0 );
  11293. _v42.setScalar( 0 );
  11294. _v40.fromBufferAttribute( attr, i1 );
  11295. _v41.fromBufferAttribute( attr, i2 );
  11296. _v42.fromBufferAttribute( attr, i3 );
  11297. target.setScalar( 0 );
  11298. target.addScaledVector( _v40, barycoord.x );
  11299. target.addScaledVector( _v41, barycoord.y );
  11300. target.addScaledVector( _v42, barycoord.z );
  11301. return target;
  11302. }
  11303. /**
  11304. * Returns `true` if the triangle is oriented towards the given direction.
  11305. *
  11306. * @param {Vector3} a - The first corner of the triangle.
  11307. * @param {Vector3} b - The second corner of the triangle.
  11308. * @param {Vector3} c - The third corner of the triangle.
  11309. * @param {Vector3} direction - The (normalized) direction vector.
  11310. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11311. */
  11312. static isFrontFacing( a, b, c, direction ) {
  11313. _v0$1.subVectors( c, b );
  11314. _v1$3.subVectors( a, b );
  11315. // strictly front facing
  11316. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11317. }
  11318. /**
  11319. * Sets the triangle's vertices by copying the given values.
  11320. *
  11321. * @param {Vector3} a - The first corner of the triangle.
  11322. * @param {Vector3} b - The second corner of the triangle.
  11323. * @param {Vector3} c - The third corner of the triangle.
  11324. * @return {Triangle} A reference to this triangle.
  11325. */
  11326. set( a, b, c ) {
  11327. this.a.copy( a );
  11328. this.b.copy( b );
  11329. this.c.copy( c );
  11330. return this;
  11331. }
  11332. /**
  11333. * Sets the triangle's vertices by copying the given array values.
  11334. *
  11335. * @param {Array<Vector3>} points - An array with 3D points.
  11336. * @param {number} i0 - The array index representing the first corner of the triangle.
  11337. * @param {number} i1 - The array index representing the second corner of the triangle.
  11338. * @param {number} i2 - The array index representing the third corner of the triangle.
  11339. * @return {Triangle} A reference to this triangle.
  11340. */
  11341. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11342. this.a.copy( points[ i0 ] );
  11343. this.b.copy( points[ i1 ] );
  11344. this.c.copy( points[ i2 ] );
  11345. return this;
  11346. }
  11347. /**
  11348. * Sets the triangle's vertices by copying the given attribute values.
  11349. *
  11350. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11351. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11352. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11353. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11354. * @return {Triangle} A reference to this triangle.
  11355. */
  11356. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11357. this.a.fromBufferAttribute( attribute, i0 );
  11358. this.b.fromBufferAttribute( attribute, i1 );
  11359. this.c.fromBufferAttribute( attribute, i2 );
  11360. return this;
  11361. }
  11362. /**
  11363. * Returns a new triangle with copied values from this instance.
  11364. *
  11365. * @return {Triangle} A clone of this instance.
  11366. */
  11367. clone() {
  11368. return new this.constructor().copy( this );
  11369. }
  11370. /**
  11371. * Copies the values of the given triangle to this instance.
  11372. *
  11373. * @param {Triangle} triangle - The triangle to copy.
  11374. * @return {Triangle} A reference to this triangle.
  11375. */
  11376. copy( triangle ) {
  11377. this.a.copy( triangle.a );
  11378. this.b.copy( triangle.b );
  11379. this.c.copy( triangle.c );
  11380. return this;
  11381. }
  11382. /**
  11383. * Computes the area of the triangle.
  11384. *
  11385. * @return {number} The triangle's area.
  11386. */
  11387. getArea() {
  11388. _v0$1.subVectors( this.c, this.b );
  11389. _v1$3.subVectors( this.a, this.b );
  11390. return _v0$1.cross( _v1$3 ).length() * 0.5;
  11391. }
  11392. /**
  11393. * Computes the midpoint of the triangle.
  11394. *
  11395. * @param {Vector3} target - The target vector that is used to store the method's result.
  11396. * @return {Vector3} The triangle's midpoint.
  11397. */
  11398. getMidpoint( target ) {
  11399. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11400. }
  11401. /**
  11402. * Computes the normal of the triangle.
  11403. *
  11404. * @param {Vector3} target - The target vector that is used to store the method's result.
  11405. * @return {Vector3} The triangle's normal.
  11406. */
  11407. getNormal( target ) {
  11408. return Triangle.getNormal( this.a, this.b, this.c, target );
  11409. }
  11410. /**
  11411. * Computes a plane the triangle lies within.
  11412. *
  11413. * @param {Plane} target - The target vector that is used to store the method's result.
  11414. * @return {Plane} The plane the triangle lies within.
  11415. */
  11416. getPlane( target ) {
  11417. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11418. }
  11419. /**
  11420. * Computes a barycentric coordinates from the given vector.
  11421. * Returns `null` if the triangle is degenerate.
  11422. *
  11423. * @param {Vector3} point - A point in 3D space.
  11424. * @param {Vector3} target - The target vector that is used to store the method's result.
  11425. * @return {?Vector3} The barycentric coordinates for the given point
  11426. */
  11427. getBarycoord( point, target ) {
  11428. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11429. }
  11430. /**
  11431. * Computes the value barycentrically interpolated for the given point on the
  11432. * triangle. Returns `null` if the triangle is degenerate.
  11433. *
  11434. * @param {Vector3} point - Position of interpolated point.
  11435. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11436. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11437. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11438. * @param {Vector3} target - The target vector that is used to store the method's result.
  11439. * @return {?Vector3} The interpolated value.
  11440. */
  11441. getInterpolation( point, v1, v2, v3, target ) {
  11442. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11443. }
  11444. /**
  11445. * Returns `true` if the given point, when projected onto the plane of the
  11446. * triangle, lies within the triangle.
  11447. *
  11448. * @param {Vector3} point - The point in 3D space to test.
  11449. * @return {boolean} Whether the given point, when projected onto the plane of the
  11450. * triangle, lies within the triangle or not.
  11451. */
  11452. containsPoint( point ) {
  11453. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11454. }
  11455. /**
  11456. * Returns `true` if the triangle is oriented towards the given direction.
  11457. *
  11458. * @param {Vector3} direction - The (normalized) direction vector.
  11459. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11460. */
  11461. isFrontFacing( direction ) {
  11462. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11463. }
  11464. /**
  11465. * Returns `true` if this triangle intersects with the given box.
  11466. *
  11467. * @param {Box3} box - The box to intersect.
  11468. * @return {boolean} Whether this triangle intersects with the given box or not.
  11469. */
  11470. intersectsBox( box ) {
  11471. return box.intersectsTriangle( this );
  11472. }
  11473. /**
  11474. * Returns the closest point on the triangle to the given point.
  11475. *
  11476. * @param {Vector3} p - The point to compute the closest point for.
  11477. * @param {Vector3} target - The target vector that is used to store the method's result.
  11478. * @return {Vector3} The closest point on the triangle.
  11479. */
  11480. closestPointToPoint( p, target ) {
  11481. const a = this.a, b = this.b, c = this.c;
  11482. let v, w;
  11483. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11484. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11485. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11486. // basically, we're distinguishing which of the voronoi regions of the triangle
  11487. // the point lies in with the minimum amount of redundant computation.
  11488. _vab.subVectors( b, a );
  11489. _vac.subVectors( c, a );
  11490. _vap.subVectors( p, a );
  11491. const d1 = _vab.dot( _vap );
  11492. const d2 = _vac.dot( _vap );
  11493. if ( d1 <= 0 && d2 <= 0 ) {
  11494. // vertex region of A; barycentric coords (1, 0, 0)
  11495. return target.copy( a );
  11496. }
  11497. _vbp.subVectors( p, b );
  11498. const d3 = _vab.dot( _vbp );
  11499. const d4 = _vac.dot( _vbp );
  11500. if ( d3 >= 0 && d4 <= d3 ) {
  11501. // vertex region of B; barycentric coords (0, 1, 0)
  11502. return target.copy( b );
  11503. }
  11504. const vc = d1 * d4 - d3 * d2;
  11505. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11506. v = d1 / ( d1 - d3 );
  11507. // edge region of AB; barycentric coords (1-v, v, 0)
  11508. return target.copy( a ).addScaledVector( _vab, v );
  11509. }
  11510. _vcp.subVectors( p, c );
  11511. const d5 = _vab.dot( _vcp );
  11512. const d6 = _vac.dot( _vcp );
  11513. if ( d6 >= 0 && d5 <= d6 ) {
  11514. // vertex region of C; barycentric coords (0, 0, 1)
  11515. return target.copy( c );
  11516. }
  11517. const vb = d5 * d2 - d1 * d6;
  11518. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11519. w = d2 / ( d2 - d6 );
  11520. // edge region of AC; barycentric coords (1-w, 0, w)
  11521. return target.copy( a ).addScaledVector( _vac, w );
  11522. }
  11523. const va = d3 * d6 - d5 * d4;
  11524. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11525. _vbc.subVectors( c, b );
  11526. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11527. // edge region of BC; barycentric coords (0, 1-w, w)
  11528. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11529. }
  11530. // face region
  11531. const denom = 1 / ( va + vb + vc );
  11532. // u = va * denom
  11533. v = vb * denom;
  11534. w = vc * denom;
  11535. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11536. }
  11537. /**
  11538. * Returns `true` if this triangle is equal with the given one.
  11539. *
  11540. * @param {Triangle} triangle - The triangle to test for equality.
  11541. * @return {boolean} Whether this triangle is equal with the given one.
  11542. */
  11543. equals( triangle ) {
  11544. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11545. }
  11546. }
  11547. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11548. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11549. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11550. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11551. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11552. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11553. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11554. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11555. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11556. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11557. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11558. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11559. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11560. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11561. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11562. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11563. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11564. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11565. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11566. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11567. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11568. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11569. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11570. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11571. const _hslA = { h: 0, s: 0, l: 0 };
  11572. const _hslB = { h: 0, s: 0, l: 0 };
  11573. function hue2rgb( p, q, t ) {
  11574. if ( t < 0 ) t += 1;
  11575. if ( t > 1 ) t -= 1;
  11576. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11577. if ( t < 1 / 2 ) return q;
  11578. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11579. return p;
  11580. }
  11581. /**
  11582. * A Color instance is represented by RGB components in the linear <i>working
  11583. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11584. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11585. * strings) are converted to the working color space automatically.
  11586. *
  11587. * ```js
  11588. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11589. * const color = new THREE.Color().setHex( 0x112233 );
  11590. * ```
  11591. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11592. * ```js
  11593. * // assumed already LinearSRGBColorSpace; no conversion
  11594. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11595. *
  11596. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11597. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11598. * ```
  11599. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11600. * see <i>Color management</i>. Iterating through a Color instance will yield
  11601. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11602. * in any of the following ways:
  11603. * ```js
  11604. * //empty constructor - will default white
  11605. * const color1 = new THREE.Color();
  11606. *
  11607. * //Hexadecimal color (recommended)
  11608. * const color2 = new THREE.Color( 0xff0000 );
  11609. *
  11610. * //RGB string
  11611. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11612. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11613. *
  11614. * //X11 color name - all 140 color names are supported.
  11615. * //Note the lack of CamelCase in the name
  11616. * const color5 = new THREE.Color( 'skyblue' );
  11617. * //HSL string
  11618. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11619. *
  11620. * //Separate RGB values between 0 and 1
  11621. * const color7 = new THREE.Color( 1, 0, 0 );
  11622. * ```
  11623. */
  11624. class Color {
  11625. /**
  11626. * Constructs a new color.
  11627. *
  11628. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11629. * and that method is used throughout the rest of the documentation.
  11630. *
  11631. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11632. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11633. * @param {number} [g] - The green component.
  11634. * @param {number} [b] - The blue component.
  11635. */
  11636. constructor( r, g, b ) {
  11637. /**
  11638. * This flag can be used for type testing.
  11639. *
  11640. * @type {boolean}
  11641. * @readonly
  11642. * @default true
  11643. */
  11644. this.isColor = true;
  11645. /**
  11646. * The red component.
  11647. *
  11648. * @type {number}
  11649. * @default 1
  11650. */
  11651. this.r = 1;
  11652. /**
  11653. * The green component.
  11654. *
  11655. * @type {number}
  11656. * @default 1
  11657. */
  11658. this.g = 1;
  11659. /**
  11660. * The blue component.
  11661. *
  11662. * @type {number}
  11663. * @default 1
  11664. */
  11665. this.b = 1;
  11666. return this.set( r, g, b );
  11667. }
  11668. /**
  11669. * Sets the colors's components from the given values.
  11670. *
  11671. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11672. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11673. * @param {number} [g] - The green component.
  11674. * @param {number} [b] - The blue component.
  11675. * @return {Color} A reference to this color.
  11676. */
  11677. set( r, g, b ) {
  11678. if ( g === undefined && b === undefined ) {
  11679. // r is THREE.Color, hex or string
  11680. const value = r;
  11681. if ( value && value.isColor ) {
  11682. this.copy( value );
  11683. } else if ( typeof value === 'number' ) {
  11684. this.setHex( value );
  11685. } else if ( typeof value === 'string' ) {
  11686. this.setStyle( value );
  11687. }
  11688. } else {
  11689. this.setRGB( r, g, b );
  11690. }
  11691. return this;
  11692. }
  11693. /**
  11694. * Sets the colors's components to the given scalar value.
  11695. *
  11696. * @param {number} scalar - The scalar value.
  11697. * @return {Color} A reference to this color.
  11698. */
  11699. setScalar( scalar ) {
  11700. this.r = scalar;
  11701. this.g = scalar;
  11702. this.b = scalar;
  11703. return this;
  11704. }
  11705. /**
  11706. * Sets this color from a hexadecimal value.
  11707. *
  11708. * @param {number} hex - The hexadecimal value.
  11709. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11710. * @return {Color} A reference to this color.
  11711. */
  11712. setHex( hex, colorSpace = SRGBColorSpace ) {
  11713. hex = Math.floor( hex );
  11714. this.r = ( hex >> 16 & 255 ) / 255;
  11715. this.g = ( hex >> 8 & 255 ) / 255;
  11716. this.b = ( hex & 255 ) / 255;
  11717. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11718. return this;
  11719. }
  11720. /**
  11721. * Sets this color from RGB values.
  11722. *
  11723. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11724. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11725. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11726. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11727. * @return {Color} A reference to this color.
  11728. */
  11729. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11730. this.r = r;
  11731. this.g = g;
  11732. this.b = b;
  11733. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11734. return this;
  11735. }
  11736. /**
  11737. * Sets this color from RGB values.
  11738. *
  11739. * @param {number} h - Hue value between `0.0` and `1.0`.
  11740. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11741. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11742. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11743. * @return {Color} A reference to this color.
  11744. */
  11745. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11746. // h,s,l ranges are in 0.0 - 1.0
  11747. h = euclideanModulo( h, 1 );
  11748. s = clamp( s, 0, 1 );
  11749. l = clamp( l, 0, 1 );
  11750. if ( s === 0 ) {
  11751. this.r = this.g = this.b = l;
  11752. } else {
  11753. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11754. const q = ( 2 * l ) - p;
  11755. this.r = hue2rgb( q, p, h + 1 / 3 );
  11756. this.g = hue2rgb( q, p, h );
  11757. this.b = hue2rgb( q, p, h - 1 / 3 );
  11758. }
  11759. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11760. return this;
  11761. }
  11762. /**
  11763. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11764. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11765. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  11766. * all 140 color names are supported).
  11767. *
  11768. * @param {string} style - Color as a CSS-style string.
  11769. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11770. * @return {Color} A reference to this color.
  11771. */
  11772. setStyle( style, colorSpace = SRGBColorSpace ) {
  11773. function handleAlpha( string ) {
  11774. if ( string === undefined ) return;
  11775. if ( parseFloat( string ) < 1 ) {
  11776. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  11777. }
  11778. }
  11779. let m;
  11780. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11781. // rgb / hsl
  11782. let color;
  11783. const name = m[ 1 ];
  11784. const components = m[ 2 ];
  11785. switch ( name ) {
  11786. case 'rgb':
  11787. case 'rgba':
  11788. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11789. // rgb(255,0,0) rgba(255,0,0,0.5)
  11790. handleAlpha( color[ 4 ] );
  11791. return this.setRGB(
  11792. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11793. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11794. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11795. colorSpace
  11796. );
  11797. }
  11798. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11799. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11800. handleAlpha( color[ 4 ] );
  11801. return this.setRGB(
  11802. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11803. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11804. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11805. colorSpace
  11806. );
  11807. }
  11808. break;
  11809. case 'hsl':
  11810. case 'hsla':
  11811. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11812. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11813. handleAlpha( color[ 4 ] );
  11814. return this.setHSL(
  11815. parseFloat( color[ 1 ] ) / 360,
  11816. parseFloat( color[ 2 ] ) / 100,
  11817. parseFloat( color[ 3 ] ) / 100,
  11818. colorSpace
  11819. );
  11820. }
  11821. break;
  11822. default:
  11823. console.warn( 'THREE.Color: Unknown color model ' + style );
  11824. }
  11825. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11826. // hex color
  11827. const hex = m[ 1 ];
  11828. const size = hex.length;
  11829. if ( size === 3 ) {
  11830. // #ff0
  11831. return this.setRGB(
  11832. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11833. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11834. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11835. colorSpace
  11836. );
  11837. } else if ( size === 6 ) {
  11838. // #ff0000
  11839. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11840. } else {
  11841. console.warn( 'THREE.Color: Invalid hex color ' + style );
  11842. }
  11843. } else if ( style && style.length > 0 ) {
  11844. return this.setColorName( style, colorSpace );
  11845. }
  11846. return this;
  11847. }
  11848. /**
  11849. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11850. * you don't need the other CSS-style formats.
  11851. *
  11852. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11853. * ```js
  11854. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11855. * ```
  11856. *
  11857. * @param {string} style - The color name.
  11858. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11859. * @return {Color} A reference to this color.
  11860. */
  11861. setColorName( style, colorSpace = SRGBColorSpace ) {
  11862. // color keywords
  11863. const hex = _colorKeywords[ style.toLowerCase() ];
  11864. if ( hex !== undefined ) {
  11865. // red
  11866. this.setHex( hex, colorSpace );
  11867. } else {
  11868. // unknown color
  11869. console.warn( 'THREE.Color: Unknown color ' + style );
  11870. }
  11871. return this;
  11872. }
  11873. /**
  11874. * Returns a new color with copied values from this instance.
  11875. *
  11876. * @return {Color} A clone of this instance.
  11877. */
  11878. clone() {
  11879. return new this.constructor( this.r, this.g, this.b );
  11880. }
  11881. /**
  11882. * Copies the values of the given color to this instance.
  11883. *
  11884. * @param {Color} color - The color to copy.
  11885. * @return {Color} A reference to this color.
  11886. */
  11887. copy( color ) {
  11888. this.r = color.r;
  11889. this.g = color.g;
  11890. this.b = color.b;
  11891. return this;
  11892. }
  11893. /**
  11894. * Copies the given color into this color, and then converts this color from
  11895. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11896. *
  11897. * @param {Color} color - The color to copy/convert.
  11898. * @return {Color} A reference to this color.
  11899. */
  11900. copySRGBToLinear( color ) {
  11901. this.r = SRGBToLinear( color.r );
  11902. this.g = SRGBToLinear( color.g );
  11903. this.b = SRGBToLinear( color.b );
  11904. return this;
  11905. }
  11906. /**
  11907. * Copies the given color into this color, and then converts this color from
  11908. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11909. *
  11910. * @param {Color} color - The color to copy/convert.
  11911. * @return {Color} A reference to this color.
  11912. */
  11913. copyLinearToSRGB( color ) {
  11914. this.r = LinearToSRGB( color.r );
  11915. this.g = LinearToSRGB( color.g );
  11916. this.b = LinearToSRGB( color.b );
  11917. return this;
  11918. }
  11919. /**
  11920. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11921. *
  11922. * @return {Color} A reference to this color.
  11923. */
  11924. convertSRGBToLinear() {
  11925. this.copySRGBToLinear( this );
  11926. return this;
  11927. }
  11928. /**
  11929. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11930. *
  11931. * @return {Color} A reference to this color.
  11932. */
  11933. convertLinearToSRGB() {
  11934. this.copyLinearToSRGB( this );
  11935. return this;
  11936. }
  11937. /**
  11938. * Returns the hexadecimal value of this color.
  11939. *
  11940. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11941. * @return {number} The hexadecimal value.
  11942. */
  11943. getHex( colorSpace = SRGBColorSpace ) {
  11944. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11945. return Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) );
  11946. }
  11947. /**
  11948. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  11949. *
  11950. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11951. * @return {string} The hexadecimal value as a string.
  11952. */
  11953. getHexString( colorSpace = SRGBColorSpace ) {
  11954. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  11955. }
  11956. /**
  11957. * Converts the colors RGB values into the HSL format and stores them into the
  11958. * given target object.
  11959. *
  11960. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  11961. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11962. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  11963. */
  11964. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  11965. // h,s,l ranges are in 0.0 - 1.0
  11966. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11967. const r = _color.r, g = _color.g, b = _color.b;
  11968. const max = Math.max( r, g, b );
  11969. const min = Math.min( r, g, b );
  11970. let hue, saturation;
  11971. const lightness = ( min + max ) / 2.0;
  11972. if ( min === max ) {
  11973. hue = 0;
  11974. saturation = 0;
  11975. } else {
  11976. const delta = max - min;
  11977. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  11978. switch ( max ) {
  11979. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  11980. case g: hue = ( b - r ) / delta + 2; break;
  11981. case b: hue = ( r - g ) / delta + 4; break;
  11982. }
  11983. hue /= 6;
  11984. }
  11985. target.h = hue;
  11986. target.s = saturation;
  11987. target.l = lightness;
  11988. return target;
  11989. }
  11990. /**
  11991. * Returns the RGB values of this color and stores them into the given target object.
  11992. *
  11993. * @param {Color} target - The target color that is used to store the method's result.
  11994. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11995. * @return {Color} The RGB representation of this color.
  11996. */
  11997. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  11998. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11999. target.r = _color.r;
  12000. target.g = _color.g;
  12001. target.b = _color.b;
  12002. return target;
  12003. }
  12004. /**
  12005. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12006. *
  12007. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12008. * @return {string} The CSS representation of this color.
  12009. */
  12010. getStyle( colorSpace = SRGBColorSpace ) {
  12011. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12012. const r = _color.r, g = _color.g, b = _color.b;
  12013. if ( colorSpace !== SRGBColorSpace ) {
  12014. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12015. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12016. }
  12017. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12018. }
  12019. /**
  12020. * Adds the given HSL values to this color's values.
  12021. * Internally, this converts the color's RGB values to HSL, adds HSL
  12022. * and then converts the color back to RGB.
  12023. *
  12024. * @param {number} h - Hue value between `0.0` and `1.0`.
  12025. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12026. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12027. * @return {Color} A reference to this color.
  12028. */
  12029. offsetHSL( h, s, l ) {
  12030. this.getHSL( _hslA );
  12031. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12032. }
  12033. /**
  12034. * Adds the RGB values of the given color to the RGB values of this color.
  12035. *
  12036. * @param {Color} color - The color to add.
  12037. * @return {Color} A reference to this color.
  12038. */
  12039. add( color ) {
  12040. this.r += color.r;
  12041. this.g += color.g;
  12042. this.b += color.b;
  12043. return this;
  12044. }
  12045. /**
  12046. * Adds the RGB values of the given colors and stores the result in this instance.
  12047. *
  12048. * @param {Color} color1 - The first color.
  12049. * @param {Color} color2 - The second color.
  12050. * @return {Color} A reference to this color.
  12051. */
  12052. addColors( color1, color2 ) {
  12053. this.r = color1.r + color2.r;
  12054. this.g = color1.g + color2.g;
  12055. this.b = color1.b + color2.b;
  12056. return this;
  12057. }
  12058. /**
  12059. * Adds the given scalar value to the RGB values of this color.
  12060. *
  12061. * @param {number} s - The scalar to add.
  12062. * @return {Color} A reference to this color.
  12063. */
  12064. addScalar( s ) {
  12065. this.r += s;
  12066. this.g += s;
  12067. this.b += s;
  12068. return this;
  12069. }
  12070. /**
  12071. * Subtracts the RGB values of the given color from the RGB values of this color.
  12072. *
  12073. * @param {Color} color - The color to subtract.
  12074. * @return {Color} A reference to this color.
  12075. */
  12076. sub( color ) {
  12077. this.r = Math.max( 0, this.r - color.r );
  12078. this.g = Math.max( 0, this.g - color.g );
  12079. this.b = Math.max( 0, this.b - color.b );
  12080. return this;
  12081. }
  12082. /**
  12083. * Multiplies the RGB values of the given color with the RGB values of this color.
  12084. *
  12085. * @param {Color} color - The color to multiply.
  12086. * @return {Color} A reference to this color.
  12087. */
  12088. multiply( color ) {
  12089. this.r *= color.r;
  12090. this.g *= color.g;
  12091. this.b *= color.b;
  12092. return this;
  12093. }
  12094. /**
  12095. * Multiplies the given scalar value with the RGB values of this color.
  12096. *
  12097. * @param {number} s - The scalar to multiply.
  12098. * @return {Color} A reference to this color.
  12099. */
  12100. multiplyScalar( s ) {
  12101. this.r *= s;
  12102. this.g *= s;
  12103. this.b *= s;
  12104. return this;
  12105. }
  12106. /**
  12107. * Linearly interpolates this color's RGB values toward the RGB values of the
  12108. * given color. The alpha argument can be thought of as the ratio between
  12109. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12110. *
  12111. * @param {Color} color - The color to converge on.
  12112. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12113. * @return {Color} A reference to this color.
  12114. */
  12115. lerp( color, alpha ) {
  12116. this.r += ( color.r - this.r ) * alpha;
  12117. this.g += ( color.g - this.g ) * alpha;
  12118. this.b += ( color.b - this.b ) * alpha;
  12119. return this;
  12120. }
  12121. /**
  12122. * Linearly interpolates between the given colors and stores the result in this instance.
  12123. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12124. * is the first and `1.0` is the second color.
  12125. *
  12126. * @param {Color} color1 - The first color.
  12127. * @param {Color} color2 - The second color.
  12128. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12129. * @return {Color} A reference to this color.
  12130. */
  12131. lerpColors( color1, color2, alpha ) {
  12132. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12133. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12134. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12135. return this;
  12136. }
  12137. /**
  12138. * Linearly interpolates this color's HSL values toward the HSL values of the
  12139. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12140. * from one color to the other, but instead going through all the hues in between
  12141. * those two colors. The alpha argument can be thought of as the ratio between
  12142. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12143. *
  12144. * @param {Color} color - The color to converge on.
  12145. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12146. * @return {Color} A reference to this color.
  12147. */
  12148. lerpHSL( color, alpha ) {
  12149. this.getHSL( _hslA );
  12150. color.getHSL( _hslB );
  12151. const h = lerp( _hslA.h, _hslB.h, alpha );
  12152. const s = lerp( _hslA.s, _hslB.s, alpha );
  12153. const l = lerp( _hslA.l, _hslB.l, alpha );
  12154. this.setHSL( h, s, l );
  12155. return this;
  12156. }
  12157. /**
  12158. * Sets the color's RGB components from the given 3D vector.
  12159. *
  12160. * @param {Vector3} v - The vector to set.
  12161. * @return {Color} A reference to this color.
  12162. */
  12163. setFromVector3( v ) {
  12164. this.r = v.x;
  12165. this.g = v.y;
  12166. this.b = v.z;
  12167. return this;
  12168. }
  12169. /**
  12170. * Transforms this color with the given 3x3 matrix.
  12171. *
  12172. * @param {Matrix3} m - The matrix.
  12173. * @return {Color} A reference to this color.
  12174. */
  12175. applyMatrix3( m ) {
  12176. const r = this.r, g = this.g, b = this.b;
  12177. const e = m.elements;
  12178. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12179. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12180. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12181. return this;
  12182. }
  12183. /**
  12184. * Returns `true` if this color is equal with the given one.
  12185. *
  12186. * @param {Color} c - The color to test for equality.
  12187. * @return {boolean} Whether this bounding color is equal with the given one.
  12188. */
  12189. equals( c ) {
  12190. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12191. }
  12192. /**
  12193. * Sets this color's RGB components from the given array.
  12194. *
  12195. * @param {Array<number>} array - An array holding the RGB values.
  12196. * @param {number} [offset=0] - The offset into the array.
  12197. * @return {Color} A reference to this color.
  12198. */
  12199. fromArray( array, offset = 0 ) {
  12200. this.r = array[ offset ];
  12201. this.g = array[ offset + 1 ];
  12202. this.b = array[ offset + 2 ];
  12203. return this;
  12204. }
  12205. /**
  12206. * Writes the RGB components of this color to the given array. If no array is provided,
  12207. * the method returns a new instance.
  12208. *
  12209. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12210. * @param {number} [offset=0] - Index of the first element in the array.
  12211. * @return {Array<number>} The color components.
  12212. */
  12213. toArray( array = [], offset = 0 ) {
  12214. array[ offset ] = this.r;
  12215. array[ offset + 1 ] = this.g;
  12216. array[ offset + 2 ] = this.b;
  12217. return array;
  12218. }
  12219. /**
  12220. * Sets the components of this color from the given buffer attribute.
  12221. *
  12222. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12223. * @param {number} index - The index into the attribute.
  12224. * @return {Color} A reference to this color.
  12225. */
  12226. fromBufferAttribute( attribute, index ) {
  12227. this.r = attribute.getX( index );
  12228. this.g = attribute.getY( index );
  12229. this.b = attribute.getZ( index );
  12230. return this;
  12231. }
  12232. /**
  12233. * This methods defines the serialization result of this class. Returns the color
  12234. * as a hexadecimal value.
  12235. *
  12236. * @return {number} The hexadecimal value.
  12237. */
  12238. toJSON() {
  12239. return this.getHex();
  12240. }
  12241. *[ Symbol.iterator ]() {
  12242. yield this.r;
  12243. yield this.g;
  12244. yield this.b;
  12245. }
  12246. }
  12247. const _color = /*@__PURE__*/ new Color();
  12248. /**
  12249. * A dictionary with X11 color names.
  12250. *
  12251. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12252. *
  12253. * @static
  12254. * @type {Object}
  12255. */
  12256. Color.NAMES = _colorKeywords;
  12257. let _materialId = 0;
  12258. /**
  12259. * Abstract base class for materials.
  12260. *
  12261. * Materials define the appearance of renderable 3D objects.
  12262. *
  12263. * @abstract
  12264. * @augments EventDispatcher
  12265. */
  12266. class Material extends EventDispatcher {
  12267. /**
  12268. * Constructs a new material.
  12269. */
  12270. constructor() {
  12271. super();
  12272. /**
  12273. * This flag can be used for type testing.
  12274. *
  12275. * @type {boolean}
  12276. * @readonly
  12277. * @default true
  12278. */
  12279. this.isMaterial = true;
  12280. /**
  12281. * The ID of the material.
  12282. *
  12283. * @name Material#id
  12284. * @type {number}
  12285. * @readonly
  12286. */
  12287. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12288. /**
  12289. * The UUID of the material.
  12290. *
  12291. * @type {string}
  12292. * @readonly
  12293. */
  12294. this.uuid = generateUUID();
  12295. /**
  12296. * The name of the material.
  12297. *
  12298. * @type {string}
  12299. */
  12300. this.name = '';
  12301. /**
  12302. * The type property is used for detecting the object type
  12303. * in context of serialization/deserialization.
  12304. *
  12305. * @type {string}
  12306. * @readonly
  12307. */
  12308. this.type = 'Material';
  12309. /**
  12310. * Defines the blending type of the material.
  12311. *
  12312. * It must be set to `CustomBlending` if custom blending properties like
  12313. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12314. * should have any effect.
  12315. *
  12316. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12317. * @default NormalBlending
  12318. */
  12319. this.blending = NormalBlending;
  12320. /**
  12321. * Defines which side of faces will be rendered - front, back or both.
  12322. *
  12323. * @type {(FrontSide|BackSide|DoubleSide)}
  12324. * @default FrontSide
  12325. */
  12326. this.side = FrontSide;
  12327. /**
  12328. * If set to `true`, vertex colors should be used.
  12329. *
  12330. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12331. * four (RGBA) component color buffer attribute is used.
  12332. *
  12333. * @type {boolean}
  12334. * @default false
  12335. */
  12336. this.vertexColors = false;
  12337. /**
  12338. * Defines how transparent the material is.
  12339. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12340. *
  12341. * If the {@link Material#transparent} is not set to `true`,
  12342. * the material will remain fully opaque and this value will only affect its color.
  12343. *
  12344. * @type {number}
  12345. * @default 1
  12346. */
  12347. this.opacity = 1;
  12348. /**
  12349. * Defines whether this material is transparent. This has an effect on
  12350. * rendering as transparent objects need special treatment and are rendered
  12351. * after non-transparent objects.
  12352. *
  12353. * When set to true, the extent to which the material is transparent is
  12354. * controlled by {@link Material#opacity}.
  12355. *
  12356. * @type {boolean}
  12357. * @default false
  12358. */
  12359. this.transparent = false;
  12360. /**
  12361. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12362. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12363. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12364. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12365. *
  12366. * @type {boolean}
  12367. * @default false
  12368. */
  12369. this.alphaHash = false;
  12370. /**
  12371. * Defines the blending source factor.
  12372. *
  12373. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12374. * @default SrcAlphaFactor
  12375. */
  12376. this.blendSrc = SrcAlphaFactor;
  12377. /**
  12378. * Defines the blending destination factor.
  12379. *
  12380. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12381. * @default OneMinusSrcAlphaFactor
  12382. */
  12383. this.blendDst = OneMinusSrcAlphaFactor;
  12384. /**
  12385. * Defines the blending equation.
  12386. *
  12387. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12388. * @default AddEquation
  12389. */
  12390. this.blendEquation = AddEquation;
  12391. /**
  12392. * Defines the blending source alpha factor.
  12393. *
  12394. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12395. * @default null
  12396. */
  12397. this.blendSrcAlpha = null;
  12398. /**
  12399. * Defines the blending destination alpha factor.
  12400. *
  12401. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12402. * @default null
  12403. */
  12404. this.blendDstAlpha = null;
  12405. /**
  12406. * Defines the blending equation of the alpha channel.
  12407. *
  12408. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12409. * @default null
  12410. */
  12411. this.blendEquationAlpha = null;
  12412. /**
  12413. * Represents the RGB values of the constant blend color.
  12414. *
  12415. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12416. *
  12417. * @type {Color}
  12418. * @default (0,0,0)
  12419. */
  12420. this.blendColor = new Color( 0, 0, 0 );
  12421. /**
  12422. * Represents the alpha value of the constant blend color.
  12423. *
  12424. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12425. *
  12426. * @type {number}
  12427. * @default 0
  12428. */
  12429. this.blendAlpha = 0;
  12430. /**
  12431. * Defines the depth function.
  12432. *
  12433. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12434. * @default LessEqualDepth
  12435. */
  12436. this.depthFunc = LessEqualDepth;
  12437. /**
  12438. * Whether to have depth test enabled when rendering this material.
  12439. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12440. *
  12441. * @type {boolean}
  12442. * @default true
  12443. */
  12444. this.depthTest = true;
  12445. /**
  12446. * Whether rendering this material has any effect on the depth buffer.
  12447. *
  12448. * When drawing 2D overlays it can be useful to disable the depth writing in
  12449. * order to layer several things together without creating z-index artifacts.
  12450. *
  12451. * @type {boolean}
  12452. * @default true
  12453. */
  12454. this.depthWrite = true;
  12455. /**
  12456. * The bit mask to use when writing to the stencil buffer.
  12457. *
  12458. * @type {number}
  12459. * @default 0xff
  12460. */
  12461. this.stencilWriteMask = 0xff;
  12462. /**
  12463. * The stencil comparison function to use.
  12464. *
  12465. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12466. * @default AlwaysStencilFunc
  12467. */
  12468. this.stencilFunc = AlwaysStencilFunc;
  12469. /**
  12470. * The value to use when performing stencil comparisons or stencil operations.
  12471. *
  12472. * @type {number}
  12473. * @default 0
  12474. */
  12475. this.stencilRef = 0;
  12476. /**
  12477. * The bit mask to use when comparing against the stencil buffer.
  12478. *
  12479. * @type {number}
  12480. * @default 0xff
  12481. */
  12482. this.stencilFuncMask = 0xff;
  12483. /**
  12484. * Which stencil operation to perform when the comparison function returns `false`.
  12485. *
  12486. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12487. * @default KeepStencilOp
  12488. */
  12489. this.stencilFail = KeepStencilOp;
  12490. /**
  12491. * Which stencil operation to perform when the comparison function returns
  12492. * `true` but the depth test fails.
  12493. *
  12494. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12495. * @default KeepStencilOp
  12496. */
  12497. this.stencilZFail = KeepStencilOp;
  12498. /**
  12499. * Which stencil operation to perform when the comparison function returns
  12500. * `true` and the depth test passes.
  12501. *
  12502. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12503. * @default KeepStencilOp
  12504. */
  12505. this.stencilZPass = KeepStencilOp;
  12506. /**
  12507. * Whether stencil operations are performed against the stencil buffer. In
  12508. * order to perform writes or comparisons against the stencil buffer this
  12509. * value must be `true`.
  12510. *
  12511. * @type {boolean}
  12512. * @default false
  12513. */
  12514. this.stencilWrite = false;
  12515. /**
  12516. * User-defined clipping planes specified as THREE.Plane objects in world
  12517. * space. These planes apply to the objects this material is attached to.
  12518. * Points in space whose signed distance to the plane is negative are clipped
  12519. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12520. * be `true`.
  12521. *
  12522. * @type {?Array<Plane>}
  12523. * @default null
  12524. */
  12525. this.clippingPlanes = null;
  12526. /**
  12527. * Changes the behavior of clipping planes so that only their intersection is
  12528. * clipped, rather than their union.
  12529. *
  12530. * @type {boolean}
  12531. * @default false
  12532. */
  12533. this.clipIntersection = false;
  12534. /**
  12535. * Defines whether to clip shadows according to the clipping planes specified
  12536. * on this material.
  12537. *
  12538. * @type {boolean}
  12539. * @default false
  12540. */
  12541. this.clipShadows = false;
  12542. /**
  12543. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12544. * is determined as follows:
  12545. *
  12546. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12547. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12548. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12549. *
  12550. * @type {?(FrontSide|BackSide|DoubleSide)}
  12551. * @default null
  12552. */
  12553. this.shadowSide = null;
  12554. /**
  12555. * Whether to render the material's color.
  12556. *
  12557. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12558. * objects that occlude other objects.
  12559. *
  12560. * @type {boolean}
  12561. * @default true
  12562. */
  12563. this.colorWrite = true;
  12564. /**
  12565. * Override the renderer's default precision for this material.
  12566. *
  12567. * @type {?('highp'|'mediump'|'lowp')}
  12568. * @default null
  12569. */
  12570. this.precision = null;
  12571. /**
  12572. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12573. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12574. * The offset is added before the depth test is performed and before the value is written
  12575. * into the depth buffer.
  12576. *
  12577. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12578. * rendering solids with highlighted edges.
  12579. *
  12580. * @type {boolean}
  12581. * @default false
  12582. */
  12583. this.polygonOffset = false;
  12584. /**
  12585. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12586. *
  12587. * @type {number}
  12588. * @default 0
  12589. */
  12590. this.polygonOffsetFactor = 0;
  12591. /**
  12592. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12593. *
  12594. * @type {number}
  12595. * @default 0
  12596. */
  12597. this.polygonOffsetUnits = 0;
  12598. /**
  12599. * Whether to apply dithering to the color to remove the appearance of banding.
  12600. *
  12601. * @type {boolean}
  12602. * @default false
  12603. */
  12604. this.dithering = false;
  12605. /**
  12606. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12607. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12608. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12609. *
  12610. * @type {boolean}
  12611. * @default false
  12612. */
  12613. this.alphaToCoverage = false;
  12614. /**
  12615. * Whether to premultiply the alpha (transparency) value.
  12616. *
  12617. * @type {boolean}
  12618. * @default false
  12619. */
  12620. this.premultipliedAlpha = false;
  12621. /**
  12622. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12623. *
  12624. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12625. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12626. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12627. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12628. * disable the two pass rendering to avoid performance issues.
  12629. *
  12630. * @type {boolean}
  12631. * @default false
  12632. */
  12633. this.forceSinglePass = false;
  12634. /**
  12635. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12636. *
  12637. * @type {boolean}
  12638. * @default true
  12639. */
  12640. this.allowOverride = true;
  12641. /**
  12642. * Defines whether 3D objects using this material are visible.
  12643. *
  12644. * @type {boolean}
  12645. * @default true
  12646. */
  12647. this.visible = true;
  12648. /**
  12649. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12650. *
  12651. * It is ignored when rendering to a render target or using post processing or when using
  12652. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12653. *
  12654. * @type {boolean}
  12655. * @default true
  12656. */
  12657. this.toneMapped = true;
  12658. /**
  12659. * An object that can be used to store custom data about the Material. It
  12660. * should not hold references to functions as these will not be cloned.
  12661. *
  12662. * @type {Object}
  12663. */
  12664. this.userData = {};
  12665. /**
  12666. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12667. *
  12668. * @type {number}
  12669. * @readonly
  12670. * @default 0
  12671. */
  12672. this.version = 0;
  12673. this._alphaTest = 0;
  12674. }
  12675. /**
  12676. * Sets the alpha value to be used when running an alpha test. The material
  12677. * will not be rendered if the opacity is lower than this value.
  12678. *
  12679. * @type {number}
  12680. * @readonly
  12681. * @default 0
  12682. */
  12683. get alphaTest() {
  12684. return this._alphaTest;
  12685. }
  12686. set alphaTest( value ) {
  12687. if ( this._alphaTest > 0 !== value > 0 ) {
  12688. this.version ++;
  12689. }
  12690. this._alphaTest = value;
  12691. }
  12692. /**
  12693. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12694. *
  12695. * This method can only be used when rendering with {@link WebGLRenderer}.
  12696. *
  12697. * @param {WebGLRenderer} renderer - The renderer.
  12698. * @param {Scene} scene - The scene.
  12699. * @param {Camera} camera - The camera that is used to render the scene.
  12700. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12701. * @param {Object3D} object - The 3D object.
  12702. * @param {Object} group - The geometry group data.
  12703. */
  12704. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12705. /**
  12706. * An optional callback that is executed immediately before the shader
  12707. * program is compiled. This function is called with the shader source code
  12708. * as a parameter. Useful for the modification of built-in materials.
  12709. *
  12710. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12711. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12712. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  12713. *
  12714. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12715. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12716. */
  12717. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12718. /**
  12719. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12720. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12721. * shader or recompile the shader for this material as needed.
  12722. *
  12723. * This method can only be used when rendering with {@link WebGLRenderer}.
  12724. *
  12725. * @return {string} The custom program cache key.
  12726. */
  12727. customProgramCacheKey() {
  12728. return this.onBeforeCompile.toString();
  12729. }
  12730. /**
  12731. * This method can be used to set default values from parameter objects.
  12732. * It is a generic implementation so it can be used with different types
  12733. * of materials.
  12734. *
  12735. * @param {Object} [values] - The material values to set.
  12736. */
  12737. setValues( values ) {
  12738. if ( values === undefined ) return;
  12739. for ( const key in values ) {
  12740. const newValue = values[ key ];
  12741. if ( newValue === undefined ) {
  12742. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  12743. continue;
  12744. }
  12745. const currentValue = this[ key ];
  12746. if ( currentValue === undefined ) {
  12747. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12748. continue;
  12749. }
  12750. if ( currentValue && currentValue.isColor ) {
  12751. currentValue.set( newValue );
  12752. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12753. currentValue.copy( newValue );
  12754. } else {
  12755. this[ key ] = newValue;
  12756. }
  12757. }
  12758. }
  12759. /**
  12760. * Serializes the material into JSON.
  12761. *
  12762. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12763. * @return {Object} A JSON object representing the serialized material.
  12764. * @see {@link ObjectLoader#parse}
  12765. */
  12766. toJSON( meta ) {
  12767. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12768. if ( isRootObject ) {
  12769. meta = {
  12770. textures: {},
  12771. images: {}
  12772. };
  12773. }
  12774. const data = {
  12775. metadata: {
  12776. version: 4.7,
  12777. type: 'Material',
  12778. generator: 'Material.toJSON'
  12779. }
  12780. };
  12781. // standard Material serialization
  12782. data.uuid = this.uuid;
  12783. data.type = this.type;
  12784. if ( this.name !== '' ) data.name = this.name;
  12785. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12786. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12787. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12788. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12789. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12790. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12791. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12792. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12793. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12794. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12795. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12796. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12797. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12798. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12799. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12800. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12801. }
  12802. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12803. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12804. }
  12805. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12806. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12807. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12808. }
  12809. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  12810. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  12811. }
  12812. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  12813. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  12814. }
  12815. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12816. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12817. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12818. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12819. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12820. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12821. }
  12822. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12823. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12824. }
  12825. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12826. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12827. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12828. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12829. }
  12830. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12831. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12832. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12833. if ( this.lightMap && this.lightMap.isTexture ) {
  12834. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12835. data.lightMapIntensity = this.lightMapIntensity;
  12836. }
  12837. if ( this.aoMap && this.aoMap.isTexture ) {
  12838. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12839. data.aoMapIntensity = this.aoMapIntensity;
  12840. }
  12841. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12842. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12843. data.bumpScale = this.bumpScale;
  12844. }
  12845. if ( this.normalMap && this.normalMap.isTexture ) {
  12846. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12847. data.normalMapType = this.normalMapType;
  12848. data.normalScale = this.normalScale.toArray();
  12849. }
  12850. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12851. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12852. data.displacementScale = this.displacementScale;
  12853. data.displacementBias = this.displacementBias;
  12854. }
  12855. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12856. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12857. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12858. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12859. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12860. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12861. if ( this.envMap && this.envMap.isTexture ) {
  12862. data.envMap = this.envMap.toJSON( meta ).uuid;
  12863. if ( this.combine !== undefined ) data.combine = this.combine;
  12864. }
  12865. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12866. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12867. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12868. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12869. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12870. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12871. }
  12872. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12873. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12874. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12875. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12876. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12877. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12878. if ( this.size !== undefined ) data.size = this.size;
  12879. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12880. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12881. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12882. if ( this.side !== FrontSide ) data.side = this.side;
  12883. if ( this.vertexColors === true ) data.vertexColors = true;
  12884. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12885. if ( this.transparent === true ) data.transparent = true;
  12886. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12887. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12888. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12889. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12890. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12891. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12892. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12893. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12894. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12895. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12896. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12897. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12898. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12899. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12900. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12901. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12902. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12903. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12904. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12905. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12906. // rotation (SpriteMaterial)
  12907. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12908. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12909. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12910. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12911. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12912. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12913. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12914. if ( this.scale !== undefined ) data.scale = this.scale;
  12915. if ( this.dithering === true ) data.dithering = true;
  12916. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12917. if ( this.alphaHash === true ) data.alphaHash = true;
  12918. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12919. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12920. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12921. if ( this.wireframe === true ) data.wireframe = true;
  12922. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12923. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12924. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12925. if ( this.flatShading === true ) data.flatShading = true;
  12926. if ( this.visible === false ) data.visible = false;
  12927. if ( this.toneMapped === false ) data.toneMapped = false;
  12928. if ( this.fog === false ) data.fog = false;
  12929. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12930. // TODO: Copied from Object3D.toJSON
  12931. function extractFromCache( cache ) {
  12932. const values = [];
  12933. for ( const key in cache ) {
  12934. const data = cache[ key ];
  12935. delete data.metadata;
  12936. values.push( data );
  12937. }
  12938. return values;
  12939. }
  12940. if ( isRootObject ) {
  12941. const textures = extractFromCache( meta.textures );
  12942. const images = extractFromCache( meta.images );
  12943. if ( textures.length > 0 ) data.textures = textures;
  12944. if ( images.length > 0 ) data.images = images;
  12945. }
  12946. return data;
  12947. }
  12948. /**
  12949. * Returns a new material with copied values from this instance.
  12950. *
  12951. * @return {Material} A clone of this instance.
  12952. */
  12953. clone() {
  12954. return new this.constructor().copy( this );
  12955. }
  12956. /**
  12957. * Copies the values of the given material to this instance.
  12958. *
  12959. * @param {Material} source - The material to copy.
  12960. * @return {Material} A reference to this instance.
  12961. */
  12962. copy( source ) {
  12963. this.name = source.name;
  12964. this.blending = source.blending;
  12965. this.side = source.side;
  12966. this.vertexColors = source.vertexColors;
  12967. this.opacity = source.opacity;
  12968. this.transparent = source.transparent;
  12969. this.blendSrc = source.blendSrc;
  12970. this.blendDst = source.blendDst;
  12971. this.blendEquation = source.blendEquation;
  12972. this.blendSrcAlpha = source.blendSrcAlpha;
  12973. this.blendDstAlpha = source.blendDstAlpha;
  12974. this.blendEquationAlpha = source.blendEquationAlpha;
  12975. this.blendColor.copy( source.blendColor );
  12976. this.blendAlpha = source.blendAlpha;
  12977. this.depthFunc = source.depthFunc;
  12978. this.depthTest = source.depthTest;
  12979. this.depthWrite = source.depthWrite;
  12980. this.stencilWriteMask = source.stencilWriteMask;
  12981. this.stencilFunc = source.stencilFunc;
  12982. this.stencilRef = source.stencilRef;
  12983. this.stencilFuncMask = source.stencilFuncMask;
  12984. this.stencilFail = source.stencilFail;
  12985. this.stencilZFail = source.stencilZFail;
  12986. this.stencilZPass = source.stencilZPass;
  12987. this.stencilWrite = source.stencilWrite;
  12988. const srcPlanes = source.clippingPlanes;
  12989. let dstPlanes = null;
  12990. if ( srcPlanes !== null ) {
  12991. const n = srcPlanes.length;
  12992. dstPlanes = new Array( n );
  12993. for ( let i = 0; i !== n; ++ i ) {
  12994. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12995. }
  12996. }
  12997. this.clippingPlanes = dstPlanes;
  12998. this.clipIntersection = source.clipIntersection;
  12999. this.clipShadows = source.clipShadows;
  13000. this.shadowSide = source.shadowSide;
  13001. this.colorWrite = source.colorWrite;
  13002. this.precision = source.precision;
  13003. this.polygonOffset = source.polygonOffset;
  13004. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13005. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13006. this.dithering = source.dithering;
  13007. this.alphaTest = source.alphaTest;
  13008. this.alphaHash = source.alphaHash;
  13009. this.alphaToCoverage = source.alphaToCoverage;
  13010. this.premultipliedAlpha = source.premultipliedAlpha;
  13011. this.forceSinglePass = source.forceSinglePass;
  13012. this.visible = source.visible;
  13013. this.toneMapped = source.toneMapped;
  13014. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13015. return this;
  13016. }
  13017. /**
  13018. * Frees the GPU-related resources allocated by this instance. Call this
  13019. * method whenever this instance is no longer used in your app.
  13020. *
  13021. * @fires Material#dispose
  13022. */
  13023. dispose() {
  13024. /**
  13025. * Fires when the material has been disposed of.
  13026. *
  13027. * @event Material#dispose
  13028. * @type {Object}
  13029. */
  13030. this.dispatchEvent( { type: 'dispose' } );
  13031. }
  13032. /**
  13033. * Setting this property to `true` indicates the engine the material
  13034. * needs to be recompiled.
  13035. *
  13036. * @type {boolean}
  13037. * @default false
  13038. * @param {boolean} value
  13039. */
  13040. set needsUpdate( value ) {
  13041. if ( value === true ) this.version ++;
  13042. }
  13043. }
  13044. /**
  13045. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13046. *
  13047. * This material is not affected by lights.
  13048. *
  13049. * @augments Material
  13050. */
  13051. class MeshBasicMaterial extends Material {
  13052. /**
  13053. * Constructs a new mesh basic material.
  13054. *
  13055. * @param {Object} [parameters] - An object with one or more properties
  13056. * defining the material's appearance. Any property of the material
  13057. * (including any property from inherited materials) can be passed
  13058. * in here. Color values can be passed any type of value accepted
  13059. * by {@link Color#set}.
  13060. */
  13061. constructor( parameters ) {
  13062. super();
  13063. /**
  13064. * This flag can be used for type testing.
  13065. *
  13066. * @type {boolean}
  13067. * @readonly
  13068. * @default true
  13069. */
  13070. this.isMeshBasicMaterial = true;
  13071. this.type = 'MeshBasicMaterial';
  13072. /**
  13073. * Color of the material.
  13074. *
  13075. * @type {Color}
  13076. * @default (1,1,1)
  13077. */
  13078. this.color = new Color( 0xffffff ); // diffuse
  13079. /**
  13080. * The color map. May optionally include an alpha channel, typically combined
  13081. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13082. * color is modulated by the diffuse `color`.
  13083. *
  13084. * @type {?Texture}
  13085. * @default null
  13086. */
  13087. this.map = null;
  13088. /**
  13089. * The light map. Requires a second set of UVs.
  13090. *
  13091. * @type {?Texture}
  13092. * @default null
  13093. */
  13094. this.lightMap = null;
  13095. /**
  13096. * Intensity of the baked light.
  13097. *
  13098. * @type {number}
  13099. * @default 1
  13100. */
  13101. this.lightMapIntensity = 1.0;
  13102. /**
  13103. * The red channel of this texture is used as the ambient occlusion map.
  13104. * Requires a second set of UVs.
  13105. *
  13106. * @type {?Texture}
  13107. * @default null
  13108. */
  13109. this.aoMap = null;
  13110. /**
  13111. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13112. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13113. * red channel is also `1`, ambient light is fully occluded on a surface.
  13114. *
  13115. * @type {number}
  13116. * @default 1
  13117. */
  13118. this.aoMapIntensity = 1.0;
  13119. /**
  13120. * Specular map used by the material.
  13121. *
  13122. * @type {?Texture}
  13123. * @default null
  13124. */
  13125. this.specularMap = null;
  13126. /**
  13127. * The alpha map is a grayscale texture that controls the opacity across the
  13128. * surface (black: fully transparent; white: fully opaque).
  13129. *
  13130. * Only the color of the texture is used, ignoring the alpha channel if one
  13131. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13132. * when sampling this texture due to the extra bit of precision provided for
  13133. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13134. * luminance/alpha textures will also still work as expected.
  13135. *
  13136. * @type {?Texture}
  13137. * @default null
  13138. */
  13139. this.alphaMap = null;
  13140. /**
  13141. * The environment map.
  13142. *
  13143. * @type {?Texture}
  13144. * @default null
  13145. */
  13146. this.envMap = null;
  13147. /**
  13148. * The rotation of the environment map in radians.
  13149. *
  13150. * @type {Euler}
  13151. * @default (0,0,0)
  13152. */
  13153. this.envMapRotation = new Euler();
  13154. /**
  13155. * How to combine the result of the surface's color with the environment map, if any.
  13156. *
  13157. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13158. * blend between the two colors.
  13159. *
  13160. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13161. * @default MultiplyOperation
  13162. */
  13163. this.combine = MultiplyOperation;
  13164. /**
  13165. * How much the environment map affects the surface.
  13166. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13167. *
  13168. * @type {number}
  13169. * @default 1
  13170. */
  13171. this.reflectivity = 1;
  13172. /**
  13173. * The index of refraction (IOR) of air (approximately 1) divided by the
  13174. * index of refraction of the material. It is used with environment mapping
  13175. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13176. * The refraction ratio should not exceed `1`.
  13177. *
  13178. * @type {number}
  13179. * @default 0.98
  13180. */
  13181. this.refractionRatio = 0.98;
  13182. /**
  13183. * Renders the geometry as a wireframe.
  13184. *
  13185. * @type {boolean}
  13186. * @default false
  13187. */
  13188. this.wireframe = false;
  13189. /**
  13190. * Controls the thickness of the wireframe.
  13191. *
  13192. * Can only be used with {@link SVGRenderer}.
  13193. *
  13194. * @type {number}
  13195. * @default 1
  13196. */
  13197. this.wireframeLinewidth = 1;
  13198. /**
  13199. * Defines appearance of wireframe ends.
  13200. *
  13201. * Can only be used with {@link SVGRenderer}.
  13202. *
  13203. * @type {('round'|'bevel'|'miter')}
  13204. * @default 'round'
  13205. */
  13206. this.wireframeLinecap = 'round';
  13207. /**
  13208. * Defines appearance of wireframe joints.
  13209. *
  13210. * Can only be used with {@link SVGRenderer}.
  13211. *
  13212. * @type {('round'|'bevel'|'miter')}
  13213. * @default 'round'
  13214. */
  13215. this.wireframeLinejoin = 'round';
  13216. /**
  13217. * Whether the material is affected by fog or not.
  13218. *
  13219. * @type {boolean}
  13220. * @default true
  13221. */
  13222. this.fog = true;
  13223. this.setValues( parameters );
  13224. }
  13225. copy( source ) {
  13226. super.copy( source );
  13227. this.color.copy( source.color );
  13228. this.map = source.map;
  13229. this.lightMap = source.lightMap;
  13230. this.lightMapIntensity = source.lightMapIntensity;
  13231. this.aoMap = source.aoMap;
  13232. this.aoMapIntensity = source.aoMapIntensity;
  13233. this.specularMap = source.specularMap;
  13234. this.alphaMap = source.alphaMap;
  13235. this.envMap = source.envMap;
  13236. this.envMapRotation.copy( source.envMapRotation );
  13237. this.combine = source.combine;
  13238. this.reflectivity = source.reflectivity;
  13239. this.refractionRatio = source.refractionRatio;
  13240. this.wireframe = source.wireframe;
  13241. this.wireframeLinewidth = source.wireframeLinewidth;
  13242. this.wireframeLinecap = source.wireframeLinecap;
  13243. this.wireframeLinejoin = source.wireframeLinejoin;
  13244. this.fog = source.fog;
  13245. return this;
  13246. }
  13247. }
  13248. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13249. const _tables = /*@__PURE__*/ _generateTables();
  13250. function _generateTables() {
  13251. // float32 to float16 helpers
  13252. const buffer = new ArrayBuffer( 4 );
  13253. const floatView = new Float32Array( buffer );
  13254. const uint32View = new Uint32Array( buffer );
  13255. const baseTable = new Uint32Array( 512 );
  13256. const shiftTable = new Uint32Array( 512 );
  13257. for ( let i = 0; i < 256; ++ i ) {
  13258. const e = i - 127;
  13259. // very small number (0, -0)
  13260. if ( e < -27 ) {
  13261. baseTable[ i ] = 0x0000;
  13262. baseTable[ i | 0x100 ] = 0x8000;
  13263. shiftTable[ i ] = 24;
  13264. shiftTable[ i | 0x100 ] = 24;
  13265. // small number (denorm)
  13266. } else if ( e < -14 ) {
  13267. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13268. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13269. shiftTable[ i ] = - e - 1;
  13270. shiftTable[ i | 0x100 ] = - e - 1;
  13271. // normal number
  13272. } else if ( e <= 15 ) {
  13273. baseTable[ i ] = ( e + 15 ) << 10;
  13274. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13275. shiftTable[ i ] = 13;
  13276. shiftTable[ i | 0x100 ] = 13;
  13277. // large number (Infinity, -Infinity)
  13278. } else if ( e < 128 ) {
  13279. baseTable[ i ] = 0x7c00;
  13280. baseTable[ i | 0x100 ] = 0xfc00;
  13281. shiftTable[ i ] = 24;
  13282. shiftTable[ i | 0x100 ] = 24;
  13283. // stay (NaN, Infinity, -Infinity)
  13284. } else {
  13285. baseTable[ i ] = 0x7c00;
  13286. baseTable[ i | 0x100 ] = 0xfc00;
  13287. shiftTable[ i ] = 13;
  13288. shiftTable[ i | 0x100 ] = 13;
  13289. }
  13290. }
  13291. // float16 to float32 helpers
  13292. const mantissaTable = new Uint32Array( 2048 );
  13293. const exponentTable = new Uint32Array( 64 );
  13294. const offsetTable = new Uint32Array( 64 );
  13295. for ( let i = 1; i < 1024; ++ i ) {
  13296. let m = i << 13; // zero pad mantissa bits
  13297. let e = 0; // zero exponent
  13298. // normalized
  13299. while ( ( m & 0x00800000 ) === 0 ) {
  13300. m <<= 1;
  13301. e -= 0x00800000; // decrement exponent
  13302. }
  13303. m &= -8388609; // clear leading 1 bit
  13304. e += 0x38800000; // adjust bias
  13305. mantissaTable[ i ] = m | e;
  13306. }
  13307. for ( let i = 1024; i < 2048; ++ i ) {
  13308. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13309. }
  13310. for ( let i = 1; i < 31; ++ i ) {
  13311. exponentTable[ i ] = i << 23;
  13312. }
  13313. exponentTable[ 31 ] = 0x47800000;
  13314. exponentTable[ 32 ] = 0x80000000;
  13315. for ( let i = 33; i < 63; ++ i ) {
  13316. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13317. }
  13318. exponentTable[ 63 ] = 0xc7800000;
  13319. for ( let i = 1; i < 64; ++ i ) {
  13320. if ( i !== 32 ) {
  13321. offsetTable[ i ] = 1024;
  13322. }
  13323. }
  13324. return {
  13325. floatView: floatView,
  13326. uint32View: uint32View,
  13327. baseTable: baseTable,
  13328. shiftTable: shiftTable,
  13329. mantissaTable: mantissaTable,
  13330. exponentTable: exponentTable,
  13331. offsetTable: offsetTable
  13332. };
  13333. }
  13334. /**
  13335. * Returns a half precision floating point value (FP16) from the given single
  13336. * precision floating point value (FP32).
  13337. *
  13338. * @param {number} val - A single precision floating point value.
  13339. * @return {number} The FP16 value.
  13340. */
  13341. function toHalfFloat( val ) {
  13342. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  13343. val = clamp( val, -65504, 65504 );
  13344. _tables.floatView[ 0 ] = val;
  13345. const f = _tables.uint32View[ 0 ];
  13346. const e = ( f >> 23 ) & 0x1ff;
  13347. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13348. }
  13349. /**
  13350. * Returns a single precision floating point value (FP32) from the given half
  13351. * precision floating point value (FP16).
  13352. *
  13353. * @param {number} val - A half precision floating point value.
  13354. * @return {number} The FP32 value.
  13355. */
  13356. function fromHalfFloat( val ) {
  13357. const m = val >> 10;
  13358. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13359. return _tables.floatView[ 0 ];
  13360. }
  13361. /**
  13362. * A class containing utility functions for data.
  13363. *
  13364. * @hideconstructor
  13365. */
  13366. class DataUtils {
  13367. /**
  13368. * Returns a half precision floating point value (FP16) from the given single
  13369. * precision floating point value (FP32).
  13370. *
  13371. * @param {number} val - A single precision floating point value.
  13372. * @return {number} The FP16 value.
  13373. */
  13374. static toHalfFloat( val ) {
  13375. return toHalfFloat( val );
  13376. }
  13377. /**
  13378. * Returns a single precision floating point value (FP32) from the given half
  13379. * precision floating point value (FP16).
  13380. *
  13381. * @param {number} val - A half precision floating point value.
  13382. * @return {number} The FP32 value.
  13383. */
  13384. static fromHalfFloat( val ) {
  13385. return fromHalfFloat( val );
  13386. }
  13387. }
  13388. const _vector$9 = /*@__PURE__*/ new Vector3();
  13389. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13390. let _id$2 = 0;
  13391. /**
  13392. * This class stores data for an attribute (such as vertex positions, face
  13393. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13394. * a geometry, which allows for more efficient passing of data to the GPU.
  13395. *
  13396. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13397. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13398. */
  13399. class BufferAttribute {
  13400. /**
  13401. * Constructs a new buffer attribute.
  13402. *
  13403. * @param {TypedArray} array - The array holding the attribute data.
  13404. * @param {number} itemSize - The item size.
  13405. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13406. */
  13407. constructor( array, itemSize, normalized = false ) {
  13408. if ( Array.isArray( array ) ) {
  13409. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13410. }
  13411. /**
  13412. * This flag can be used for type testing.
  13413. *
  13414. * @type {boolean}
  13415. * @readonly
  13416. * @default true
  13417. */
  13418. this.isBufferAttribute = true;
  13419. /**
  13420. * The ID of the buffer attribute.
  13421. *
  13422. * @name BufferAttribute#id
  13423. * @type {number}
  13424. * @readonly
  13425. */
  13426. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  13427. /**
  13428. * The name of the buffer attribute.
  13429. *
  13430. * @type {string}
  13431. */
  13432. this.name = '';
  13433. /**
  13434. * The array holding the attribute data. It should have `itemSize * numVertices`
  13435. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13436. *
  13437. * @type {TypedArray}
  13438. */
  13439. this.array = array;
  13440. /**
  13441. * The number of values of the array that should be associated with a particular vertex.
  13442. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13443. * normal, or color), then the value should be `3`.
  13444. *
  13445. * @type {number}
  13446. */
  13447. this.itemSize = itemSize;
  13448. /**
  13449. * Represents the number of items this buffer attribute stores. It is internally computed
  13450. * by dividing the `array` length by the `itemSize`.
  13451. *
  13452. * @type {number}
  13453. * @readonly
  13454. */
  13455. this.count = array !== undefined ? array.length / itemSize : 0;
  13456. /**
  13457. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13458. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13459. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13460. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13461. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13462. *
  13463. * @type {boolean}
  13464. */
  13465. this.normalized = normalized;
  13466. /**
  13467. * Defines the intended usage pattern of the data store for optimization purposes.
  13468. *
  13469. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13470. * instantiate a new one and set the desired usage before the next render.
  13471. *
  13472. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13473. * @default StaticDrawUsage
  13474. */
  13475. this.usage = StaticDrawUsage;
  13476. /**
  13477. * This can be used to only update some components of stored vectors (for example, just the
  13478. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13479. *
  13480. * @type {Array<Object>}
  13481. */
  13482. this.updateRanges = [];
  13483. /**
  13484. * Configures the bound GPU type for use in shaders.
  13485. *
  13486. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13487. * For lower precision float types, use `Float16BufferAttribute`.
  13488. *
  13489. * @type {(FloatType|IntType)}
  13490. * @default FloatType
  13491. */
  13492. this.gpuType = FloatType;
  13493. /**
  13494. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13495. *
  13496. * @type {number}
  13497. */
  13498. this.version = 0;
  13499. }
  13500. /**
  13501. * A callback function that is executed after the renderer has transferred the attribute
  13502. * array data to the GPU.
  13503. */
  13504. onUploadCallback() {}
  13505. /**
  13506. * Flag to indicate that this attribute has changed and should be re-sent to
  13507. * the GPU. Set this to `true` when you modify the value of the array.
  13508. *
  13509. * @type {number}
  13510. * @default false
  13511. * @param {boolean} value
  13512. */
  13513. set needsUpdate( value ) {
  13514. if ( value === true ) this.version ++;
  13515. }
  13516. /**
  13517. * Sets the usage of this buffer attribute.
  13518. *
  13519. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13520. * @return {BufferAttribute} A reference to this buffer attribute.
  13521. */
  13522. setUsage( value ) {
  13523. this.usage = value;
  13524. return this;
  13525. }
  13526. /**
  13527. * Adds a range of data in the data array to be updated on the GPU.
  13528. *
  13529. * @param {number} start - Position at which to start update.
  13530. * @param {number} count - The number of components to update.
  13531. */
  13532. addUpdateRange( start, count ) {
  13533. this.updateRanges.push( { start, count } );
  13534. }
  13535. /**
  13536. * Clears the update ranges.
  13537. */
  13538. clearUpdateRanges() {
  13539. this.updateRanges.length = 0;
  13540. }
  13541. /**
  13542. * Copies the values of the given buffer attribute to this instance.
  13543. *
  13544. * @param {BufferAttribute} source - The buffer attribute to copy.
  13545. * @return {BufferAttribute} A reference to this instance.
  13546. */
  13547. copy( source ) {
  13548. this.name = source.name;
  13549. this.array = new source.array.constructor( source.array );
  13550. this.itemSize = source.itemSize;
  13551. this.count = source.count;
  13552. this.normalized = source.normalized;
  13553. this.usage = source.usage;
  13554. this.gpuType = source.gpuType;
  13555. return this;
  13556. }
  13557. /**
  13558. * Copies a vector from the given buffer attribute to this one. The start
  13559. * and destination position in the attribute buffers are represented by the
  13560. * given indices.
  13561. *
  13562. * @param {number} index1 - The destination index into this buffer attribute.
  13563. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13564. * @param {number} index2 - The source index into the given buffer attribute.
  13565. * @return {BufferAttribute} A reference to this instance.
  13566. */
  13567. copyAt( index1, attribute, index2 ) {
  13568. index1 *= this.itemSize;
  13569. index2 *= attribute.itemSize;
  13570. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13571. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13572. }
  13573. return this;
  13574. }
  13575. /**
  13576. * Copies the given array data into this buffer attribute.
  13577. *
  13578. * @param {(TypedArray|Array)} array - The array to copy.
  13579. * @return {BufferAttribute} A reference to this instance.
  13580. */
  13581. copyArray( array ) {
  13582. this.array.set( array );
  13583. return this;
  13584. }
  13585. /**
  13586. * Applies the given 3x3 matrix to the given attribute. Works with
  13587. * item size `2` and `3`.
  13588. *
  13589. * @param {Matrix3} m - The matrix to apply.
  13590. * @return {BufferAttribute} A reference to this instance.
  13591. */
  13592. applyMatrix3( m ) {
  13593. if ( this.itemSize === 2 ) {
  13594. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13595. _vector2$1.fromBufferAttribute( this, i );
  13596. _vector2$1.applyMatrix3( m );
  13597. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13598. }
  13599. } else if ( this.itemSize === 3 ) {
  13600. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13601. _vector$9.fromBufferAttribute( this, i );
  13602. _vector$9.applyMatrix3( m );
  13603. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13604. }
  13605. }
  13606. return this;
  13607. }
  13608. /**
  13609. * Applies the given 4x4 matrix to the given attribute. Only works with
  13610. * item size `3`.
  13611. *
  13612. * @param {Matrix4} m - The matrix to apply.
  13613. * @return {BufferAttribute} A reference to this instance.
  13614. */
  13615. applyMatrix4( m ) {
  13616. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13617. _vector$9.fromBufferAttribute( this, i );
  13618. _vector$9.applyMatrix4( m );
  13619. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13620. }
  13621. return this;
  13622. }
  13623. /**
  13624. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13625. * item size `3`.
  13626. *
  13627. * @param {Matrix3} m - The normal matrix to apply.
  13628. * @return {BufferAttribute} A reference to this instance.
  13629. */
  13630. applyNormalMatrix( m ) {
  13631. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13632. _vector$9.fromBufferAttribute( this, i );
  13633. _vector$9.applyNormalMatrix( m );
  13634. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13635. }
  13636. return this;
  13637. }
  13638. /**
  13639. * Applies the given 4x4 matrix to the given attribute. Only works with
  13640. * item size `3` and with direction vectors.
  13641. *
  13642. * @param {Matrix4} m - The matrix to apply.
  13643. * @return {BufferAttribute} A reference to this instance.
  13644. */
  13645. transformDirection( m ) {
  13646. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13647. _vector$9.fromBufferAttribute( this, i );
  13648. _vector$9.transformDirection( m );
  13649. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13650. }
  13651. return this;
  13652. }
  13653. /**
  13654. * Sets the given array data in the buffer attribute.
  13655. *
  13656. * @param {(TypedArray|Array)} value - The array data to set.
  13657. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13658. * @return {BufferAttribute} A reference to this instance.
  13659. */
  13660. set( value, offset = 0 ) {
  13661. // Matching BufferAttribute constructor, do not normalize the array.
  13662. this.array.set( value, offset );
  13663. return this;
  13664. }
  13665. /**
  13666. * Returns the given component of the vector at the given index.
  13667. *
  13668. * @param {number} index - The index into the buffer attribute.
  13669. * @param {number} component - The component index.
  13670. * @return {number} The returned value.
  13671. */
  13672. getComponent( index, component ) {
  13673. let value = this.array[ index * this.itemSize + component ];
  13674. if ( this.normalized ) value = denormalize( value, this.array );
  13675. return value;
  13676. }
  13677. /**
  13678. * Sets the given value to the given component of the vector at the given index.
  13679. *
  13680. * @param {number} index - The index into the buffer attribute.
  13681. * @param {number} component - The component index.
  13682. * @param {number} value - The value to set.
  13683. * @return {BufferAttribute} A reference to this instance.
  13684. */
  13685. setComponent( index, component, value ) {
  13686. if ( this.normalized ) value = normalize( value, this.array );
  13687. this.array[ index * this.itemSize + component ] = value;
  13688. return this;
  13689. }
  13690. /**
  13691. * Returns the x component of the vector at the given index.
  13692. *
  13693. * @param {number} index - The index into the buffer attribute.
  13694. * @return {number} The x component.
  13695. */
  13696. getX( index ) {
  13697. let x = this.array[ index * this.itemSize ];
  13698. if ( this.normalized ) x = denormalize( x, this.array );
  13699. return x;
  13700. }
  13701. /**
  13702. * Sets the x component of the vector at the given index.
  13703. *
  13704. * @param {number} index - The index into the buffer attribute.
  13705. * @param {number} x - The value to set.
  13706. * @return {BufferAttribute} A reference to this instance.
  13707. */
  13708. setX( index, x ) {
  13709. if ( this.normalized ) x = normalize( x, this.array );
  13710. this.array[ index * this.itemSize ] = x;
  13711. return this;
  13712. }
  13713. /**
  13714. * Returns the y component of the vector at the given index.
  13715. *
  13716. * @param {number} index - The index into the buffer attribute.
  13717. * @return {number} The y component.
  13718. */
  13719. getY( index ) {
  13720. let y = this.array[ index * this.itemSize + 1 ];
  13721. if ( this.normalized ) y = denormalize( y, this.array );
  13722. return y;
  13723. }
  13724. /**
  13725. * Sets the y component of the vector at the given index.
  13726. *
  13727. * @param {number} index - The index into the buffer attribute.
  13728. * @param {number} y - The value to set.
  13729. * @return {BufferAttribute} A reference to this instance.
  13730. */
  13731. setY( index, y ) {
  13732. if ( this.normalized ) y = normalize( y, this.array );
  13733. this.array[ index * this.itemSize + 1 ] = y;
  13734. return this;
  13735. }
  13736. /**
  13737. * Returns the z component of the vector at the given index.
  13738. *
  13739. * @param {number} index - The index into the buffer attribute.
  13740. * @return {number} The z component.
  13741. */
  13742. getZ( index ) {
  13743. let z = this.array[ index * this.itemSize + 2 ];
  13744. if ( this.normalized ) z = denormalize( z, this.array );
  13745. return z;
  13746. }
  13747. /**
  13748. * Sets the z component of the vector at the given index.
  13749. *
  13750. * @param {number} index - The index into the buffer attribute.
  13751. * @param {number} z - The value to set.
  13752. * @return {BufferAttribute} A reference to this instance.
  13753. */
  13754. setZ( index, z ) {
  13755. if ( this.normalized ) z = normalize( z, this.array );
  13756. this.array[ index * this.itemSize + 2 ] = z;
  13757. return this;
  13758. }
  13759. /**
  13760. * Returns the w component of the vector at the given index.
  13761. *
  13762. * @param {number} index - The index into the buffer attribute.
  13763. * @return {number} The w component.
  13764. */
  13765. getW( index ) {
  13766. let w = this.array[ index * this.itemSize + 3 ];
  13767. if ( this.normalized ) w = denormalize( w, this.array );
  13768. return w;
  13769. }
  13770. /**
  13771. * Sets the w component of the vector at the given index.
  13772. *
  13773. * @param {number} index - The index into the buffer attribute.
  13774. * @param {number} w - The value to set.
  13775. * @return {BufferAttribute} A reference to this instance.
  13776. */
  13777. setW( index, w ) {
  13778. if ( this.normalized ) w = normalize( w, this.array );
  13779. this.array[ index * this.itemSize + 3 ] = w;
  13780. return this;
  13781. }
  13782. /**
  13783. * Sets the x and y component of the vector at the given index.
  13784. *
  13785. * @param {number} index - The index into the buffer attribute.
  13786. * @param {number} x - The value for the x component to set.
  13787. * @param {number} y - The value for the y component to set.
  13788. * @return {BufferAttribute} A reference to this instance.
  13789. */
  13790. setXY( index, x, y ) {
  13791. index *= this.itemSize;
  13792. if ( this.normalized ) {
  13793. x = normalize( x, this.array );
  13794. y = normalize( y, this.array );
  13795. }
  13796. this.array[ index + 0 ] = x;
  13797. this.array[ index + 1 ] = y;
  13798. return this;
  13799. }
  13800. /**
  13801. * Sets the x, y and z component of the vector at the given index.
  13802. *
  13803. * @param {number} index - The index into the buffer attribute.
  13804. * @param {number} x - The value for the x component to set.
  13805. * @param {number} y - The value for the y component to set.
  13806. * @param {number} z - The value for the z component to set.
  13807. * @return {BufferAttribute} A reference to this instance.
  13808. */
  13809. setXYZ( index, x, y, z ) {
  13810. index *= this.itemSize;
  13811. if ( this.normalized ) {
  13812. x = normalize( x, this.array );
  13813. y = normalize( y, this.array );
  13814. z = normalize( z, this.array );
  13815. }
  13816. this.array[ index + 0 ] = x;
  13817. this.array[ index + 1 ] = y;
  13818. this.array[ index + 2 ] = z;
  13819. return this;
  13820. }
  13821. /**
  13822. * Sets the x, y, z and w component of the vector at the given index.
  13823. *
  13824. * @param {number} index - The index into the buffer attribute.
  13825. * @param {number} x - The value for the x component to set.
  13826. * @param {number} y - The value for the y component to set.
  13827. * @param {number} z - The value for the z component to set.
  13828. * @param {number} w - The value for the w component to set.
  13829. * @return {BufferAttribute} A reference to this instance.
  13830. */
  13831. setXYZW( index, x, y, z, w ) {
  13832. index *= this.itemSize;
  13833. if ( this.normalized ) {
  13834. x = normalize( x, this.array );
  13835. y = normalize( y, this.array );
  13836. z = normalize( z, this.array );
  13837. w = normalize( w, this.array );
  13838. }
  13839. this.array[ index + 0 ] = x;
  13840. this.array[ index + 1 ] = y;
  13841. this.array[ index + 2 ] = z;
  13842. this.array[ index + 3 ] = w;
  13843. return this;
  13844. }
  13845. /**
  13846. * Sets the given callback function that is executed after the Renderer has transferred
  13847. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13848. * the upload when attribute data are not needed anymore on the CPU side.
  13849. *
  13850. * @param {Function} callback - The `onUpload()` callback.
  13851. * @return {BufferAttribute} A reference to this instance.
  13852. */
  13853. onUpload( callback ) {
  13854. this.onUploadCallback = callback;
  13855. return this;
  13856. }
  13857. /**
  13858. * Returns a new buffer attribute with copied values from this instance.
  13859. *
  13860. * @return {BufferAttribute} A clone of this instance.
  13861. */
  13862. clone() {
  13863. return new this.constructor( this.array, this.itemSize ).copy( this );
  13864. }
  13865. /**
  13866. * Serializes the buffer attribute into JSON.
  13867. *
  13868. * @return {Object} A JSON object representing the serialized buffer attribute.
  13869. */
  13870. toJSON() {
  13871. const data = {
  13872. itemSize: this.itemSize,
  13873. type: this.array.constructor.name,
  13874. array: Array.from( this.array ),
  13875. normalized: this.normalized
  13876. };
  13877. if ( this.name !== '' ) data.name = this.name;
  13878. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13879. return data;
  13880. }
  13881. }
  13882. /**
  13883. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13884. * a plain `Array` instance.
  13885. *
  13886. * @augments BufferAttribute
  13887. */
  13888. class Int8BufferAttribute extends BufferAttribute {
  13889. /**
  13890. * Constructs a new buffer attribute.
  13891. *
  13892. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13893. * @param {number} itemSize - The item size.
  13894. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13895. */
  13896. constructor( array, itemSize, normalized ) {
  13897. super( new Int8Array( array ), itemSize, normalized );
  13898. }
  13899. }
  13900. /**
  13901. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13902. * a plain `Array` instance.
  13903. *
  13904. * @augments BufferAttribute
  13905. */
  13906. class Uint8BufferAttribute extends BufferAttribute {
  13907. /**
  13908. * Constructs a new buffer attribute.
  13909. *
  13910. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13911. * @param {number} itemSize - The item size.
  13912. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13913. */
  13914. constructor( array, itemSize, normalized ) {
  13915. super( new Uint8Array( array ), itemSize, normalized );
  13916. }
  13917. }
  13918. /**
  13919. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13920. * a plain `Array` instance.
  13921. *
  13922. * @augments BufferAttribute
  13923. */
  13924. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13925. /**
  13926. * Constructs a new buffer attribute.
  13927. *
  13928. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13929. * @param {number} itemSize - The item size.
  13930. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13931. */
  13932. constructor( array, itemSize, normalized ) {
  13933. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13934. }
  13935. }
  13936. /**
  13937. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13938. * a plain `Array` instance.
  13939. *
  13940. * @augments BufferAttribute
  13941. */
  13942. class Int16BufferAttribute extends BufferAttribute {
  13943. /**
  13944. * Constructs a new buffer attribute.
  13945. *
  13946. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13947. * @param {number} itemSize - The item size.
  13948. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13949. */
  13950. constructor( array, itemSize, normalized ) {
  13951. super( new Int16Array( array ), itemSize, normalized );
  13952. }
  13953. }
  13954. /**
  13955. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13956. * a plain `Array` instance.
  13957. *
  13958. * @augments BufferAttribute
  13959. */
  13960. class Uint16BufferAttribute extends BufferAttribute {
  13961. /**
  13962. * Constructs a new buffer attribute.
  13963. *
  13964. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13965. * @param {number} itemSize - The item size.
  13966. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13967. */
  13968. constructor( array, itemSize, normalized ) {
  13969. super( new Uint16Array( array ), itemSize, normalized );
  13970. }
  13971. }
  13972. /**
  13973. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13974. * a plain `Array` instance.
  13975. *
  13976. * @augments BufferAttribute
  13977. */
  13978. class Int32BufferAttribute extends BufferAttribute {
  13979. /**
  13980. * Constructs a new buffer attribute.
  13981. *
  13982. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13983. * @param {number} itemSize - The item size.
  13984. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13985. */
  13986. constructor( array, itemSize, normalized ) {
  13987. super( new Int32Array( array ), itemSize, normalized );
  13988. }
  13989. }
  13990. /**
  13991. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13992. * a plain `Array` instance.
  13993. *
  13994. * @augments BufferAttribute
  13995. */
  13996. class Uint32BufferAttribute extends BufferAttribute {
  13997. /**
  13998. * Constructs a new buffer attribute.
  13999. *
  14000. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14001. * @param {number} itemSize - The item size.
  14002. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14003. */
  14004. constructor( array, itemSize, normalized ) {
  14005. super( new Uint32Array( array ), itemSize, normalized );
  14006. }
  14007. }
  14008. /**
  14009. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14010. * a plain `Array` instance.
  14011. *
  14012. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14013. * browser support is still problematic.
  14014. *
  14015. * @augments BufferAttribute
  14016. */
  14017. class Float16BufferAttribute extends BufferAttribute {
  14018. /**
  14019. * Constructs a new buffer attribute.
  14020. *
  14021. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14022. * @param {number} itemSize - The item size.
  14023. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14024. */
  14025. constructor( array, itemSize, normalized ) {
  14026. super( new Uint16Array( array ), itemSize, normalized );
  14027. this.isFloat16BufferAttribute = true;
  14028. }
  14029. getX( index ) {
  14030. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14031. if ( this.normalized ) x = denormalize( x, this.array );
  14032. return x;
  14033. }
  14034. setX( index, x ) {
  14035. if ( this.normalized ) x = normalize( x, this.array );
  14036. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14037. return this;
  14038. }
  14039. getY( index ) {
  14040. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14041. if ( this.normalized ) y = denormalize( y, this.array );
  14042. return y;
  14043. }
  14044. setY( index, y ) {
  14045. if ( this.normalized ) y = normalize( y, this.array );
  14046. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14047. return this;
  14048. }
  14049. getZ( index ) {
  14050. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14051. if ( this.normalized ) z = denormalize( z, this.array );
  14052. return z;
  14053. }
  14054. setZ( index, z ) {
  14055. if ( this.normalized ) z = normalize( z, this.array );
  14056. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14057. return this;
  14058. }
  14059. getW( index ) {
  14060. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14061. if ( this.normalized ) w = denormalize( w, this.array );
  14062. return w;
  14063. }
  14064. setW( index, w ) {
  14065. if ( this.normalized ) w = normalize( w, this.array );
  14066. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14067. return this;
  14068. }
  14069. setXY( index, x, y ) {
  14070. index *= this.itemSize;
  14071. if ( this.normalized ) {
  14072. x = normalize( x, this.array );
  14073. y = normalize( y, this.array );
  14074. }
  14075. this.array[ index + 0 ] = toHalfFloat( x );
  14076. this.array[ index + 1 ] = toHalfFloat( y );
  14077. return this;
  14078. }
  14079. setXYZ( index, x, y, z ) {
  14080. index *= this.itemSize;
  14081. if ( this.normalized ) {
  14082. x = normalize( x, this.array );
  14083. y = normalize( y, this.array );
  14084. z = normalize( z, this.array );
  14085. }
  14086. this.array[ index + 0 ] = toHalfFloat( x );
  14087. this.array[ index + 1 ] = toHalfFloat( y );
  14088. this.array[ index + 2 ] = toHalfFloat( z );
  14089. return this;
  14090. }
  14091. setXYZW( index, x, y, z, w ) {
  14092. index *= this.itemSize;
  14093. if ( this.normalized ) {
  14094. x = normalize( x, this.array );
  14095. y = normalize( y, this.array );
  14096. z = normalize( z, this.array );
  14097. w = normalize( w, this.array );
  14098. }
  14099. this.array[ index + 0 ] = toHalfFloat( x );
  14100. this.array[ index + 1 ] = toHalfFloat( y );
  14101. this.array[ index + 2 ] = toHalfFloat( z );
  14102. this.array[ index + 3 ] = toHalfFloat( w );
  14103. return this;
  14104. }
  14105. }
  14106. /**
  14107. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14108. * a plain `Array` instance.
  14109. *
  14110. * @augments BufferAttribute
  14111. */
  14112. class Float32BufferAttribute extends BufferAttribute {
  14113. /**
  14114. * Constructs a new buffer attribute.
  14115. *
  14116. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14117. * @param {number} itemSize - The item size.
  14118. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14119. */
  14120. constructor( array, itemSize, normalized ) {
  14121. super( new Float32Array( array ), itemSize, normalized );
  14122. }
  14123. }
  14124. let _id$1 = 0;
  14125. const _m1 = /*@__PURE__*/ new Matrix4();
  14126. const _obj = /*@__PURE__*/ new Object3D();
  14127. const _offset = /*@__PURE__*/ new Vector3();
  14128. const _box$2 = /*@__PURE__*/ new Box3();
  14129. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14130. const _vector$8 = /*@__PURE__*/ new Vector3();
  14131. /**
  14132. * A representation of mesh, line, or point geometry. Includes vertex
  14133. * positions, face indices, normals, colors, UVs, and custom attributes
  14134. * within buffers, reducing the cost of passing all this data to the GPU.
  14135. *
  14136. * ```js
  14137. * const geometry = new THREE.BufferGeometry();
  14138. * // create a simple square shape. We duplicate the top left and bottom right
  14139. * // vertices because each vertex needs to appear once per triangle.
  14140. * const vertices = new Float32Array( [
  14141. * -1.0, -1.0, 1.0, // v0
  14142. * 1.0, -1.0, 1.0, // v1
  14143. * 1.0, 1.0, 1.0, // v2
  14144. *
  14145. * 1.0, 1.0, 1.0, // v3
  14146. * -1.0, 1.0, 1.0, // v4
  14147. * -1.0, -1.0, 1.0 // v5
  14148. * ] );
  14149. * // itemSize = 3 because there are 3 values (components) per vertex
  14150. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14151. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14152. * const mesh = new THREE.Mesh( geometry, material );
  14153. * ```
  14154. *
  14155. * @augments EventDispatcher
  14156. */
  14157. class BufferGeometry extends EventDispatcher {
  14158. /**
  14159. * Constructs a new geometry.
  14160. */
  14161. constructor() {
  14162. super();
  14163. /**
  14164. * This flag can be used for type testing.
  14165. *
  14166. * @type {boolean}
  14167. * @readonly
  14168. * @default true
  14169. */
  14170. this.isBufferGeometry = true;
  14171. /**
  14172. * The ID of the geometry.
  14173. *
  14174. * @name BufferGeometry#id
  14175. * @type {number}
  14176. * @readonly
  14177. */
  14178. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  14179. /**
  14180. * The UUID of the geometry.
  14181. *
  14182. * @type {string}
  14183. * @readonly
  14184. */
  14185. this.uuid = generateUUID();
  14186. /**
  14187. * The name of the geometry.
  14188. *
  14189. * @type {string}
  14190. */
  14191. this.name = '';
  14192. this.type = 'BufferGeometry';
  14193. /**
  14194. * Allows for vertices to be re-used across multiple triangles; this is
  14195. * called using "indexed triangles". Each triangle is associated with the
  14196. * indices of three vertices. This attribute therefore stores the index of
  14197. * each vertex for each triangular face. If this attribute is not set, the
  14198. * renderer assumes that each three contiguous positions represent a single triangle.
  14199. *
  14200. * @type {?BufferAttribute}
  14201. * @default null
  14202. */
  14203. this.index = null;
  14204. /**
  14205. * A (storage) buffer attribute which was generated with a compute shader and
  14206. * now defines indirect draw calls.
  14207. *
  14208. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14209. *
  14210. * @type {?BufferAttribute}
  14211. * @default null
  14212. */
  14213. this.indirect = null;
  14214. /**
  14215. * This dictionary has as id the name of the attribute to be set and as value
  14216. * the buffer attribute to set it to. Rather than accessing this property directly,
  14217. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14218. *
  14219. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14220. */
  14221. this.attributes = {};
  14222. /**
  14223. * This dictionary holds the morph targets of the geometry.
  14224. *
  14225. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14226. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14227. *
  14228. * @type {Object}
  14229. */
  14230. this.morphAttributes = {};
  14231. /**
  14232. * Used to control the morph target behavior; when set to `true`, the morph
  14233. * target data is treated as relative offsets, rather than as absolute
  14234. * positions/normals.
  14235. *
  14236. * @type {boolean}
  14237. * @default false
  14238. */
  14239. this.morphTargetsRelative = false;
  14240. /**
  14241. * Split the geometry into groups, each of which will be rendered in a
  14242. * separate draw call. This allows an array of materials to be used with the geometry.
  14243. *
  14244. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14245. *
  14246. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14247. * indices, and must not leave vertices or indices unused.
  14248. *
  14249. * @type {Array<Object>}
  14250. */
  14251. this.groups = [];
  14252. /**
  14253. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14254. *
  14255. * @type {Box3}
  14256. * @default null
  14257. */
  14258. this.boundingBox = null;
  14259. /**
  14260. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14261. *
  14262. * @type {Sphere}
  14263. * @default null
  14264. */
  14265. this.boundingSphere = null;
  14266. /**
  14267. * Determines the part of the geometry to render. This should not be set directly,
  14268. * instead use `setDrawRange()`.
  14269. *
  14270. * @type {{start:number,count:number}}
  14271. */
  14272. this.drawRange = { start: 0, count: Infinity };
  14273. /**
  14274. * An object that can be used to store custom data about the geometry.
  14275. * It should not hold references to functions as these will not be cloned.
  14276. *
  14277. * @type {Object}
  14278. */
  14279. this.userData = {};
  14280. }
  14281. /**
  14282. * Returns the index of this geometry.
  14283. *
  14284. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14285. */
  14286. getIndex() {
  14287. return this.index;
  14288. }
  14289. /**
  14290. * Sets the given index to this geometry.
  14291. *
  14292. * @param {Array<number>|BufferAttribute} index - The index to set.
  14293. * @return {BufferGeometry} A reference to this instance.
  14294. */
  14295. setIndex( index ) {
  14296. if ( Array.isArray( index ) ) {
  14297. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14298. } else {
  14299. this.index = index;
  14300. }
  14301. return this;
  14302. }
  14303. /**
  14304. * Sets the given indirect attribute to this geometry.
  14305. *
  14306. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14307. * @return {BufferGeometry} A reference to this instance.
  14308. */
  14309. setIndirect( indirect ) {
  14310. this.indirect = indirect;
  14311. return this;
  14312. }
  14313. /**
  14314. * Returns the indirect attribute of this geometry.
  14315. *
  14316. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14317. */
  14318. getIndirect() {
  14319. return this.indirect;
  14320. }
  14321. /**
  14322. * Returns the buffer attribute for the given name.
  14323. *
  14324. * @param {string} name - The attribute name.
  14325. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14326. * Returns `undefined` if not attribute has been found.
  14327. */
  14328. getAttribute( name ) {
  14329. return this.attributes[ name ];
  14330. }
  14331. /**
  14332. * Sets the given attribute for the given name.
  14333. *
  14334. * @param {string} name - The attribute name.
  14335. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14336. * @return {BufferGeometry} A reference to this instance.
  14337. */
  14338. setAttribute( name, attribute ) {
  14339. this.attributes[ name ] = attribute;
  14340. return this;
  14341. }
  14342. /**
  14343. * Deletes the attribute for the given name.
  14344. *
  14345. * @param {string} name - The attribute name to delete.
  14346. * @return {BufferGeometry} A reference to this instance.
  14347. */
  14348. deleteAttribute( name ) {
  14349. delete this.attributes[ name ];
  14350. return this;
  14351. }
  14352. /**
  14353. * Returns `true` if this geometry has an attribute for the given name.
  14354. *
  14355. * @param {string} name - The attribute name.
  14356. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14357. */
  14358. hasAttribute( name ) {
  14359. return this.attributes[ name ] !== undefined;
  14360. }
  14361. /**
  14362. * Adds a group to this geometry.
  14363. *
  14364. * @param {number} start - The first element in this draw call. That is the first
  14365. * vertex for non-indexed geometry, otherwise the first triangle index.
  14366. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14367. * @param {number} [materialIndex=0] - The material array index to use.
  14368. */
  14369. addGroup( start, count, materialIndex = 0 ) {
  14370. this.groups.push( {
  14371. start: start,
  14372. count: count,
  14373. materialIndex: materialIndex
  14374. } );
  14375. }
  14376. /**
  14377. * Clears all groups.
  14378. */
  14379. clearGroups() {
  14380. this.groups = [];
  14381. }
  14382. /**
  14383. * Sets the draw range for this geometry.
  14384. *
  14385. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14386. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14387. * For indexed BufferGeometry, `count` is the number of indices to render.
  14388. */
  14389. setDrawRange( start, count ) {
  14390. this.drawRange.start = start;
  14391. this.drawRange.count = count;
  14392. }
  14393. /**
  14394. * Applies the given 4x4 transformation matrix to the geometry.
  14395. *
  14396. * @param {Matrix4} matrix - The matrix to apply.
  14397. * @return {BufferGeometry} A reference to this instance.
  14398. */
  14399. applyMatrix4( matrix ) {
  14400. const position = this.attributes.position;
  14401. if ( position !== undefined ) {
  14402. position.applyMatrix4( matrix );
  14403. position.needsUpdate = true;
  14404. }
  14405. const normal = this.attributes.normal;
  14406. if ( normal !== undefined ) {
  14407. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14408. normal.applyNormalMatrix( normalMatrix );
  14409. normal.needsUpdate = true;
  14410. }
  14411. const tangent = this.attributes.tangent;
  14412. if ( tangent !== undefined ) {
  14413. tangent.transformDirection( matrix );
  14414. tangent.needsUpdate = true;
  14415. }
  14416. if ( this.boundingBox !== null ) {
  14417. this.computeBoundingBox();
  14418. }
  14419. if ( this.boundingSphere !== null ) {
  14420. this.computeBoundingSphere();
  14421. }
  14422. return this;
  14423. }
  14424. /**
  14425. * Applies the rotation represented by the Quaternion to the geometry.
  14426. *
  14427. * @param {Quaternion} q - The Quaternion to apply.
  14428. * @return {BufferGeometry} A reference to this instance.
  14429. */
  14430. applyQuaternion( q ) {
  14431. _m1.makeRotationFromQuaternion( q );
  14432. this.applyMatrix4( _m1 );
  14433. return this;
  14434. }
  14435. /**
  14436. * Rotates the geometry about the X axis. This is typically done as a one time
  14437. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14438. * real-time mesh rotation.
  14439. *
  14440. * @param {number} angle - The angle in radians.
  14441. * @return {BufferGeometry} A reference to this instance.
  14442. */
  14443. rotateX( angle ) {
  14444. // rotate geometry around world x-axis
  14445. _m1.makeRotationX( angle );
  14446. this.applyMatrix4( _m1 );
  14447. return this;
  14448. }
  14449. /**
  14450. * Rotates the geometry about the Y axis. This is typically done as a one time
  14451. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14452. * real-time mesh rotation.
  14453. *
  14454. * @param {number} angle - The angle in radians.
  14455. * @return {BufferGeometry} A reference to this instance.
  14456. */
  14457. rotateY( angle ) {
  14458. // rotate geometry around world y-axis
  14459. _m1.makeRotationY( angle );
  14460. this.applyMatrix4( _m1 );
  14461. return this;
  14462. }
  14463. /**
  14464. * Rotates the geometry about the Z axis. This is typically done as a one time
  14465. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14466. * real-time mesh rotation.
  14467. *
  14468. * @param {number} angle - The angle in radians.
  14469. * @return {BufferGeometry} A reference to this instance.
  14470. */
  14471. rotateZ( angle ) {
  14472. // rotate geometry around world z-axis
  14473. _m1.makeRotationZ( angle );
  14474. this.applyMatrix4( _m1 );
  14475. return this;
  14476. }
  14477. /**
  14478. * Translates the geometry. This is typically done as a one time
  14479. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14480. * real-time mesh rotation.
  14481. *
  14482. * @param {number} x - The x offset.
  14483. * @param {number} y - The y offset.
  14484. * @param {number} z - The z offset.
  14485. * @return {BufferGeometry} A reference to this instance.
  14486. */
  14487. translate( x, y, z ) {
  14488. // translate geometry
  14489. _m1.makeTranslation( x, y, z );
  14490. this.applyMatrix4( _m1 );
  14491. return this;
  14492. }
  14493. /**
  14494. * Scales the geometry. This is typically done as a one time
  14495. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14496. * real-time mesh rotation.
  14497. *
  14498. * @param {number} x - The x scale.
  14499. * @param {number} y - The y scale.
  14500. * @param {number} z - The z scale.
  14501. * @return {BufferGeometry} A reference to this instance.
  14502. */
  14503. scale( x, y, z ) {
  14504. // scale geometry
  14505. _m1.makeScale( x, y, z );
  14506. this.applyMatrix4( _m1 );
  14507. return this;
  14508. }
  14509. /**
  14510. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14511. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14512. * real-time mesh rotation.
  14513. *
  14514. * @param {Vector3} vector - The target point.
  14515. * @return {BufferGeometry} A reference to this instance.
  14516. */
  14517. lookAt( vector ) {
  14518. _obj.lookAt( vector );
  14519. _obj.updateMatrix();
  14520. this.applyMatrix4( _obj.matrix );
  14521. return this;
  14522. }
  14523. /**
  14524. * Center the geometry based on its bounding box.
  14525. *
  14526. * @return {BufferGeometry} A reference to this instance.
  14527. */
  14528. center() {
  14529. this.computeBoundingBox();
  14530. this.boundingBox.getCenter( _offset ).negate();
  14531. this.translate( _offset.x, _offset.y, _offset.z );
  14532. return this;
  14533. }
  14534. /**
  14535. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14536. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14537. * set to `0`.
  14538. *
  14539. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14540. * data from the array. The length of the array must match the vertex count.
  14541. *
  14542. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14543. * @return {BufferGeometry} A reference to this instance.
  14544. */
  14545. setFromPoints( points ) {
  14546. const positionAttribute = this.getAttribute( 'position' );
  14547. if ( positionAttribute === undefined ) {
  14548. const position = [];
  14549. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14550. const point = points[ i ];
  14551. position.push( point.x, point.y, point.z || 0 );
  14552. }
  14553. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14554. } else {
  14555. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14556. for ( let i = 0; i < l; i ++ ) {
  14557. const point = points[ i ];
  14558. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14559. }
  14560. if ( points.length > positionAttribute.count ) {
  14561. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14562. }
  14563. positionAttribute.needsUpdate = true;
  14564. }
  14565. return this;
  14566. }
  14567. /**
  14568. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14569. * The bounding box is not computed by the engine; it must be computed by your app.
  14570. * You may need to recompute the bounding box if the geometry vertices are modified.
  14571. */
  14572. computeBoundingBox() {
  14573. if ( this.boundingBox === null ) {
  14574. this.boundingBox = new Box3();
  14575. }
  14576. const position = this.attributes.position;
  14577. const morphAttributesPosition = this.morphAttributes.position;
  14578. if ( position && position.isGLBufferAttribute ) {
  14579. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14580. this.boundingBox.set(
  14581. new Vector3( - Infinity, - Infinity, - Infinity ),
  14582. new Vector3( + Infinity, + Infinity, + Infinity )
  14583. );
  14584. return;
  14585. }
  14586. if ( position !== undefined ) {
  14587. this.boundingBox.setFromBufferAttribute( position );
  14588. // process morph attributes if present
  14589. if ( morphAttributesPosition ) {
  14590. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14591. const morphAttribute = morphAttributesPosition[ i ];
  14592. _box$2.setFromBufferAttribute( morphAttribute );
  14593. if ( this.morphTargetsRelative ) {
  14594. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14595. this.boundingBox.expandByPoint( _vector$8 );
  14596. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14597. this.boundingBox.expandByPoint( _vector$8 );
  14598. } else {
  14599. this.boundingBox.expandByPoint( _box$2.min );
  14600. this.boundingBox.expandByPoint( _box$2.max );
  14601. }
  14602. }
  14603. }
  14604. } else {
  14605. this.boundingBox.makeEmpty();
  14606. }
  14607. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14608. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14609. }
  14610. }
  14611. /**
  14612. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14613. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14614. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14615. */
  14616. computeBoundingSphere() {
  14617. if ( this.boundingSphere === null ) {
  14618. this.boundingSphere = new Sphere();
  14619. }
  14620. const position = this.attributes.position;
  14621. const morphAttributesPosition = this.morphAttributes.position;
  14622. if ( position && position.isGLBufferAttribute ) {
  14623. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14624. this.boundingSphere.set( new Vector3(), Infinity );
  14625. return;
  14626. }
  14627. if ( position ) {
  14628. // first, find the center of the bounding sphere
  14629. const center = this.boundingSphere.center;
  14630. _box$2.setFromBufferAttribute( position );
  14631. // process morph attributes if present
  14632. if ( morphAttributesPosition ) {
  14633. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14634. const morphAttribute = morphAttributesPosition[ i ];
  14635. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14636. if ( this.morphTargetsRelative ) {
  14637. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14638. _box$2.expandByPoint( _vector$8 );
  14639. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14640. _box$2.expandByPoint( _vector$8 );
  14641. } else {
  14642. _box$2.expandByPoint( _boxMorphTargets.min );
  14643. _box$2.expandByPoint( _boxMorphTargets.max );
  14644. }
  14645. }
  14646. }
  14647. _box$2.getCenter( center );
  14648. // second, try to find a boundingSphere with a radius smaller than the
  14649. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14650. let maxRadiusSq = 0;
  14651. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14652. _vector$8.fromBufferAttribute( position, i );
  14653. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14654. }
  14655. // process morph attributes if present
  14656. if ( morphAttributesPosition ) {
  14657. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14658. const morphAttribute = morphAttributesPosition[ i ];
  14659. const morphTargetsRelative = this.morphTargetsRelative;
  14660. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14661. _vector$8.fromBufferAttribute( morphAttribute, j );
  14662. if ( morphTargetsRelative ) {
  14663. _offset.fromBufferAttribute( position, j );
  14664. _vector$8.add( _offset );
  14665. }
  14666. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14667. }
  14668. }
  14669. }
  14670. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14671. if ( isNaN( this.boundingSphere.radius ) ) {
  14672. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14673. }
  14674. }
  14675. }
  14676. /**
  14677. * Calculates and adds a tangent attribute to this geometry.
  14678. *
  14679. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14680. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14681. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14682. */
  14683. computeTangents() {
  14684. const index = this.index;
  14685. const attributes = this.attributes;
  14686. // based on http://www.terathon.com/code/tangent.html
  14687. // (per vertex tangents)
  14688. if ( index === null ||
  14689. attributes.position === undefined ||
  14690. attributes.normal === undefined ||
  14691. attributes.uv === undefined ) {
  14692. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14693. return;
  14694. }
  14695. const positionAttribute = attributes.position;
  14696. const normalAttribute = attributes.normal;
  14697. const uvAttribute = attributes.uv;
  14698. if ( this.hasAttribute( 'tangent' ) === false ) {
  14699. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14700. }
  14701. const tangentAttribute = this.getAttribute( 'tangent' );
  14702. const tan1 = [], tan2 = [];
  14703. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14704. tan1[ i ] = new Vector3();
  14705. tan2[ i ] = new Vector3();
  14706. }
  14707. const vA = new Vector3(),
  14708. vB = new Vector3(),
  14709. vC = new Vector3(),
  14710. uvA = new Vector2(),
  14711. uvB = new Vector2(),
  14712. uvC = new Vector2(),
  14713. sdir = new Vector3(),
  14714. tdir = new Vector3();
  14715. function handleTriangle( a, b, c ) {
  14716. vA.fromBufferAttribute( positionAttribute, a );
  14717. vB.fromBufferAttribute( positionAttribute, b );
  14718. vC.fromBufferAttribute( positionAttribute, c );
  14719. uvA.fromBufferAttribute( uvAttribute, a );
  14720. uvB.fromBufferAttribute( uvAttribute, b );
  14721. uvC.fromBufferAttribute( uvAttribute, c );
  14722. vB.sub( vA );
  14723. vC.sub( vA );
  14724. uvB.sub( uvA );
  14725. uvC.sub( uvA );
  14726. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14727. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14728. if ( ! isFinite( r ) ) return;
  14729. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14730. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14731. tan1[ a ].add( sdir );
  14732. tan1[ b ].add( sdir );
  14733. tan1[ c ].add( sdir );
  14734. tan2[ a ].add( tdir );
  14735. tan2[ b ].add( tdir );
  14736. tan2[ c ].add( tdir );
  14737. }
  14738. let groups = this.groups;
  14739. if ( groups.length === 0 ) {
  14740. groups = [ {
  14741. start: 0,
  14742. count: index.count
  14743. } ];
  14744. }
  14745. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14746. const group = groups[ i ];
  14747. const start = group.start;
  14748. const count = group.count;
  14749. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14750. handleTriangle(
  14751. index.getX( j + 0 ),
  14752. index.getX( j + 1 ),
  14753. index.getX( j + 2 )
  14754. );
  14755. }
  14756. }
  14757. const tmp = new Vector3(), tmp2 = new Vector3();
  14758. const n = new Vector3(), n2 = new Vector3();
  14759. function handleVertex( v ) {
  14760. n.fromBufferAttribute( normalAttribute, v );
  14761. n2.copy( n );
  14762. const t = tan1[ v ];
  14763. // Gram-Schmidt orthogonalize
  14764. tmp.copy( t );
  14765. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14766. // Calculate handedness
  14767. tmp2.crossVectors( n2, t );
  14768. const test = tmp2.dot( tan2[ v ] );
  14769. const w = ( test < 0.0 ) ? -1 : 1.0;
  14770. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14771. }
  14772. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14773. const group = groups[ i ];
  14774. const start = group.start;
  14775. const count = group.count;
  14776. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14777. handleVertex( index.getX( j + 0 ) );
  14778. handleVertex( index.getX( j + 1 ) );
  14779. handleVertex( index.getX( j + 2 ) );
  14780. }
  14781. }
  14782. }
  14783. /**
  14784. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14785. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14786. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14787. * to be the same as the face normal.
  14788. */
  14789. computeVertexNormals() {
  14790. const index = this.index;
  14791. const positionAttribute = this.getAttribute( 'position' );
  14792. if ( positionAttribute !== undefined ) {
  14793. let normalAttribute = this.getAttribute( 'normal' );
  14794. if ( normalAttribute === undefined ) {
  14795. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14796. this.setAttribute( 'normal', normalAttribute );
  14797. } else {
  14798. // reset existing normals to zero
  14799. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14800. normalAttribute.setXYZ( i, 0, 0, 0 );
  14801. }
  14802. }
  14803. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14804. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14805. const cb = new Vector3(), ab = new Vector3();
  14806. // indexed elements
  14807. if ( index ) {
  14808. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14809. const vA = index.getX( i + 0 );
  14810. const vB = index.getX( i + 1 );
  14811. const vC = index.getX( i + 2 );
  14812. pA.fromBufferAttribute( positionAttribute, vA );
  14813. pB.fromBufferAttribute( positionAttribute, vB );
  14814. pC.fromBufferAttribute( positionAttribute, vC );
  14815. cb.subVectors( pC, pB );
  14816. ab.subVectors( pA, pB );
  14817. cb.cross( ab );
  14818. nA.fromBufferAttribute( normalAttribute, vA );
  14819. nB.fromBufferAttribute( normalAttribute, vB );
  14820. nC.fromBufferAttribute( normalAttribute, vC );
  14821. nA.add( cb );
  14822. nB.add( cb );
  14823. nC.add( cb );
  14824. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14825. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14826. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14827. }
  14828. } else {
  14829. // non-indexed elements (unconnected triangle soup)
  14830. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14831. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14832. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14833. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14834. cb.subVectors( pC, pB );
  14835. ab.subVectors( pA, pB );
  14836. cb.cross( ab );
  14837. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14838. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14839. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14840. }
  14841. }
  14842. this.normalizeNormals();
  14843. normalAttribute.needsUpdate = true;
  14844. }
  14845. }
  14846. /**
  14847. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14848. * correct lighting on the geometry surfaces.
  14849. */
  14850. normalizeNormals() {
  14851. const normals = this.attributes.normal;
  14852. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14853. _vector$8.fromBufferAttribute( normals, i );
  14854. _vector$8.normalize();
  14855. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14856. }
  14857. }
  14858. /**
  14859. * Return a new non-index version of this indexed geometry. If the geometry
  14860. * is already non-indexed, the method is a NOOP.
  14861. *
  14862. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14863. */
  14864. toNonIndexed() {
  14865. function convertBufferAttribute( attribute, indices ) {
  14866. const array = attribute.array;
  14867. const itemSize = attribute.itemSize;
  14868. const normalized = attribute.normalized;
  14869. const array2 = new array.constructor( indices.length * itemSize );
  14870. let index = 0, index2 = 0;
  14871. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14872. if ( attribute.isInterleavedBufferAttribute ) {
  14873. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14874. } else {
  14875. index = indices[ i ] * itemSize;
  14876. }
  14877. for ( let j = 0; j < itemSize; j ++ ) {
  14878. array2[ index2 ++ ] = array[ index ++ ];
  14879. }
  14880. }
  14881. return new BufferAttribute( array2, itemSize, normalized );
  14882. }
  14883. //
  14884. if ( this.index === null ) {
  14885. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14886. return this;
  14887. }
  14888. const geometry2 = new BufferGeometry();
  14889. const indices = this.index.array;
  14890. const attributes = this.attributes;
  14891. // attributes
  14892. for ( const name in attributes ) {
  14893. const attribute = attributes[ name ];
  14894. const newAttribute = convertBufferAttribute( attribute, indices );
  14895. geometry2.setAttribute( name, newAttribute );
  14896. }
  14897. // morph attributes
  14898. const morphAttributes = this.morphAttributes;
  14899. for ( const name in morphAttributes ) {
  14900. const morphArray = [];
  14901. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14902. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14903. const attribute = morphAttribute[ i ];
  14904. const newAttribute = convertBufferAttribute( attribute, indices );
  14905. morphArray.push( newAttribute );
  14906. }
  14907. geometry2.morphAttributes[ name ] = morphArray;
  14908. }
  14909. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14910. // groups
  14911. const groups = this.groups;
  14912. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14913. const group = groups[ i ];
  14914. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14915. }
  14916. return geometry2;
  14917. }
  14918. /**
  14919. * Serializes the geometry into JSON.
  14920. *
  14921. * @return {Object} A JSON object representing the serialized geometry.
  14922. */
  14923. toJSON() {
  14924. const data = {
  14925. metadata: {
  14926. version: 4.7,
  14927. type: 'BufferGeometry',
  14928. generator: 'BufferGeometry.toJSON'
  14929. }
  14930. };
  14931. // standard BufferGeometry serialization
  14932. data.uuid = this.uuid;
  14933. data.type = this.type;
  14934. if ( this.name !== '' ) data.name = this.name;
  14935. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14936. if ( this.parameters !== undefined ) {
  14937. const parameters = this.parameters;
  14938. for ( const key in parameters ) {
  14939. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14940. }
  14941. return data;
  14942. }
  14943. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14944. data.data = { attributes: {} };
  14945. const index = this.index;
  14946. if ( index !== null ) {
  14947. data.data.index = {
  14948. type: index.array.constructor.name,
  14949. array: Array.prototype.slice.call( index.array )
  14950. };
  14951. }
  14952. const attributes = this.attributes;
  14953. for ( const key in attributes ) {
  14954. const attribute = attributes[ key ];
  14955. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14956. }
  14957. const morphAttributes = {};
  14958. let hasMorphAttributes = false;
  14959. for ( const key in this.morphAttributes ) {
  14960. const attributeArray = this.morphAttributes[ key ];
  14961. const array = [];
  14962. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14963. const attribute = attributeArray[ i ];
  14964. array.push( attribute.toJSON( data.data ) );
  14965. }
  14966. if ( array.length > 0 ) {
  14967. morphAttributes[ key ] = array;
  14968. hasMorphAttributes = true;
  14969. }
  14970. }
  14971. if ( hasMorphAttributes ) {
  14972. data.data.morphAttributes = morphAttributes;
  14973. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14974. }
  14975. const groups = this.groups;
  14976. if ( groups.length > 0 ) {
  14977. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14978. }
  14979. const boundingSphere = this.boundingSphere;
  14980. if ( boundingSphere !== null ) {
  14981. data.data.boundingSphere = boundingSphere.toJSON();
  14982. }
  14983. return data;
  14984. }
  14985. /**
  14986. * Returns a new geometry with copied values from this instance.
  14987. *
  14988. * @return {BufferGeometry} A clone of this instance.
  14989. */
  14990. clone() {
  14991. return new this.constructor().copy( this );
  14992. }
  14993. /**
  14994. * Copies the values of the given geometry to this instance.
  14995. *
  14996. * @param {BufferGeometry} source - The geometry to copy.
  14997. * @return {BufferGeometry} A reference to this instance.
  14998. */
  14999. copy( source ) {
  15000. // reset
  15001. this.index = null;
  15002. this.attributes = {};
  15003. this.morphAttributes = {};
  15004. this.groups = [];
  15005. this.boundingBox = null;
  15006. this.boundingSphere = null;
  15007. // used for storing cloned, shared data
  15008. const data = {};
  15009. // name
  15010. this.name = source.name;
  15011. // index
  15012. const index = source.index;
  15013. if ( index !== null ) {
  15014. this.setIndex( index.clone() );
  15015. }
  15016. // attributes
  15017. const attributes = source.attributes;
  15018. for ( const name in attributes ) {
  15019. const attribute = attributes[ name ];
  15020. this.setAttribute( name, attribute.clone( data ) );
  15021. }
  15022. // morph attributes
  15023. const morphAttributes = source.morphAttributes;
  15024. for ( const name in morphAttributes ) {
  15025. const array = [];
  15026. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15027. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15028. array.push( morphAttribute[ i ].clone( data ) );
  15029. }
  15030. this.morphAttributes[ name ] = array;
  15031. }
  15032. this.morphTargetsRelative = source.morphTargetsRelative;
  15033. // groups
  15034. const groups = source.groups;
  15035. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15036. const group = groups[ i ];
  15037. this.addGroup( group.start, group.count, group.materialIndex );
  15038. }
  15039. // bounding box
  15040. const boundingBox = source.boundingBox;
  15041. if ( boundingBox !== null ) {
  15042. this.boundingBox = boundingBox.clone();
  15043. }
  15044. // bounding sphere
  15045. const boundingSphere = source.boundingSphere;
  15046. if ( boundingSphere !== null ) {
  15047. this.boundingSphere = boundingSphere.clone();
  15048. }
  15049. // draw range
  15050. this.drawRange.start = source.drawRange.start;
  15051. this.drawRange.count = source.drawRange.count;
  15052. // user data
  15053. this.userData = source.userData;
  15054. return this;
  15055. }
  15056. /**
  15057. * Frees the GPU-related resources allocated by this instance. Call this
  15058. * method whenever this instance is no longer used in your app.
  15059. *
  15060. * @fires BufferGeometry#dispose
  15061. */
  15062. dispose() {
  15063. this.dispatchEvent( { type: 'dispose' } );
  15064. }
  15065. }
  15066. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15067. const _ray$3 = /*@__PURE__*/ new Ray();
  15068. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15069. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15070. const _vA$1 = /*@__PURE__*/ new Vector3();
  15071. const _vB$1 = /*@__PURE__*/ new Vector3();
  15072. const _vC$1 = /*@__PURE__*/ new Vector3();
  15073. const _tempA = /*@__PURE__*/ new Vector3();
  15074. const _morphA = /*@__PURE__*/ new Vector3();
  15075. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15076. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15077. /**
  15078. * Class representing triangular polygon mesh based objects.
  15079. *
  15080. * ```js
  15081. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15082. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15083. * const mesh = new THREE.Mesh( geometry, material );
  15084. * scene.add( mesh );
  15085. * ```
  15086. *
  15087. * @augments Object3D
  15088. */
  15089. class Mesh extends Object3D {
  15090. /**
  15091. * Constructs a new mesh.
  15092. *
  15093. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15094. * @param {Material|Array<Material>} [material] - The mesh material.
  15095. */
  15096. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15097. super();
  15098. /**
  15099. * This flag can be used for type testing.
  15100. *
  15101. * @type {boolean}
  15102. * @readonly
  15103. * @default true
  15104. */
  15105. this.isMesh = true;
  15106. this.type = 'Mesh';
  15107. /**
  15108. * The mesh geometry.
  15109. *
  15110. * @type {BufferGeometry}
  15111. */
  15112. this.geometry = geometry;
  15113. /**
  15114. * The mesh material.
  15115. *
  15116. * @type {Material|Array<Material>}
  15117. * @default MeshBasicMaterial
  15118. */
  15119. this.material = material;
  15120. /**
  15121. * A dictionary representing the morph targets in the geometry. The key is the
  15122. * morph targets name, the value its attribute index. This member is `undefined`
  15123. * by default and only set when morph targets are detected in the geometry.
  15124. *
  15125. * @type {Object<String,number>|undefined}
  15126. * @default undefined
  15127. */
  15128. this.morphTargetDictionary = undefined;
  15129. /**
  15130. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15131. * is applied. This member is `undefined` by default and only set when morph targets are
  15132. * detected in the geometry.
  15133. *
  15134. * @type {Array<number>|undefined}
  15135. * @default undefined
  15136. */
  15137. this.morphTargetInfluences = undefined;
  15138. /**
  15139. * The number of instances of this mesh.
  15140. * Can only be used with {@link WebGPURenderer}.
  15141. *
  15142. * @type {number}
  15143. * @default 1
  15144. */
  15145. this.count = 1;
  15146. this.updateMorphTargets();
  15147. }
  15148. copy( source, recursive ) {
  15149. super.copy( source, recursive );
  15150. if ( source.morphTargetInfluences !== undefined ) {
  15151. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15152. }
  15153. if ( source.morphTargetDictionary !== undefined ) {
  15154. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15155. }
  15156. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15157. this.geometry = source.geometry;
  15158. return this;
  15159. }
  15160. /**
  15161. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15162. * to make sure existing morph targets can influence this 3D object.
  15163. */
  15164. updateMorphTargets() {
  15165. const geometry = this.geometry;
  15166. const morphAttributes = geometry.morphAttributes;
  15167. const keys = Object.keys( morphAttributes );
  15168. if ( keys.length > 0 ) {
  15169. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15170. if ( morphAttribute !== undefined ) {
  15171. this.morphTargetInfluences = [];
  15172. this.morphTargetDictionary = {};
  15173. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15174. const name = morphAttribute[ m ].name || String( m );
  15175. this.morphTargetInfluences.push( 0 );
  15176. this.morphTargetDictionary[ name ] = m;
  15177. }
  15178. }
  15179. }
  15180. }
  15181. /**
  15182. * Returns the local-space position of the vertex at the given index, taking into
  15183. * account the current animation state of both morph targets and skinning.
  15184. *
  15185. * @param {number} index - The vertex index.
  15186. * @param {Vector3} target - The target object that is used to store the method's result.
  15187. * @return {Vector3} The vertex position in local space.
  15188. */
  15189. getVertexPosition( index, target ) {
  15190. const geometry = this.geometry;
  15191. const position = geometry.attributes.position;
  15192. const morphPosition = geometry.morphAttributes.position;
  15193. const morphTargetsRelative = geometry.morphTargetsRelative;
  15194. target.fromBufferAttribute( position, index );
  15195. const morphInfluences = this.morphTargetInfluences;
  15196. if ( morphPosition && morphInfluences ) {
  15197. _morphA.set( 0, 0, 0 );
  15198. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15199. const influence = morphInfluences[ i ];
  15200. const morphAttribute = morphPosition[ i ];
  15201. if ( influence === 0 ) continue;
  15202. _tempA.fromBufferAttribute( morphAttribute, index );
  15203. if ( morphTargetsRelative ) {
  15204. _morphA.addScaledVector( _tempA, influence );
  15205. } else {
  15206. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15207. }
  15208. }
  15209. target.add( _morphA );
  15210. }
  15211. return target;
  15212. }
  15213. /**
  15214. * Computes intersection points between a casted ray and this line.
  15215. *
  15216. * @param {Raycaster} raycaster - The raycaster.
  15217. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15218. */
  15219. raycast( raycaster, intersects ) {
  15220. const geometry = this.geometry;
  15221. const material = this.material;
  15222. const matrixWorld = this.matrixWorld;
  15223. if ( material === undefined ) return;
  15224. // test with bounding sphere in world space
  15225. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15226. _sphere$6.copy( geometry.boundingSphere );
  15227. _sphere$6.applyMatrix4( matrixWorld );
  15228. // check distance from ray origin to bounding sphere
  15229. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15230. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15231. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15232. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15233. }
  15234. // convert ray to local space of mesh
  15235. _inverseMatrix$3.copy( matrixWorld ).invert();
  15236. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15237. // test with bounding box in local space
  15238. if ( geometry.boundingBox !== null ) {
  15239. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15240. }
  15241. // test for intersections with geometry
  15242. this._computeIntersections( raycaster, intersects, _ray$3 );
  15243. }
  15244. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15245. let intersection;
  15246. const geometry = this.geometry;
  15247. const material = this.material;
  15248. const index = geometry.index;
  15249. const position = geometry.attributes.position;
  15250. const uv = geometry.attributes.uv;
  15251. const uv1 = geometry.attributes.uv1;
  15252. const normal = geometry.attributes.normal;
  15253. const groups = geometry.groups;
  15254. const drawRange = geometry.drawRange;
  15255. if ( index !== null ) {
  15256. // indexed buffer geometry
  15257. if ( Array.isArray( material ) ) {
  15258. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15259. const group = groups[ i ];
  15260. const groupMaterial = material[ group.materialIndex ];
  15261. const start = Math.max( group.start, drawRange.start );
  15262. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15263. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15264. const a = index.getX( j );
  15265. const b = index.getX( j + 1 );
  15266. const c = index.getX( j + 2 );
  15267. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15268. if ( intersection ) {
  15269. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15270. intersection.face.materialIndex = group.materialIndex;
  15271. intersects.push( intersection );
  15272. }
  15273. }
  15274. }
  15275. } else {
  15276. const start = Math.max( 0, drawRange.start );
  15277. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15278. for ( let i = start, il = end; i < il; i += 3 ) {
  15279. const a = index.getX( i );
  15280. const b = index.getX( i + 1 );
  15281. const c = index.getX( i + 2 );
  15282. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15283. if ( intersection ) {
  15284. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15285. intersects.push( intersection );
  15286. }
  15287. }
  15288. }
  15289. } else if ( position !== undefined ) {
  15290. // non-indexed buffer geometry
  15291. if ( Array.isArray( material ) ) {
  15292. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15293. const group = groups[ i ];
  15294. const groupMaterial = material[ group.materialIndex ];
  15295. const start = Math.max( group.start, drawRange.start );
  15296. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15297. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15298. const a = j;
  15299. const b = j + 1;
  15300. const c = j + 2;
  15301. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15302. if ( intersection ) {
  15303. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15304. intersection.face.materialIndex = group.materialIndex;
  15305. intersects.push( intersection );
  15306. }
  15307. }
  15308. }
  15309. } else {
  15310. const start = Math.max( 0, drawRange.start );
  15311. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15312. for ( let i = start, il = end; i < il; i += 3 ) {
  15313. const a = i;
  15314. const b = i + 1;
  15315. const c = i + 2;
  15316. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15317. if ( intersection ) {
  15318. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15319. intersects.push( intersection );
  15320. }
  15321. }
  15322. }
  15323. }
  15324. }
  15325. }
  15326. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15327. let intersect;
  15328. if ( material.side === BackSide ) {
  15329. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15330. } else {
  15331. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15332. }
  15333. if ( intersect === null ) return null;
  15334. _intersectionPointWorld.copy( point );
  15335. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15336. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15337. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15338. return {
  15339. distance: distance,
  15340. point: _intersectionPointWorld.clone(),
  15341. object: object
  15342. };
  15343. }
  15344. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15345. object.getVertexPosition( a, _vA$1 );
  15346. object.getVertexPosition( b, _vB$1 );
  15347. object.getVertexPosition( c, _vC$1 );
  15348. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15349. if ( intersection ) {
  15350. const barycoord = new Vector3();
  15351. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15352. if ( uv ) {
  15353. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15354. }
  15355. if ( uv1 ) {
  15356. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15357. }
  15358. if ( normal ) {
  15359. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15360. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15361. intersection.normal.multiplyScalar( -1 );
  15362. }
  15363. }
  15364. const face = {
  15365. a: a,
  15366. b: b,
  15367. c: c,
  15368. normal: new Vector3(),
  15369. materialIndex: 0
  15370. };
  15371. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15372. intersection.face = face;
  15373. intersection.barycoord = barycoord;
  15374. }
  15375. return intersection;
  15376. }
  15377. /**
  15378. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15379. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15380. * of the axes.
  15381. *
  15382. * ```js
  15383. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15384. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15385. * const cube = new THREE.Mesh( geometry, material );
  15386. * scene.add( cube );
  15387. * ```
  15388. *
  15389. * @augments BufferGeometry
  15390. */
  15391. class BoxGeometry extends BufferGeometry {
  15392. /**
  15393. * Constructs a new box geometry.
  15394. *
  15395. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15396. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15397. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15398. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15399. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15400. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15401. */
  15402. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15403. super();
  15404. this.type = 'BoxGeometry';
  15405. /**
  15406. * Holds the constructor parameters that have been
  15407. * used to generate the geometry. Any modification
  15408. * after instantiation does not change the geometry.
  15409. *
  15410. * @type {Object}
  15411. */
  15412. this.parameters = {
  15413. width: width,
  15414. height: height,
  15415. depth: depth,
  15416. widthSegments: widthSegments,
  15417. heightSegments: heightSegments,
  15418. depthSegments: depthSegments
  15419. };
  15420. const scope = this;
  15421. // segments
  15422. widthSegments = Math.floor( widthSegments );
  15423. heightSegments = Math.floor( heightSegments );
  15424. depthSegments = Math.floor( depthSegments );
  15425. // buffers
  15426. const indices = [];
  15427. const vertices = [];
  15428. const normals = [];
  15429. const uvs = [];
  15430. // helper variables
  15431. let numberOfVertices = 0;
  15432. let groupStart = 0;
  15433. // build each side of the box geometry
  15434. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15435. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15436. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15437. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15438. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15439. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15440. // build geometry
  15441. this.setIndex( indices );
  15442. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15443. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15444. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15445. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15446. const segmentWidth = width / gridX;
  15447. const segmentHeight = height / gridY;
  15448. const widthHalf = width / 2;
  15449. const heightHalf = height / 2;
  15450. const depthHalf = depth / 2;
  15451. const gridX1 = gridX + 1;
  15452. const gridY1 = gridY + 1;
  15453. let vertexCounter = 0;
  15454. let groupCount = 0;
  15455. const vector = new Vector3();
  15456. // generate vertices, normals and uvs
  15457. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15458. const y = iy * segmentHeight - heightHalf;
  15459. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15460. const x = ix * segmentWidth - widthHalf;
  15461. // set values to correct vector component
  15462. vector[ u ] = x * udir;
  15463. vector[ v ] = y * vdir;
  15464. vector[ w ] = depthHalf;
  15465. // now apply vector to vertex buffer
  15466. vertices.push( vector.x, vector.y, vector.z );
  15467. // set values to correct vector component
  15468. vector[ u ] = 0;
  15469. vector[ v ] = 0;
  15470. vector[ w ] = depth > 0 ? 1 : -1;
  15471. // now apply vector to normal buffer
  15472. normals.push( vector.x, vector.y, vector.z );
  15473. // uvs
  15474. uvs.push( ix / gridX );
  15475. uvs.push( 1 - ( iy / gridY ) );
  15476. // counters
  15477. vertexCounter += 1;
  15478. }
  15479. }
  15480. // indices
  15481. // 1. you need three indices to draw a single face
  15482. // 2. a single segment consists of two faces
  15483. // 3. so we need to generate six (2*3) indices per segment
  15484. for ( let iy = 0; iy < gridY; iy ++ ) {
  15485. for ( let ix = 0; ix < gridX; ix ++ ) {
  15486. const a = numberOfVertices + ix + gridX1 * iy;
  15487. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15488. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15489. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15490. // faces
  15491. indices.push( a, b, d );
  15492. indices.push( b, c, d );
  15493. // increase counter
  15494. groupCount += 6;
  15495. }
  15496. }
  15497. // add a group to the geometry. this will ensure multi material support
  15498. scope.addGroup( groupStart, groupCount, materialIndex );
  15499. // calculate new start value for groups
  15500. groupStart += groupCount;
  15501. // update total number of vertices
  15502. numberOfVertices += vertexCounter;
  15503. }
  15504. }
  15505. copy( source ) {
  15506. super.copy( source );
  15507. this.parameters = Object.assign( {}, source.parameters );
  15508. return this;
  15509. }
  15510. /**
  15511. * Factory method for creating an instance of this class from the given
  15512. * JSON object.
  15513. *
  15514. * @param {Object} data - A JSON object representing the serialized geometry.
  15515. * @return {BoxGeometry} A new instance.
  15516. */
  15517. static fromJSON( data ) {
  15518. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15519. }
  15520. }
  15521. // Uniform Utilities
  15522. function cloneUniforms( src ) {
  15523. const dst = {};
  15524. for ( const u in src ) {
  15525. dst[ u ] = {};
  15526. for ( const p in src[ u ] ) {
  15527. const property = src[ u ][ p ];
  15528. if ( property && ( property.isColor ||
  15529. property.isMatrix3 || property.isMatrix4 ||
  15530. property.isVector2 || property.isVector3 || property.isVector4 ||
  15531. property.isTexture || property.isQuaternion ) ) {
  15532. if ( property.isRenderTargetTexture ) {
  15533. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15534. dst[ u ][ p ] = null;
  15535. } else {
  15536. dst[ u ][ p ] = property.clone();
  15537. }
  15538. } else if ( Array.isArray( property ) ) {
  15539. dst[ u ][ p ] = property.slice();
  15540. } else {
  15541. dst[ u ][ p ] = property;
  15542. }
  15543. }
  15544. }
  15545. return dst;
  15546. }
  15547. function mergeUniforms( uniforms ) {
  15548. const merged = {};
  15549. for ( let u = 0; u < uniforms.length; u ++ ) {
  15550. const tmp = cloneUniforms( uniforms[ u ] );
  15551. for ( const p in tmp ) {
  15552. merged[ p ] = tmp[ p ];
  15553. }
  15554. }
  15555. return merged;
  15556. }
  15557. function cloneUniformsGroups( src ) {
  15558. const dst = [];
  15559. for ( let u = 0; u < src.length; u ++ ) {
  15560. dst.push( src[ u ].clone() );
  15561. }
  15562. return dst;
  15563. }
  15564. function getUnlitUniformColorSpace( renderer ) {
  15565. const currentRenderTarget = renderer.getRenderTarget();
  15566. if ( currentRenderTarget === null ) {
  15567. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15568. return renderer.outputColorSpace;
  15569. }
  15570. // https://github.com/mrdoob/three.js/issues/27868
  15571. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15572. return currentRenderTarget.texture.colorSpace;
  15573. }
  15574. return ColorManagement.workingColorSpace;
  15575. }
  15576. // Legacy
  15577. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15578. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15579. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15580. /**
  15581. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15582. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15583. * effect not included with any of the built-in materials.
  15584. *
  15585. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15586. *
  15587. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15588. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15589. * you don't want that, use {@link RawShaderMaterial} instead.
  15590. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15591. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15592. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15593. * - The loop has to be [normalized]{@link https://en.wikipedia.org/wiki/Normalized_loop}.
  15594. * - The loop variable has to be *i*.
  15595. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15596. * value of *i* for the given iteration and can be used in preprocessor
  15597. * statements.
  15598. *
  15599. * ```js
  15600. * const material = new THREE.ShaderMaterial( {
  15601. * uniforms: {
  15602. * time: { value: 1.0 },
  15603. * resolution: { value: new THREE.Vector2() }
  15604. * },
  15605. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15606. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15607. * } );
  15608. * ```
  15609. *
  15610. * @augments Material
  15611. */
  15612. class ShaderMaterial extends Material {
  15613. /**
  15614. * Constructs a new shader material.
  15615. *
  15616. * @param {Object} [parameters] - An object with one or more properties
  15617. * defining the material's appearance. Any property of the material
  15618. * (including any property from inherited materials) can be passed
  15619. * in here. Color values can be passed any type of value accepted
  15620. * by {@link Color#set}.
  15621. */
  15622. constructor( parameters ) {
  15623. super();
  15624. /**
  15625. * This flag can be used for type testing.
  15626. *
  15627. * @type {boolean}
  15628. * @readonly
  15629. * @default true
  15630. */
  15631. this.isShaderMaterial = true;
  15632. this.type = 'ShaderMaterial';
  15633. /**
  15634. * Defines custom constants using `#define` directives within the GLSL code
  15635. * for both the vertex shader and the fragment shader; each key/value pair
  15636. * yields another directive.
  15637. * ```js
  15638. * defines: {
  15639. * FOO: 15,
  15640. * BAR: true
  15641. * }
  15642. * ```
  15643. * Yields the lines:
  15644. * ```
  15645. * #define FOO 15
  15646. * #define BAR true
  15647. * ```
  15648. *
  15649. * @type {Object}
  15650. */
  15651. this.defines = {};
  15652. /**
  15653. * An object of the form:
  15654. * ```js
  15655. * {
  15656. * "uniform1": { value: 1.0 },
  15657. * "uniform2": { value: 2 }
  15658. * }
  15659. * ```
  15660. * specifying the uniforms to be passed to the shader code; keys are uniform
  15661. * names, values are definitions of the form
  15662. * ```
  15663. * {
  15664. * value: 1.0
  15665. * }
  15666. * ```
  15667. * where `value` is the value of the uniform. Names must match the name of
  15668. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15669. * on every frame, so updating the value of the uniform will immediately
  15670. * update the value available to the GLSL code.
  15671. *
  15672. * @type {Object}
  15673. */
  15674. this.uniforms = {};
  15675. /**
  15676. * An array holding uniforms groups for configuring UBOs.
  15677. *
  15678. * @type {Array<UniformsGroup>}
  15679. */
  15680. this.uniformsGroups = [];
  15681. /**
  15682. * Vertex shader GLSL code. This is the actual code for the shader.
  15683. *
  15684. * @type {string}
  15685. */
  15686. this.vertexShader = default_vertex;
  15687. /**
  15688. * Fragment shader GLSL code. This is the actual code for the shader.
  15689. *
  15690. * @type {string}
  15691. */
  15692. this.fragmentShader = default_fragment;
  15693. /**
  15694. * Controls line thickness or lines.
  15695. *
  15696. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15697. * width of one pixel.
  15698. *
  15699. * @type {number}
  15700. * @default 1
  15701. */
  15702. this.linewidth = 1;
  15703. /**
  15704. * Renders the geometry as a wireframe.
  15705. *
  15706. * @type {boolean}
  15707. * @default false
  15708. */
  15709. this.wireframe = false;
  15710. /**
  15711. * Controls the thickness of the wireframe.
  15712. *
  15713. * WebGL and WebGPU ignore this property and always render
  15714. * 1 pixel wide lines.
  15715. *
  15716. * @type {number}
  15717. * @default 1
  15718. */
  15719. this.wireframeLinewidth = 1;
  15720. /**
  15721. * Define whether the material color is affected by global fog settings; `true`
  15722. * to pass fog uniforms to the shader.
  15723. *
  15724. * @type {boolean}
  15725. * @default false
  15726. */
  15727. this.fog = false;
  15728. /**
  15729. * Defines whether this material uses lighting; `true` to pass uniform data
  15730. * related to lighting to this shader.
  15731. *
  15732. * @type {boolean}
  15733. * @default false
  15734. */
  15735. this.lights = false;
  15736. /**
  15737. * Defines whether this material supports clipping; `true` to let the renderer
  15738. * pass the clippingPlanes uniform.
  15739. *
  15740. * @type {boolean}
  15741. * @default false
  15742. */
  15743. this.clipping = false;
  15744. /**
  15745. * Overwritten and set to `true` by default.
  15746. *
  15747. * @type {boolean}
  15748. * @default true
  15749. */
  15750. this.forceSinglePass = true;
  15751. /**
  15752. * This object allows to enable certain WebGL 2 extensions.
  15753. *
  15754. * - clipCullDistance: set to `true` to use vertex shader clipping
  15755. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15756. *
  15757. * @type {{clipCullDistance:false,multiDraw:false}}
  15758. */
  15759. this.extensions = {
  15760. clipCullDistance: false, // set to use vertex shader clipping
  15761. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15762. };
  15763. /**
  15764. * When the rendered geometry doesn't include these attributes but the
  15765. * material does, these default values will be passed to the shaders. This
  15766. * avoids errors when buffer data is missing.
  15767. *
  15768. * - color: [ 1, 1, 1 ]
  15769. * - uv: [ 0, 0 ]
  15770. * - uv1: [ 0, 0 ]
  15771. *
  15772. * @type {Object}
  15773. */
  15774. this.defaultAttributeValues = {
  15775. 'color': [ 1, 1, 1 ],
  15776. 'uv': [ 0, 0 ],
  15777. 'uv1': [ 0, 0 ]
  15778. };
  15779. /**
  15780. * If set, this calls [gl.bindAttribLocation]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation}
  15781. * to bind a generic vertex index to an attribute variable.
  15782. *
  15783. * @type {string|undefined}
  15784. * @default undefined
  15785. */
  15786. this.index0AttributeName = undefined;
  15787. /**
  15788. * Can be used to force a uniform update while changing uniforms in
  15789. * {@link Object3D#onBeforeRender}.
  15790. *
  15791. * @type {boolean}
  15792. * @default false
  15793. */
  15794. this.uniformsNeedUpdate = false;
  15795. /**
  15796. * Defines the GLSL version of custom shader code.
  15797. *
  15798. * @type {?(GLSL1|GLSL3)}
  15799. * @default null
  15800. */
  15801. this.glslVersion = null;
  15802. if ( parameters !== undefined ) {
  15803. this.setValues( parameters );
  15804. }
  15805. }
  15806. copy( source ) {
  15807. super.copy( source );
  15808. this.fragmentShader = source.fragmentShader;
  15809. this.vertexShader = source.vertexShader;
  15810. this.uniforms = cloneUniforms( source.uniforms );
  15811. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15812. this.defines = Object.assign( {}, source.defines );
  15813. this.wireframe = source.wireframe;
  15814. this.wireframeLinewidth = source.wireframeLinewidth;
  15815. this.fog = source.fog;
  15816. this.lights = source.lights;
  15817. this.clipping = source.clipping;
  15818. this.extensions = Object.assign( {}, source.extensions );
  15819. this.glslVersion = source.glslVersion;
  15820. return this;
  15821. }
  15822. toJSON( meta ) {
  15823. const data = super.toJSON( meta );
  15824. data.glslVersion = this.glslVersion;
  15825. data.uniforms = {};
  15826. for ( const name in this.uniforms ) {
  15827. const uniform = this.uniforms[ name ];
  15828. const value = uniform.value;
  15829. if ( value && value.isTexture ) {
  15830. data.uniforms[ name ] = {
  15831. type: 't',
  15832. value: value.toJSON( meta ).uuid
  15833. };
  15834. } else if ( value && value.isColor ) {
  15835. data.uniforms[ name ] = {
  15836. type: 'c',
  15837. value: value.getHex()
  15838. };
  15839. } else if ( value && value.isVector2 ) {
  15840. data.uniforms[ name ] = {
  15841. type: 'v2',
  15842. value: value.toArray()
  15843. };
  15844. } else if ( value && value.isVector3 ) {
  15845. data.uniforms[ name ] = {
  15846. type: 'v3',
  15847. value: value.toArray()
  15848. };
  15849. } else if ( value && value.isVector4 ) {
  15850. data.uniforms[ name ] = {
  15851. type: 'v4',
  15852. value: value.toArray()
  15853. };
  15854. } else if ( value && value.isMatrix3 ) {
  15855. data.uniforms[ name ] = {
  15856. type: 'm3',
  15857. value: value.toArray()
  15858. };
  15859. } else if ( value && value.isMatrix4 ) {
  15860. data.uniforms[ name ] = {
  15861. type: 'm4',
  15862. value: value.toArray()
  15863. };
  15864. } else {
  15865. data.uniforms[ name ] = {
  15866. value: value
  15867. };
  15868. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15869. }
  15870. }
  15871. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15872. data.vertexShader = this.vertexShader;
  15873. data.fragmentShader = this.fragmentShader;
  15874. data.lights = this.lights;
  15875. data.clipping = this.clipping;
  15876. const extensions = {};
  15877. for ( const key in this.extensions ) {
  15878. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15879. }
  15880. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15881. return data;
  15882. }
  15883. }
  15884. /**
  15885. * Abstract base class for cameras. This class should always be inherited
  15886. * when you build a new camera.
  15887. *
  15888. * @abstract
  15889. * @augments Object3D
  15890. */
  15891. class Camera extends Object3D {
  15892. /**
  15893. * Constructs a new camera.
  15894. */
  15895. constructor() {
  15896. super();
  15897. /**
  15898. * This flag can be used for type testing.
  15899. *
  15900. * @type {boolean}
  15901. * @readonly
  15902. * @default true
  15903. */
  15904. this.isCamera = true;
  15905. this.type = 'Camera';
  15906. /**
  15907. * The inverse of the camera's world matrix.
  15908. *
  15909. * @type {Matrix4}
  15910. */
  15911. this.matrixWorldInverse = new Matrix4();
  15912. /**
  15913. * The camera's projection matrix.
  15914. *
  15915. * @type {Matrix4}
  15916. */
  15917. this.projectionMatrix = new Matrix4();
  15918. /**
  15919. * The inverse of the camera's projection matrix.
  15920. *
  15921. * @type {Matrix4}
  15922. */
  15923. this.projectionMatrixInverse = new Matrix4();
  15924. /**
  15925. * The coordinate system in which the camera is used.
  15926. *
  15927. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  15928. */
  15929. this.coordinateSystem = WebGLCoordinateSystem;
  15930. this._reversedDepth = false;
  15931. }
  15932. /**
  15933. * The flag that indicates whether the camera uses a reversed depth buffer.
  15934. *
  15935. * @type {boolean}
  15936. * @default false
  15937. */
  15938. get reversedDepth() {
  15939. return this._reversedDepth;
  15940. }
  15941. copy( source, recursive ) {
  15942. super.copy( source, recursive );
  15943. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  15944. this.projectionMatrix.copy( source.projectionMatrix );
  15945. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  15946. this.coordinateSystem = source.coordinateSystem;
  15947. return this;
  15948. }
  15949. /**
  15950. * Returns a vector representing the ("look") direction of the 3D object in world space.
  15951. *
  15952. * This method is overwritten since cameras have a different forward vector compared to other
  15953. * 3D objects. A camera looks down its local, negative z-axis by default.
  15954. *
  15955. * @param {Vector3} target - The target vector the result is stored to.
  15956. * @return {Vector3} The 3D object's direction in world space.
  15957. */
  15958. getWorldDirection( target ) {
  15959. return super.getWorldDirection( target ).negate();
  15960. }
  15961. updateMatrixWorld( force ) {
  15962. super.updateMatrixWorld( force );
  15963. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15964. }
  15965. updateWorldMatrix( updateParents, updateChildren ) {
  15966. super.updateWorldMatrix( updateParents, updateChildren );
  15967. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15968. }
  15969. clone() {
  15970. return new this.constructor().copy( this );
  15971. }
  15972. }
  15973. const _v3$1 = /*@__PURE__*/ new Vector3();
  15974. const _minTarget = /*@__PURE__*/ new Vector2();
  15975. const _maxTarget = /*@__PURE__*/ new Vector2();
  15976. /**
  15977. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  15978. *
  15979. * This projection mode is designed to mimic the way the human eye sees. It
  15980. * is the most common projection mode used for rendering a 3D scene.
  15981. *
  15982. * ```js
  15983. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  15984. * scene.add( camera );
  15985. * ```
  15986. *
  15987. * @augments Camera
  15988. */
  15989. class PerspectiveCamera extends Camera {
  15990. /**
  15991. * Constructs a new perspective camera.
  15992. *
  15993. * @param {number} [fov=50] - The vertical field of view.
  15994. * @param {number} [aspect=1] - The aspect ratio.
  15995. * @param {number} [near=0.1] - The camera's near plane.
  15996. * @param {number} [far=2000] - The camera's far plane.
  15997. */
  15998. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  15999. super();
  16000. /**
  16001. * This flag can be used for type testing.
  16002. *
  16003. * @type {boolean}
  16004. * @readonly
  16005. * @default true
  16006. */
  16007. this.isPerspectiveCamera = true;
  16008. this.type = 'PerspectiveCamera';
  16009. /**
  16010. * The vertical field of view, from bottom to top of view,
  16011. * in degrees.
  16012. *
  16013. * @type {number}
  16014. * @default 50
  16015. */
  16016. this.fov = fov;
  16017. /**
  16018. * The zoom factor of the camera.
  16019. *
  16020. * @type {number}
  16021. * @default 1
  16022. */
  16023. this.zoom = 1;
  16024. /**
  16025. * The camera's near plane. The valid range is greater than `0`
  16026. * and less than the current value of {@link PerspectiveCamera#far}.
  16027. *
  16028. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16029. * valid value for a perspective camera's near plane.
  16030. *
  16031. * @type {number}
  16032. * @default 0.1
  16033. */
  16034. this.near = near;
  16035. /**
  16036. * The camera's far plane. Must be greater than the
  16037. * current value of {@link PerspectiveCamera#near}.
  16038. *
  16039. * @type {number}
  16040. * @default 2000
  16041. */
  16042. this.far = far;
  16043. /**
  16044. * Object distance used for stereoscopy and depth-of-field effects. This
  16045. * parameter does not influence the projection matrix unless a
  16046. * {@link StereoCamera} is being used.
  16047. *
  16048. * @type {number}
  16049. * @default 10
  16050. */
  16051. this.focus = 10;
  16052. /**
  16053. * The aspect ratio, usually the canvas width / canvas height.
  16054. *
  16055. * @type {number}
  16056. * @default 1
  16057. */
  16058. this.aspect = aspect;
  16059. /**
  16060. * Represents the frustum window specification. This property should not be edited
  16061. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16062. *
  16063. * @type {?Object}
  16064. * @default null
  16065. */
  16066. this.view = null;
  16067. /**
  16068. * Film size used for the larger axis. Default is `35` (millimeters). This
  16069. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16070. * is set to a nonzero value.
  16071. *
  16072. * @type {number}
  16073. * @default 35
  16074. */
  16075. this.filmGauge = 35;
  16076. /**
  16077. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16078. *
  16079. * @type {number}
  16080. * @default 0
  16081. */
  16082. this.filmOffset = 0;
  16083. this.updateProjectionMatrix();
  16084. }
  16085. copy( source, recursive ) {
  16086. super.copy( source, recursive );
  16087. this.fov = source.fov;
  16088. this.zoom = source.zoom;
  16089. this.near = source.near;
  16090. this.far = source.far;
  16091. this.focus = source.focus;
  16092. this.aspect = source.aspect;
  16093. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16094. this.filmGauge = source.filmGauge;
  16095. this.filmOffset = source.filmOffset;
  16096. return this;
  16097. }
  16098. /**
  16099. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16100. *
  16101. * The default film gauge is 35, so that the focal length can be specified for
  16102. * a 35mm (full frame) camera.
  16103. *
  16104. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16105. */
  16106. setFocalLength( focalLength ) {
  16107. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16108. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16109. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16110. this.updateProjectionMatrix();
  16111. }
  16112. /**
  16113. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16114. * {@link PerspectiveCamera#filmGauge}.
  16115. *
  16116. * @return {number} The computed focal length.
  16117. */
  16118. getFocalLength() {
  16119. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16120. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16121. }
  16122. /**
  16123. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16124. *
  16125. * @return {number} The effective FOV.
  16126. */
  16127. getEffectiveFOV() {
  16128. return RAD2DEG * 2 * Math.atan(
  16129. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16130. }
  16131. /**
  16132. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16133. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16134. *
  16135. * @return {number} The film width.
  16136. */
  16137. getFilmWidth() {
  16138. // film not completely covered in portrait format (aspect < 1)
  16139. return this.filmGauge * Math.min( this.aspect, 1 );
  16140. }
  16141. /**
  16142. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16143. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16144. *
  16145. * @return {number} The film width.
  16146. */
  16147. getFilmHeight() {
  16148. // film not completely covered in landscape format (aspect > 1)
  16149. return this.filmGauge / Math.max( this.aspect, 1 );
  16150. }
  16151. /**
  16152. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16153. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16154. *
  16155. * @param {number} distance - The viewing distance.
  16156. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16157. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16158. */
  16159. getViewBounds( distance, minTarget, maxTarget ) {
  16160. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16161. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16162. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16163. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16164. }
  16165. /**
  16166. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16167. *
  16168. * @param {number} distance - The viewing distance.
  16169. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16170. * @returns {Vector2} The view size.
  16171. */
  16172. getViewSize( distance, target ) {
  16173. this.getViewBounds( distance, _minTarget, _maxTarget );
  16174. return target.subVectors( _maxTarget, _minTarget );
  16175. }
  16176. /**
  16177. * Sets an offset in a larger frustum. This is useful for multi-window or
  16178. * multi-monitor/multi-machine setups.
  16179. *
  16180. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16181. * the monitors are in grid like this
  16182. *```
  16183. * +---+---+---+
  16184. * | A | B | C |
  16185. * +---+---+---+
  16186. * | D | E | F |
  16187. * +---+---+---+
  16188. *```
  16189. * then for each monitor you would call it like this:
  16190. *```js
  16191. * const w = 1920;
  16192. * const h = 1080;
  16193. * const fullWidth = w * 3;
  16194. * const fullHeight = h * 2;
  16195. *
  16196. * // --A--
  16197. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16198. * // --B--
  16199. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16200. * // --C--
  16201. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16202. * // --D--
  16203. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16204. * // --E--
  16205. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16206. * // --F--
  16207. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16208. * ```
  16209. *
  16210. * Note there is no reason monitors have to be the same size or in a grid.
  16211. *
  16212. * @param {number} fullWidth - The full width of multiview setup.
  16213. * @param {number} fullHeight - The full height of multiview setup.
  16214. * @param {number} x - The horizontal offset of the subcamera.
  16215. * @param {number} y - The vertical offset of the subcamera.
  16216. * @param {number} width - The width of subcamera.
  16217. * @param {number} height - The height of subcamera.
  16218. */
  16219. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16220. this.aspect = fullWidth / fullHeight;
  16221. if ( this.view === null ) {
  16222. this.view = {
  16223. enabled: true,
  16224. fullWidth: 1,
  16225. fullHeight: 1,
  16226. offsetX: 0,
  16227. offsetY: 0,
  16228. width: 1,
  16229. height: 1
  16230. };
  16231. }
  16232. this.view.enabled = true;
  16233. this.view.fullWidth = fullWidth;
  16234. this.view.fullHeight = fullHeight;
  16235. this.view.offsetX = x;
  16236. this.view.offsetY = y;
  16237. this.view.width = width;
  16238. this.view.height = height;
  16239. this.updateProjectionMatrix();
  16240. }
  16241. /**
  16242. * Removes the view offset from the projection matrix.
  16243. */
  16244. clearViewOffset() {
  16245. if ( this.view !== null ) {
  16246. this.view.enabled = false;
  16247. }
  16248. this.updateProjectionMatrix();
  16249. }
  16250. /**
  16251. * Updates the camera's projection matrix. Must be called after any change of
  16252. * camera properties.
  16253. */
  16254. updateProjectionMatrix() {
  16255. const near = this.near;
  16256. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16257. let height = 2 * top;
  16258. let width = this.aspect * height;
  16259. let left = -0.5 * width;
  16260. const view = this.view;
  16261. if ( this.view !== null && this.view.enabled ) {
  16262. const fullWidth = view.fullWidth,
  16263. fullHeight = view.fullHeight;
  16264. left += view.offsetX * width / fullWidth;
  16265. top -= view.offsetY * height / fullHeight;
  16266. width *= view.width / fullWidth;
  16267. height *= view.height / fullHeight;
  16268. }
  16269. const skew = this.filmOffset;
  16270. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16271. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16272. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16273. }
  16274. toJSON( meta ) {
  16275. const data = super.toJSON( meta );
  16276. data.object.fov = this.fov;
  16277. data.object.zoom = this.zoom;
  16278. data.object.near = this.near;
  16279. data.object.far = this.far;
  16280. data.object.focus = this.focus;
  16281. data.object.aspect = this.aspect;
  16282. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16283. data.object.filmGauge = this.filmGauge;
  16284. data.object.filmOffset = this.filmOffset;
  16285. return data;
  16286. }
  16287. }
  16288. const fov = -90; // negative fov is not an error
  16289. const aspect = 1;
  16290. /**
  16291. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16292. * cube render target. The render target can then be used as an environment map for rendering
  16293. * realtime reflections in your scene.
  16294. *
  16295. * ```js
  16296. * // Create cube render target
  16297. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16298. *
  16299. * // Create cube camera
  16300. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16301. * scene.add( cubeCamera );
  16302. *
  16303. * // Create car
  16304. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16305. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16306. * scene.add( car );
  16307. *
  16308. * // Update the render target cube
  16309. * car.visible = false;
  16310. * cubeCamera.position.copy( car.position );
  16311. * cubeCamera.update( renderer, scene );
  16312. *
  16313. * // Render the scene
  16314. * car.visible = true;
  16315. * renderer.render( scene, camera );
  16316. * ```
  16317. *
  16318. * @augments Object3D
  16319. */
  16320. class CubeCamera extends Object3D {
  16321. /**
  16322. * Constructs a new cube camera.
  16323. *
  16324. * @param {number} near - The camera's near plane.
  16325. * @param {number} far - The camera's far plane.
  16326. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16327. */
  16328. constructor( near, far, renderTarget ) {
  16329. super();
  16330. this.type = 'CubeCamera';
  16331. /**
  16332. * A reference to the cube render target.
  16333. *
  16334. * @type {WebGLCubeRenderTarget}
  16335. */
  16336. this.renderTarget = renderTarget;
  16337. /**
  16338. * The current active coordinate system.
  16339. *
  16340. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16341. * @default null
  16342. */
  16343. this.coordinateSystem = null;
  16344. /**
  16345. * The current active mipmap level
  16346. *
  16347. * @type {number}
  16348. * @default 0
  16349. */
  16350. this.activeMipmapLevel = 0;
  16351. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16352. cameraPX.layers = this.layers;
  16353. this.add( cameraPX );
  16354. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16355. cameraNX.layers = this.layers;
  16356. this.add( cameraNX );
  16357. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16358. cameraPY.layers = this.layers;
  16359. this.add( cameraPY );
  16360. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16361. cameraNY.layers = this.layers;
  16362. this.add( cameraNY );
  16363. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16364. cameraPZ.layers = this.layers;
  16365. this.add( cameraPZ );
  16366. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16367. cameraNZ.layers = this.layers;
  16368. this.add( cameraNZ );
  16369. }
  16370. /**
  16371. * Must be called when the coordinate system of the cube camera is changed.
  16372. */
  16373. updateCoordinateSystem() {
  16374. const coordinateSystem = this.coordinateSystem;
  16375. const cameras = this.children.concat();
  16376. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16377. for ( const camera of cameras ) this.remove( camera );
  16378. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16379. cameraPX.up.set( 0, 1, 0 );
  16380. cameraPX.lookAt( 1, 0, 0 );
  16381. cameraNX.up.set( 0, 1, 0 );
  16382. cameraNX.lookAt( -1, 0, 0 );
  16383. cameraPY.up.set( 0, 0, -1 );
  16384. cameraPY.lookAt( 0, 1, 0 );
  16385. cameraNY.up.set( 0, 0, 1 );
  16386. cameraNY.lookAt( 0, -1, 0 );
  16387. cameraPZ.up.set( 0, 1, 0 );
  16388. cameraPZ.lookAt( 0, 0, 1 );
  16389. cameraNZ.up.set( 0, 1, 0 );
  16390. cameraNZ.lookAt( 0, 0, -1 );
  16391. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16392. cameraPX.up.set( 0, -1, 0 );
  16393. cameraPX.lookAt( -1, 0, 0 );
  16394. cameraNX.up.set( 0, -1, 0 );
  16395. cameraNX.lookAt( 1, 0, 0 );
  16396. cameraPY.up.set( 0, 0, 1 );
  16397. cameraPY.lookAt( 0, 1, 0 );
  16398. cameraNY.up.set( 0, 0, -1 );
  16399. cameraNY.lookAt( 0, -1, 0 );
  16400. cameraPZ.up.set( 0, -1, 0 );
  16401. cameraPZ.lookAt( 0, 0, 1 );
  16402. cameraNZ.up.set( 0, -1, 0 );
  16403. cameraNZ.lookAt( 0, 0, -1 );
  16404. } else {
  16405. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16406. }
  16407. for ( const camera of cameras ) {
  16408. this.add( camera );
  16409. camera.updateMatrixWorld();
  16410. }
  16411. }
  16412. /**
  16413. * Calling this method will render the given scene with the given renderer
  16414. * into the cube render target of the camera.
  16415. *
  16416. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16417. * @param {Scene} scene - The scene to render.
  16418. */
  16419. update( renderer, scene ) {
  16420. if ( this.parent === null ) this.updateMatrixWorld();
  16421. const { renderTarget, activeMipmapLevel } = this;
  16422. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16423. this.coordinateSystem = renderer.coordinateSystem;
  16424. this.updateCoordinateSystem();
  16425. }
  16426. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16427. const currentRenderTarget = renderer.getRenderTarget();
  16428. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16429. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16430. const currentXrEnabled = renderer.xr.enabled;
  16431. renderer.xr.enabled = false;
  16432. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16433. renderTarget.texture.generateMipmaps = false;
  16434. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16435. renderer.render( scene, cameraPX );
  16436. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16437. renderer.render( scene, cameraNX );
  16438. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16439. renderer.render( scene, cameraPY );
  16440. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16441. renderer.render( scene, cameraNY );
  16442. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16443. renderer.render( scene, cameraPZ );
  16444. // mipmaps are generated during the last call of render()
  16445. // at this point, all sides of the cube render target are defined
  16446. renderTarget.texture.generateMipmaps = generateMipmaps;
  16447. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16448. renderer.render( scene, cameraNZ );
  16449. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16450. renderer.xr.enabled = currentXrEnabled;
  16451. renderTarget.texture.needsPMREMUpdate = true;
  16452. }
  16453. }
  16454. /**
  16455. * Creates a cube texture made up of six images.
  16456. *
  16457. * ```js
  16458. * const loader = new THREE.CubeTextureLoader();
  16459. * loader.setPath( 'textures/cube/pisa/' );
  16460. *
  16461. * const textureCube = loader.load( [
  16462. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16463. * ] );
  16464. *
  16465. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16466. * ```
  16467. *
  16468. * @augments Texture
  16469. */
  16470. class CubeTexture extends Texture {
  16471. /**
  16472. * Constructs a new cube texture.
  16473. *
  16474. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16475. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16476. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16477. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16478. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16479. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16480. * @param {number} [format=RGBAFormat] - The texture format.
  16481. * @param {number} [type=UnsignedByteType] - The texture type.
  16482. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16483. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16484. */
  16485. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16486. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16487. /**
  16488. * This flag can be used for type testing.
  16489. *
  16490. * @type {boolean}
  16491. * @readonly
  16492. * @default true
  16493. */
  16494. this.isCubeTexture = true;
  16495. /**
  16496. * If set to `true`, the texture is flipped along the vertical axis when
  16497. * uploaded to the GPU.
  16498. *
  16499. * Overwritten and set to `false` by default.
  16500. *
  16501. * @type {boolean}
  16502. * @default false
  16503. */
  16504. this.flipY = false;
  16505. }
  16506. /**
  16507. * Alias for {@link CubeTexture#image}.
  16508. *
  16509. * @type {Array<Image>}
  16510. */
  16511. get images() {
  16512. return this.image;
  16513. }
  16514. set images( value ) {
  16515. this.image = value;
  16516. }
  16517. }
  16518. /**
  16519. * A cube render target used in context of {@link WebGLRenderer}.
  16520. *
  16521. * @augments WebGLRenderTarget
  16522. */
  16523. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16524. /**
  16525. * Constructs a new cube render target.
  16526. *
  16527. * @param {number} [size=1] - The size of the render target.
  16528. * @param {RenderTarget~Options} [options] - The configuration object.
  16529. */
  16530. constructor( size = 1, options = {} ) {
  16531. super( size, size, options );
  16532. /**
  16533. * This flag can be used for type testing.
  16534. *
  16535. * @type {boolean}
  16536. * @readonly
  16537. * @default true
  16538. */
  16539. this.isWebGLCubeRenderTarget = true;
  16540. const image = { width: size, height: size, depth: 1 };
  16541. const images = [ image, image, image, image, image, image ];
  16542. /**
  16543. * Overwritten with a different texture type.
  16544. *
  16545. * @type {DataArrayTexture}
  16546. */
  16547. this.texture = new CubeTexture( images );
  16548. this._setTextureOptions( options );
  16549. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16550. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16551. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16552. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16553. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16554. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16555. this.texture.isRenderTargetTexture = true;
  16556. }
  16557. /**
  16558. * Converts the given equirectangular texture to a cube map.
  16559. *
  16560. * @param {WebGLRenderer} renderer - The renderer.
  16561. * @param {Texture} texture - The equirectangular texture.
  16562. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16563. */
  16564. fromEquirectangularTexture( renderer, texture ) {
  16565. this.texture.type = texture.type;
  16566. this.texture.colorSpace = texture.colorSpace;
  16567. this.texture.generateMipmaps = texture.generateMipmaps;
  16568. this.texture.minFilter = texture.minFilter;
  16569. this.texture.magFilter = texture.magFilter;
  16570. const shader = {
  16571. uniforms: {
  16572. tEquirect: { value: null },
  16573. },
  16574. vertexShader: /* glsl */`
  16575. varying vec3 vWorldDirection;
  16576. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16577. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16578. }
  16579. void main() {
  16580. vWorldDirection = transformDirection( position, modelMatrix );
  16581. #include <begin_vertex>
  16582. #include <project_vertex>
  16583. }
  16584. `,
  16585. fragmentShader: /* glsl */`
  16586. uniform sampler2D tEquirect;
  16587. varying vec3 vWorldDirection;
  16588. #include <common>
  16589. void main() {
  16590. vec3 direction = normalize( vWorldDirection );
  16591. vec2 sampleUV = equirectUv( direction );
  16592. gl_FragColor = texture2D( tEquirect, sampleUV );
  16593. }
  16594. `
  16595. };
  16596. const geometry = new BoxGeometry( 5, 5, 5 );
  16597. const material = new ShaderMaterial( {
  16598. name: 'CubemapFromEquirect',
  16599. uniforms: cloneUniforms( shader.uniforms ),
  16600. vertexShader: shader.vertexShader,
  16601. fragmentShader: shader.fragmentShader,
  16602. side: BackSide,
  16603. blending: NoBlending
  16604. } );
  16605. material.uniforms.tEquirect.value = texture;
  16606. const mesh = new Mesh( geometry, material );
  16607. const currentMinFilter = texture.minFilter;
  16608. // Avoid blurred poles
  16609. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16610. const camera = new CubeCamera( 1, 10, this );
  16611. camera.update( renderer, mesh );
  16612. texture.minFilter = currentMinFilter;
  16613. mesh.geometry.dispose();
  16614. mesh.material.dispose();
  16615. return this;
  16616. }
  16617. /**
  16618. * Clears this cube render target.
  16619. *
  16620. * @param {WebGLRenderer} renderer - The renderer.
  16621. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16622. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16623. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16624. */
  16625. clear( renderer, color = true, depth = true, stencil = true ) {
  16626. const currentRenderTarget = renderer.getRenderTarget();
  16627. for ( let i = 0; i < 6; i ++ ) {
  16628. renderer.setRenderTarget( this, i );
  16629. renderer.clear( color, depth, stencil );
  16630. }
  16631. renderer.setRenderTarget( currentRenderTarget );
  16632. }
  16633. }
  16634. /**
  16635. * This is almost identical to an {@link Object3D}. Its purpose is to
  16636. * make working with groups of objects syntactically clearer.
  16637. *
  16638. * ```js
  16639. * // Create a group and add the two cubes.
  16640. * // These cubes can now be rotated / scaled etc as a group.
  16641. * const group = new THREE.Group();
  16642. *
  16643. * group.add( meshA );
  16644. * group.add( meshB );
  16645. *
  16646. * scene.add( group );
  16647. * ```
  16648. *
  16649. * @augments Object3D
  16650. */
  16651. class Group extends Object3D {
  16652. constructor() {
  16653. super();
  16654. /**
  16655. * This flag can be used for type testing.
  16656. *
  16657. * @type {boolean}
  16658. * @readonly
  16659. * @default true
  16660. */
  16661. this.isGroup = true;
  16662. this.type = 'Group';
  16663. }
  16664. }
  16665. const _moveEvent = { type: 'move' };
  16666. /**
  16667. * Class for representing a XR controller with its
  16668. * different coordinate systems.
  16669. *
  16670. * @private
  16671. */
  16672. class WebXRController {
  16673. /**
  16674. * Constructs a new XR controller.
  16675. */
  16676. constructor() {
  16677. /**
  16678. * A group representing the target ray space
  16679. * of the XR controller.
  16680. *
  16681. * @private
  16682. * @type {?Group}
  16683. * @default null
  16684. */
  16685. this._targetRay = null;
  16686. /**
  16687. * A group representing the grip space
  16688. * of the XR controller.
  16689. *
  16690. * @private
  16691. * @type {?Group}
  16692. * @default null
  16693. */
  16694. this._grip = null;
  16695. /**
  16696. * A group representing the hand space
  16697. * of the XR controller.
  16698. *
  16699. * @private
  16700. * @type {?Group}
  16701. * @default null
  16702. */
  16703. this._hand = null;
  16704. }
  16705. /**
  16706. * Returns a group representing the hand space of the XR controller.
  16707. *
  16708. * @return {Group} A group representing the hand space of the XR controller.
  16709. */
  16710. getHandSpace() {
  16711. if ( this._hand === null ) {
  16712. this._hand = new Group();
  16713. this._hand.matrixAutoUpdate = false;
  16714. this._hand.visible = false;
  16715. this._hand.joints = {};
  16716. this._hand.inputState = { pinching: false };
  16717. }
  16718. return this._hand;
  16719. }
  16720. /**
  16721. * Returns a group representing the target ray space of the XR controller.
  16722. *
  16723. * @return {Group} A group representing the target ray space of the XR controller.
  16724. */
  16725. getTargetRaySpace() {
  16726. if ( this._targetRay === null ) {
  16727. this._targetRay = new Group();
  16728. this._targetRay.matrixAutoUpdate = false;
  16729. this._targetRay.visible = false;
  16730. this._targetRay.hasLinearVelocity = false;
  16731. this._targetRay.linearVelocity = new Vector3();
  16732. this._targetRay.hasAngularVelocity = false;
  16733. this._targetRay.angularVelocity = new Vector3();
  16734. }
  16735. return this._targetRay;
  16736. }
  16737. /**
  16738. * Returns a group representing the grip space of the XR controller.
  16739. *
  16740. * @return {Group} A group representing the grip space of the XR controller.
  16741. */
  16742. getGripSpace() {
  16743. if ( this._grip === null ) {
  16744. this._grip = new Group();
  16745. this._grip.matrixAutoUpdate = false;
  16746. this._grip.visible = false;
  16747. this._grip.hasLinearVelocity = false;
  16748. this._grip.linearVelocity = new Vector3();
  16749. this._grip.hasAngularVelocity = false;
  16750. this._grip.angularVelocity = new Vector3();
  16751. }
  16752. return this._grip;
  16753. }
  16754. /**
  16755. * Dispatches the given event to the groups representing
  16756. * the different coordinate spaces of the XR controller.
  16757. *
  16758. * @param {Object} event - The event to dispatch.
  16759. * @return {WebXRController} A reference to this instance.
  16760. */
  16761. dispatchEvent( event ) {
  16762. if ( this._targetRay !== null ) {
  16763. this._targetRay.dispatchEvent( event );
  16764. }
  16765. if ( this._grip !== null ) {
  16766. this._grip.dispatchEvent( event );
  16767. }
  16768. if ( this._hand !== null ) {
  16769. this._hand.dispatchEvent( event );
  16770. }
  16771. return this;
  16772. }
  16773. /**
  16774. * Connects the controller with the given XR input source.
  16775. *
  16776. * @param {XRInputSource} inputSource - The input source.
  16777. * @return {WebXRController} A reference to this instance.
  16778. */
  16779. connect( inputSource ) {
  16780. if ( inputSource && inputSource.hand ) {
  16781. const hand = this._hand;
  16782. if ( hand ) {
  16783. for ( const inputjoint of inputSource.hand.values() ) {
  16784. // Initialize hand with joints when connected
  16785. this._getHandJoint( hand, inputjoint );
  16786. }
  16787. }
  16788. }
  16789. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16790. return this;
  16791. }
  16792. /**
  16793. * Disconnects the controller from the given XR input source.
  16794. *
  16795. * @param {XRInputSource} inputSource - The input source.
  16796. * @return {WebXRController} A reference to this instance.
  16797. */
  16798. disconnect( inputSource ) {
  16799. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16800. if ( this._targetRay !== null ) {
  16801. this._targetRay.visible = false;
  16802. }
  16803. if ( this._grip !== null ) {
  16804. this._grip.visible = false;
  16805. }
  16806. if ( this._hand !== null ) {
  16807. this._hand.visible = false;
  16808. }
  16809. return this;
  16810. }
  16811. /**
  16812. * Updates the controller with the given input source, XR frame and reference space.
  16813. * This updates the transformations of the groups that represent the different
  16814. * coordinate systems of the controller.
  16815. *
  16816. * @param {XRInputSource} inputSource - The input source.
  16817. * @param {XRFrame} frame - The XR frame.
  16818. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16819. * @return {WebXRController} A reference to this instance.
  16820. */
  16821. update( inputSource, frame, referenceSpace ) {
  16822. let inputPose = null;
  16823. let gripPose = null;
  16824. let handPose = null;
  16825. const targetRay = this._targetRay;
  16826. const grip = this._grip;
  16827. const hand = this._hand;
  16828. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16829. if ( hand && inputSource.hand ) {
  16830. handPose = true;
  16831. for ( const inputjoint of inputSource.hand.values() ) {
  16832. // Update the joints groups with the XRJoint poses
  16833. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16834. // The transform of this joint will be updated with the joint pose on each frame
  16835. const joint = this._getHandJoint( hand, inputjoint );
  16836. if ( jointPose !== null ) {
  16837. joint.matrix.fromArray( jointPose.transform.matrix );
  16838. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16839. joint.matrixWorldNeedsUpdate = true;
  16840. joint.jointRadius = jointPose.radius;
  16841. }
  16842. joint.visible = jointPose !== null;
  16843. }
  16844. // Custom events
  16845. // Check pinchz
  16846. const indexTip = hand.joints[ 'index-finger-tip' ];
  16847. const thumbTip = hand.joints[ 'thumb-tip' ];
  16848. const distance = indexTip.position.distanceTo( thumbTip.position );
  16849. const distanceToPinch = 0.02;
  16850. const threshold = 0.005;
  16851. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16852. hand.inputState.pinching = false;
  16853. this.dispatchEvent( {
  16854. type: 'pinchend',
  16855. handedness: inputSource.handedness,
  16856. target: this
  16857. } );
  16858. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16859. hand.inputState.pinching = true;
  16860. this.dispatchEvent( {
  16861. type: 'pinchstart',
  16862. handedness: inputSource.handedness,
  16863. target: this
  16864. } );
  16865. }
  16866. } else {
  16867. if ( grip !== null && inputSource.gripSpace ) {
  16868. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16869. if ( gripPose !== null ) {
  16870. grip.matrix.fromArray( gripPose.transform.matrix );
  16871. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16872. grip.matrixWorldNeedsUpdate = true;
  16873. if ( gripPose.linearVelocity ) {
  16874. grip.hasLinearVelocity = true;
  16875. grip.linearVelocity.copy( gripPose.linearVelocity );
  16876. } else {
  16877. grip.hasLinearVelocity = false;
  16878. }
  16879. if ( gripPose.angularVelocity ) {
  16880. grip.hasAngularVelocity = true;
  16881. grip.angularVelocity.copy( gripPose.angularVelocity );
  16882. } else {
  16883. grip.hasAngularVelocity = false;
  16884. }
  16885. }
  16886. }
  16887. }
  16888. if ( targetRay !== null ) {
  16889. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16890. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16891. if ( inputPose === null && gripPose !== null ) {
  16892. inputPose = gripPose;
  16893. }
  16894. if ( inputPose !== null ) {
  16895. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16896. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16897. targetRay.matrixWorldNeedsUpdate = true;
  16898. if ( inputPose.linearVelocity ) {
  16899. targetRay.hasLinearVelocity = true;
  16900. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16901. } else {
  16902. targetRay.hasLinearVelocity = false;
  16903. }
  16904. if ( inputPose.angularVelocity ) {
  16905. targetRay.hasAngularVelocity = true;
  16906. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16907. } else {
  16908. targetRay.hasAngularVelocity = false;
  16909. }
  16910. this.dispatchEvent( _moveEvent );
  16911. }
  16912. }
  16913. }
  16914. if ( targetRay !== null ) {
  16915. targetRay.visible = ( inputPose !== null );
  16916. }
  16917. if ( grip !== null ) {
  16918. grip.visible = ( gripPose !== null );
  16919. }
  16920. if ( hand !== null ) {
  16921. hand.visible = ( handPose !== null );
  16922. }
  16923. return this;
  16924. }
  16925. /**
  16926. * Returns a group representing the hand joint for the given input joint.
  16927. *
  16928. * @private
  16929. * @param {Group} hand - The group representing the hand space.
  16930. * @param {XRJointSpace} inputjoint - The hand joint data.
  16931. * @return {Group} A group representing the hand joint for the given input joint.
  16932. */
  16933. _getHandJoint( hand, inputjoint ) {
  16934. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16935. const joint = new Group();
  16936. joint.matrixAutoUpdate = false;
  16937. joint.visible = false;
  16938. hand.joints[ inputjoint.jointName ] = joint;
  16939. hand.add( joint );
  16940. }
  16941. return hand.joints[ inputjoint.jointName ];
  16942. }
  16943. }
  16944. /**
  16945. * This class can be used to define an exponential squared fog,
  16946. * which gives a clear view near the camera and a faster than exponentially
  16947. * densening fog farther from the camera.
  16948. *
  16949. * ```js
  16950. * const scene = new THREE.Scene();
  16951. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  16952. * ```
  16953. */
  16954. class FogExp2 {
  16955. /**
  16956. * Constructs a new fog.
  16957. *
  16958. * @param {number|Color} color - The fog's color.
  16959. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  16960. */
  16961. constructor( color, density = 0.00025 ) {
  16962. /**
  16963. * This flag can be used for type testing.
  16964. *
  16965. * @type {boolean}
  16966. * @readonly
  16967. * @default true
  16968. */
  16969. this.isFogExp2 = true;
  16970. /**
  16971. * The name of the fog.
  16972. *
  16973. * @type {string}
  16974. */
  16975. this.name = '';
  16976. /**
  16977. * The fog's color.
  16978. *
  16979. * @type {Color}
  16980. */
  16981. this.color = new Color( color );
  16982. /**
  16983. * Defines how fast the fog will grow dense.
  16984. *
  16985. * @type {number}
  16986. * @default 0.00025
  16987. */
  16988. this.density = density;
  16989. }
  16990. /**
  16991. * Returns a new fog with copied values from this instance.
  16992. *
  16993. * @return {FogExp2} A clone of this instance.
  16994. */
  16995. clone() {
  16996. return new FogExp2( this.color, this.density );
  16997. }
  16998. /**
  16999. * Serializes the fog into JSON.
  17000. *
  17001. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17002. * @return {Object} A JSON object representing the serialized fog
  17003. */
  17004. toJSON( /* meta */ ) {
  17005. return {
  17006. type: 'FogExp2',
  17007. name: this.name,
  17008. color: this.color.getHex(),
  17009. density: this.density
  17010. };
  17011. }
  17012. }
  17013. /**
  17014. * This class can be used to define a linear fog that grows linearly denser
  17015. * with the distance.
  17016. *
  17017. * ```js
  17018. * const scene = new THREE.Scene();
  17019. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17020. * ```
  17021. */
  17022. class Fog {
  17023. /**
  17024. * Constructs a new fog.
  17025. *
  17026. * @param {number|Color} color - The fog's color.
  17027. * @param {number} [near=1] - The minimum distance to start applying fog.
  17028. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17029. */
  17030. constructor( color, near = 1, far = 1000 ) {
  17031. /**
  17032. * This flag can be used for type testing.
  17033. *
  17034. * @type {boolean}
  17035. * @readonly
  17036. * @default true
  17037. */
  17038. this.isFog = true;
  17039. /**
  17040. * The name of the fog.
  17041. *
  17042. * @type {string}
  17043. */
  17044. this.name = '';
  17045. /**
  17046. * The fog's color.
  17047. *
  17048. * @type {Color}
  17049. */
  17050. this.color = new Color( color );
  17051. /**
  17052. * The minimum distance to start applying fog. Objects that are less than
  17053. * `near` units from the active camera won't be affected by fog.
  17054. *
  17055. * @type {number}
  17056. * @default 1
  17057. */
  17058. this.near = near;
  17059. /**
  17060. * The maximum distance at which fog stops being calculated and applied.
  17061. * Objects that are more than `far` units away from the active camera won't
  17062. * be affected by fog.
  17063. *
  17064. * @type {number}
  17065. * @default 1000
  17066. */
  17067. this.far = far;
  17068. }
  17069. /**
  17070. * Returns a new fog with copied values from this instance.
  17071. *
  17072. * @return {Fog} A clone of this instance.
  17073. */
  17074. clone() {
  17075. return new Fog( this.color, this.near, this.far );
  17076. }
  17077. /**
  17078. * Serializes the fog into JSON.
  17079. *
  17080. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17081. * @return {Object} A JSON object representing the serialized fog
  17082. */
  17083. toJSON( /* meta */ ) {
  17084. return {
  17085. type: 'Fog',
  17086. name: this.name,
  17087. color: this.color.getHex(),
  17088. near: this.near,
  17089. far: this.far
  17090. };
  17091. }
  17092. }
  17093. /**
  17094. * Scenes allow you to set up what is to be rendered and where by three.js.
  17095. * This is where you place 3D objects like meshes, lines or lights.
  17096. *
  17097. * @augments Object3D
  17098. */
  17099. class Scene extends Object3D {
  17100. /**
  17101. * Constructs a new scene.
  17102. */
  17103. constructor() {
  17104. super();
  17105. /**
  17106. * This flag can be used for type testing.
  17107. *
  17108. * @type {boolean}
  17109. * @readonly
  17110. * @default true
  17111. */
  17112. this.isScene = true;
  17113. this.type = 'Scene';
  17114. /**
  17115. * Defines the background of the scene. Valid inputs are:
  17116. *
  17117. * - A color for defining a uniform colored background.
  17118. * - A texture for defining a (flat) textured background.
  17119. * - Cube textures or equirectangular textures for defining a skybox.
  17120. *
  17121. * @type {?(Color|Texture)}
  17122. * @default null
  17123. */
  17124. this.background = null;
  17125. /**
  17126. * Sets the environment map for all physical materials in the scene. However,
  17127. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17128. * material property.
  17129. *
  17130. * @type {?Texture}
  17131. * @default null
  17132. */
  17133. this.environment = null;
  17134. /**
  17135. * A fog instance defining the type of fog that affects everything
  17136. * rendered in the scene.
  17137. *
  17138. * @type {?(Fog|FogExp2)}
  17139. * @default null
  17140. */
  17141. this.fog = null;
  17142. /**
  17143. * Sets the blurriness of the background. Only influences environment maps
  17144. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17145. * and `1`.
  17146. *
  17147. * @type {number}
  17148. * @default 0
  17149. */
  17150. this.backgroundBlurriness = 0;
  17151. /**
  17152. * Attenuates the color of the background. Only applies to background textures.
  17153. *
  17154. * @type {number}
  17155. * @default 1
  17156. */
  17157. this.backgroundIntensity = 1;
  17158. /**
  17159. * The rotation of the background in radians. Only influences environment maps
  17160. * assigned to {@link Scene#background}.
  17161. *
  17162. * @type {Euler}
  17163. * @default (0,0,0)
  17164. */
  17165. this.backgroundRotation = new Euler();
  17166. /**
  17167. * Attenuates the color of the environment. Only influences environment maps
  17168. * assigned to {@link Scene#environment}.
  17169. *
  17170. * @type {number}
  17171. * @default 1
  17172. */
  17173. this.environmentIntensity = 1;
  17174. /**
  17175. * The rotation of the environment map in radians. Only influences physical materials
  17176. * in the scene when {@link Scene#environment} is used.
  17177. *
  17178. * @type {Euler}
  17179. * @default (0,0,0)
  17180. */
  17181. this.environmentRotation = new Euler();
  17182. /**
  17183. * Forces everything in the scene to be rendered with the defined material. It is possible
  17184. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17185. *
  17186. * @type {?Material}
  17187. * @default null
  17188. */
  17189. this.overrideMaterial = null;
  17190. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17191. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17192. }
  17193. }
  17194. copy( source, recursive ) {
  17195. super.copy( source, recursive );
  17196. if ( source.background !== null ) this.background = source.background.clone();
  17197. if ( source.environment !== null ) this.environment = source.environment.clone();
  17198. if ( source.fog !== null ) this.fog = source.fog.clone();
  17199. this.backgroundBlurriness = source.backgroundBlurriness;
  17200. this.backgroundIntensity = source.backgroundIntensity;
  17201. this.backgroundRotation.copy( source.backgroundRotation );
  17202. this.environmentIntensity = source.environmentIntensity;
  17203. this.environmentRotation.copy( source.environmentRotation );
  17204. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17205. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17206. return this;
  17207. }
  17208. toJSON( meta ) {
  17209. const data = super.toJSON( meta );
  17210. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17211. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17212. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17213. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17214. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17215. data.object.environmentRotation = this.environmentRotation.toArray();
  17216. return data;
  17217. }
  17218. }
  17219. /**
  17220. * "Interleaved" means that multiple attributes, possibly of different types,
  17221. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17222. *
  17223. * An introduction into interleaved arrays can be found here: [Interleaved array basics]{@link https://blog.tojicode.com/2011/05/interleaved-array-basics.html}
  17224. */
  17225. class InterleavedBuffer {
  17226. /**
  17227. * Constructs a new interleaved buffer.
  17228. *
  17229. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17230. * @param {number} stride - The number of typed-array elements per vertex.
  17231. */
  17232. constructor( array, stride ) {
  17233. /**
  17234. * This flag can be used for type testing.
  17235. *
  17236. * @type {boolean}
  17237. * @readonly
  17238. * @default true
  17239. */
  17240. this.isInterleavedBuffer = true;
  17241. /**
  17242. * A typed array with a shared buffer storing attribute data.
  17243. *
  17244. * @type {TypedArray}
  17245. */
  17246. this.array = array;
  17247. /**
  17248. * The number of typed-array elements per vertex.
  17249. *
  17250. * @type {number}
  17251. */
  17252. this.stride = stride;
  17253. /**
  17254. * The total number of elements in the array
  17255. *
  17256. * @type {number}
  17257. * @readonly
  17258. */
  17259. this.count = array !== undefined ? array.length / stride : 0;
  17260. /**
  17261. * Defines the intended usage pattern of the data store for optimization purposes.
  17262. *
  17263. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17264. * instantiate a new one and set the desired usage before the next render.
  17265. *
  17266. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17267. * @default StaticDrawUsage
  17268. */
  17269. this.usage = StaticDrawUsage;
  17270. /**
  17271. * This can be used to only update some components of stored vectors (for example, just the
  17272. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17273. *
  17274. * @type {Array<Object>}
  17275. */
  17276. this.updateRanges = [];
  17277. /**
  17278. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17279. *
  17280. * @type {number}
  17281. */
  17282. this.version = 0;
  17283. /**
  17284. * The UUID of the interleaved buffer.
  17285. *
  17286. * @type {string}
  17287. * @readonly
  17288. */
  17289. this.uuid = generateUUID();
  17290. }
  17291. /**
  17292. * A callback function that is executed after the renderer has transferred the attribute array
  17293. * data to the GPU.
  17294. */
  17295. onUploadCallback() {}
  17296. /**
  17297. * Flag to indicate that this attribute has changed and should be re-sent to
  17298. * the GPU. Set this to `true` when you modify the value of the array.
  17299. *
  17300. * @type {number}
  17301. * @default false
  17302. * @param {boolean} value
  17303. */
  17304. set needsUpdate( value ) {
  17305. if ( value === true ) this.version ++;
  17306. }
  17307. /**
  17308. * Sets the usage of this interleaved buffer.
  17309. *
  17310. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17311. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17312. */
  17313. setUsage( value ) {
  17314. this.usage = value;
  17315. return this;
  17316. }
  17317. /**
  17318. * Adds a range of data in the data array to be updated on the GPU.
  17319. *
  17320. * @param {number} start - Position at which to start update.
  17321. * @param {number} count - The number of components to update.
  17322. */
  17323. addUpdateRange( start, count ) {
  17324. this.updateRanges.push( { start, count } );
  17325. }
  17326. /**
  17327. * Clears the update ranges.
  17328. */
  17329. clearUpdateRanges() {
  17330. this.updateRanges.length = 0;
  17331. }
  17332. /**
  17333. * Copies the values of the given interleaved buffer to this instance.
  17334. *
  17335. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17336. * @return {InterleavedBuffer} A reference to this instance.
  17337. */
  17338. copy( source ) {
  17339. this.array = new source.array.constructor( source.array );
  17340. this.count = source.count;
  17341. this.stride = source.stride;
  17342. this.usage = source.usage;
  17343. return this;
  17344. }
  17345. /**
  17346. * Copies a vector from the given interleaved buffer to this one. The start
  17347. * and destination position in the attribute buffers are represented by the
  17348. * given indices.
  17349. *
  17350. * @param {number} index1 - The destination index into this interleaved buffer.
  17351. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17352. * @param {number} index2 - The source index into the given interleaved buffer.
  17353. * @return {InterleavedBuffer} A reference to this instance.
  17354. */
  17355. copyAt( index1, interleavedBuffer, index2 ) {
  17356. index1 *= this.stride;
  17357. index2 *= interleavedBuffer.stride;
  17358. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17359. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17360. }
  17361. return this;
  17362. }
  17363. /**
  17364. * Sets the given array data in the interleaved buffer.
  17365. *
  17366. * @param {(TypedArray|Array)} value - The array data to set.
  17367. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17368. * @return {InterleavedBuffer} A reference to this instance.
  17369. */
  17370. set( value, offset = 0 ) {
  17371. this.array.set( value, offset );
  17372. return this;
  17373. }
  17374. /**
  17375. * Returns a new interleaved buffer with copied values from this instance.
  17376. *
  17377. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17378. * @return {InterleavedBuffer} A clone of this instance.
  17379. */
  17380. clone( data ) {
  17381. if ( data.arrayBuffers === undefined ) {
  17382. data.arrayBuffers = {};
  17383. }
  17384. if ( this.array.buffer._uuid === undefined ) {
  17385. this.array.buffer._uuid = generateUUID();
  17386. }
  17387. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17388. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17389. }
  17390. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17391. const ib = new this.constructor( array, this.stride );
  17392. ib.setUsage( this.usage );
  17393. return ib;
  17394. }
  17395. /**
  17396. * Sets the given callback function that is executed after the Renderer has transferred
  17397. * the array data to the GPU. Can be used to perform clean-up operations after
  17398. * the upload when data are not needed anymore on the CPU side.
  17399. *
  17400. * @param {Function} callback - The `onUpload()` callback.
  17401. * @return {InterleavedBuffer} A reference to this instance.
  17402. */
  17403. onUpload( callback ) {
  17404. this.onUploadCallback = callback;
  17405. return this;
  17406. }
  17407. /**
  17408. * Serializes the interleaved buffer into JSON.
  17409. *
  17410. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17411. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17412. */
  17413. toJSON( data ) {
  17414. if ( data.arrayBuffers === undefined ) {
  17415. data.arrayBuffers = {};
  17416. }
  17417. // generate UUID for array buffer if necessary
  17418. if ( this.array.buffer._uuid === undefined ) {
  17419. this.array.buffer._uuid = generateUUID();
  17420. }
  17421. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17422. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17423. }
  17424. //
  17425. return {
  17426. uuid: this.uuid,
  17427. buffer: this.array.buffer._uuid,
  17428. type: this.array.constructor.name,
  17429. stride: this.stride
  17430. };
  17431. }
  17432. }
  17433. const _vector$7 = /*@__PURE__*/ new Vector3();
  17434. /**
  17435. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17436. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17437. * different offsets into the buffer.
  17438. */
  17439. class InterleavedBufferAttribute {
  17440. /**
  17441. * Constructs a new interleaved buffer attribute.
  17442. *
  17443. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17444. * @param {number} itemSize - The item size.
  17445. * @param {number} offset - The attribute offset into the buffer.
  17446. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17447. */
  17448. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17449. /**
  17450. * This flag can be used for type testing.
  17451. *
  17452. * @type {boolean}
  17453. * @readonly
  17454. * @default true
  17455. */
  17456. this.isInterleavedBufferAttribute = true;
  17457. /**
  17458. * The name of the buffer attribute.
  17459. *
  17460. * @type {string}
  17461. */
  17462. this.name = '';
  17463. /**
  17464. * The buffer holding the interleaved data.
  17465. *
  17466. * @type {InterleavedBuffer}
  17467. */
  17468. this.data = interleavedBuffer;
  17469. /**
  17470. * The item size, see {@link BufferAttribute#itemSize}.
  17471. *
  17472. * @type {number}
  17473. */
  17474. this.itemSize = itemSize;
  17475. /**
  17476. * The attribute offset into the buffer.
  17477. *
  17478. * @type {number}
  17479. */
  17480. this.offset = offset;
  17481. /**
  17482. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17483. *
  17484. * @type {InterleavedBuffer}
  17485. */
  17486. this.normalized = normalized;
  17487. }
  17488. /**
  17489. * The item count of this buffer attribute.
  17490. *
  17491. * @type {number}
  17492. * @readonly
  17493. */
  17494. get count() {
  17495. return this.data.count;
  17496. }
  17497. /**
  17498. * The array holding the interleaved buffer attribute data.
  17499. *
  17500. * @type {TypedArray}
  17501. */
  17502. get array() {
  17503. return this.data.array;
  17504. }
  17505. /**
  17506. * Flag to indicate that this attribute has changed and should be re-sent to
  17507. * the GPU. Set this to `true` when you modify the value of the array.
  17508. *
  17509. * @type {number}
  17510. * @default false
  17511. * @param {boolean} value
  17512. */
  17513. set needsUpdate( value ) {
  17514. this.data.needsUpdate = value;
  17515. }
  17516. /**
  17517. * Applies the given 4x4 matrix to the given attribute. Only works with
  17518. * item size `3`.
  17519. *
  17520. * @param {Matrix4} m - The matrix to apply.
  17521. * @return {InterleavedBufferAttribute} A reference to this instance.
  17522. */
  17523. applyMatrix4( m ) {
  17524. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17525. _vector$7.fromBufferAttribute( this, i );
  17526. _vector$7.applyMatrix4( m );
  17527. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17528. }
  17529. return this;
  17530. }
  17531. /**
  17532. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17533. * item size `3`.
  17534. *
  17535. * @param {Matrix3} m - The normal matrix to apply.
  17536. * @return {InterleavedBufferAttribute} A reference to this instance.
  17537. */
  17538. applyNormalMatrix( m ) {
  17539. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17540. _vector$7.fromBufferAttribute( this, i );
  17541. _vector$7.applyNormalMatrix( m );
  17542. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17543. }
  17544. return this;
  17545. }
  17546. /**
  17547. * Applies the given 4x4 matrix to the given attribute. Only works with
  17548. * item size `3` and with direction vectors.
  17549. *
  17550. * @param {Matrix4} m - The matrix to apply.
  17551. * @return {InterleavedBufferAttribute} A reference to this instance.
  17552. */
  17553. transformDirection( m ) {
  17554. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17555. _vector$7.fromBufferAttribute( this, i );
  17556. _vector$7.transformDirection( m );
  17557. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17558. }
  17559. return this;
  17560. }
  17561. /**
  17562. * Returns the given component of the vector at the given index.
  17563. *
  17564. * @param {number} index - The index into the buffer attribute.
  17565. * @param {number} component - The component index.
  17566. * @return {number} The returned value.
  17567. */
  17568. getComponent( index, component ) {
  17569. let value = this.array[ index * this.data.stride + this.offset + component ];
  17570. if ( this.normalized ) value = denormalize( value, this.array );
  17571. return value;
  17572. }
  17573. /**
  17574. * Sets the given value to the given component of the vector at the given index.
  17575. *
  17576. * @param {number} index - The index into the buffer attribute.
  17577. * @param {number} component - The component index.
  17578. * @param {number} value - The value to set.
  17579. * @return {InterleavedBufferAttribute} A reference to this instance.
  17580. */
  17581. setComponent( index, component, value ) {
  17582. if ( this.normalized ) value = normalize( value, this.array );
  17583. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17584. return this;
  17585. }
  17586. /**
  17587. * Sets the x component of the vector at the given index.
  17588. *
  17589. * @param {number} index - The index into the buffer attribute.
  17590. * @param {number} x - The value to set.
  17591. * @return {InterleavedBufferAttribute} A reference to this instance.
  17592. */
  17593. setX( index, x ) {
  17594. if ( this.normalized ) x = normalize( x, this.array );
  17595. this.data.array[ index * this.data.stride + this.offset ] = x;
  17596. return this;
  17597. }
  17598. /**
  17599. * Sets the y component of the vector at the given index.
  17600. *
  17601. * @param {number} index - The index into the buffer attribute.
  17602. * @param {number} y - The value to set.
  17603. * @return {InterleavedBufferAttribute} A reference to this instance.
  17604. */
  17605. setY( index, y ) {
  17606. if ( this.normalized ) y = normalize( y, this.array );
  17607. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17608. return this;
  17609. }
  17610. /**
  17611. * Sets the z component of the vector at the given index.
  17612. *
  17613. * @param {number} index - The index into the buffer attribute.
  17614. * @param {number} z - The value to set.
  17615. * @return {InterleavedBufferAttribute} A reference to this instance.
  17616. */
  17617. setZ( index, z ) {
  17618. if ( this.normalized ) z = normalize( z, this.array );
  17619. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17620. return this;
  17621. }
  17622. /**
  17623. * Sets the w component of the vector at the given index.
  17624. *
  17625. * @param {number} index - The index into the buffer attribute.
  17626. * @param {number} w - The value to set.
  17627. * @return {InterleavedBufferAttribute} A reference to this instance.
  17628. */
  17629. setW( index, w ) {
  17630. if ( this.normalized ) w = normalize( w, this.array );
  17631. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17632. return this;
  17633. }
  17634. /**
  17635. * Returns the x component of the vector at the given index.
  17636. *
  17637. * @param {number} index - The index into the buffer attribute.
  17638. * @return {number} The x component.
  17639. */
  17640. getX( index ) {
  17641. let x = this.data.array[ index * this.data.stride + this.offset ];
  17642. if ( this.normalized ) x = denormalize( x, this.array );
  17643. return x;
  17644. }
  17645. /**
  17646. * Returns the y component of the vector at the given index.
  17647. *
  17648. * @param {number} index - The index into the buffer attribute.
  17649. * @return {number} The y component.
  17650. */
  17651. getY( index ) {
  17652. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17653. if ( this.normalized ) y = denormalize( y, this.array );
  17654. return y;
  17655. }
  17656. /**
  17657. * Returns the z component of the vector at the given index.
  17658. *
  17659. * @param {number} index - The index into the buffer attribute.
  17660. * @return {number} The z component.
  17661. */
  17662. getZ( index ) {
  17663. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17664. if ( this.normalized ) z = denormalize( z, this.array );
  17665. return z;
  17666. }
  17667. /**
  17668. * Returns the w component of the vector at the given index.
  17669. *
  17670. * @param {number} index - The index into the buffer attribute.
  17671. * @return {number} The w component.
  17672. */
  17673. getW( index ) {
  17674. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17675. if ( this.normalized ) w = denormalize( w, this.array );
  17676. return w;
  17677. }
  17678. /**
  17679. * Sets the x and y component of the vector at the given index.
  17680. *
  17681. * @param {number} index - The index into the buffer attribute.
  17682. * @param {number} x - The value for the x component to set.
  17683. * @param {number} y - The value for the y component to set.
  17684. * @return {InterleavedBufferAttribute} A reference to this instance.
  17685. */
  17686. setXY( index, x, y ) {
  17687. index = index * this.data.stride + this.offset;
  17688. if ( this.normalized ) {
  17689. x = normalize( x, this.array );
  17690. y = normalize( y, this.array );
  17691. }
  17692. this.data.array[ index + 0 ] = x;
  17693. this.data.array[ index + 1 ] = y;
  17694. return this;
  17695. }
  17696. /**
  17697. * Sets the x, y and z component of the vector at the given index.
  17698. *
  17699. * @param {number} index - The index into the buffer attribute.
  17700. * @param {number} x - The value for the x component to set.
  17701. * @param {number} y - The value for the y component to set.
  17702. * @param {number} z - The value for the z component to set.
  17703. * @return {InterleavedBufferAttribute} A reference to this instance.
  17704. */
  17705. setXYZ( index, x, y, z ) {
  17706. index = index * this.data.stride + this.offset;
  17707. if ( this.normalized ) {
  17708. x = normalize( x, this.array );
  17709. y = normalize( y, this.array );
  17710. z = normalize( z, this.array );
  17711. }
  17712. this.data.array[ index + 0 ] = x;
  17713. this.data.array[ index + 1 ] = y;
  17714. this.data.array[ index + 2 ] = z;
  17715. return this;
  17716. }
  17717. /**
  17718. * Sets the x, y, z and w component of the vector at the given index.
  17719. *
  17720. * @param {number} index - The index into the buffer attribute.
  17721. * @param {number} x - The value for the x component to set.
  17722. * @param {number} y - The value for the y component to set.
  17723. * @param {number} z - The value for the z component to set.
  17724. * @param {number} w - The value for the w component to set.
  17725. * @return {InterleavedBufferAttribute} A reference to this instance.
  17726. */
  17727. setXYZW( index, x, y, z, w ) {
  17728. index = index * this.data.stride + this.offset;
  17729. if ( this.normalized ) {
  17730. x = normalize( x, this.array );
  17731. y = normalize( y, this.array );
  17732. z = normalize( z, this.array );
  17733. w = normalize( w, this.array );
  17734. }
  17735. this.data.array[ index + 0 ] = x;
  17736. this.data.array[ index + 1 ] = y;
  17737. this.data.array[ index + 2 ] = z;
  17738. this.data.array[ index + 3 ] = w;
  17739. return this;
  17740. }
  17741. /**
  17742. * Returns a new buffer attribute with copied values from this instance.
  17743. *
  17744. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17745. *
  17746. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17747. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17748. */
  17749. clone( data ) {
  17750. if ( data === undefined ) {
  17751. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17752. const array = [];
  17753. for ( let i = 0; i < this.count; i ++ ) {
  17754. const index = i * this.data.stride + this.offset;
  17755. for ( let j = 0; j < this.itemSize; j ++ ) {
  17756. array.push( this.data.array[ index + j ] );
  17757. }
  17758. }
  17759. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17760. } else {
  17761. if ( data.interleavedBuffers === undefined ) {
  17762. data.interleavedBuffers = {};
  17763. }
  17764. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17765. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17766. }
  17767. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17768. }
  17769. }
  17770. /**
  17771. * Serializes the buffer attribute into JSON.
  17772. *
  17773. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17774. *
  17775. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17776. * @return {Object} A JSON object representing the serialized buffer attribute.
  17777. */
  17778. toJSON( data ) {
  17779. if ( data === undefined ) {
  17780. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17781. const array = [];
  17782. for ( let i = 0; i < this.count; i ++ ) {
  17783. const index = i * this.data.stride + this.offset;
  17784. for ( let j = 0; j < this.itemSize; j ++ ) {
  17785. array.push( this.data.array[ index + j ] );
  17786. }
  17787. }
  17788. // de-interleave data and save it as an ordinary buffer attribute for now
  17789. return {
  17790. itemSize: this.itemSize,
  17791. type: this.array.constructor.name,
  17792. array: array,
  17793. normalized: this.normalized
  17794. };
  17795. } else {
  17796. // save as true interleaved attribute
  17797. if ( data.interleavedBuffers === undefined ) {
  17798. data.interleavedBuffers = {};
  17799. }
  17800. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17801. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17802. }
  17803. return {
  17804. isInterleavedBufferAttribute: true,
  17805. itemSize: this.itemSize,
  17806. data: this.data.uuid,
  17807. offset: this.offset,
  17808. normalized: this.normalized
  17809. };
  17810. }
  17811. }
  17812. }
  17813. /**
  17814. * A material for rendering instances of {@link Sprite}.
  17815. *
  17816. * ```js
  17817. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17818. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17819. *
  17820. * const sprite = new THREE.Sprite( material );
  17821. * sprite.scale.set(200, 200, 1)
  17822. * scene.add( sprite );
  17823. * ```
  17824. *
  17825. * @augments Material
  17826. */
  17827. class SpriteMaterial extends Material {
  17828. /**
  17829. * Constructs a new sprite material.
  17830. *
  17831. * @param {Object} [parameters] - An object with one or more properties
  17832. * defining the material's appearance. Any property of the material
  17833. * (including any property from inherited materials) can be passed
  17834. * in here. Color values can be passed any type of value accepted
  17835. * by {@link Color#set}.
  17836. */
  17837. constructor( parameters ) {
  17838. super();
  17839. /**
  17840. * This flag can be used for type testing.
  17841. *
  17842. * @type {boolean}
  17843. * @readonly
  17844. * @default true
  17845. */
  17846. this.isSpriteMaterial = true;
  17847. this.type = 'SpriteMaterial';
  17848. /**
  17849. * Color of the material.
  17850. *
  17851. * @type {Color}
  17852. * @default (1,1,1)
  17853. */
  17854. this.color = new Color( 0xffffff );
  17855. /**
  17856. * The color map. May optionally include an alpha channel, typically combined
  17857. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17858. * color is modulated by the diffuse `color`.
  17859. *
  17860. * @type {?Texture}
  17861. * @default null
  17862. */
  17863. this.map = null;
  17864. /**
  17865. * The alpha map is a grayscale texture that controls the opacity across the
  17866. * surface (black: fully transparent; white: fully opaque).
  17867. *
  17868. * Only the color of the texture is used, ignoring the alpha channel if one
  17869. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17870. * when sampling this texture due to the extra bit of precision provided for
  17871. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17872. * luminance/alpha textures will also still work as expected.
  17873. *
  17874. * @type {?Texture}
  17875. * @default null
  17876. */
  17877. this.alphaMap = null;
  17878. /**
  17879. * The rotation of the sprite in radians.
  17880. *
  17881. * @type {number}
  17882. * @default 0
  17883. */
  17884. this.rotation = 0;
  17885. /**
  17886. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  17887. *
  17888. * @type {boolean}
  17889. * @default true
  17890. */
  17891. this.sizeAttenuation = true;
  17892. /**
  17893. * Overwritten since sprite materials are transparent
  17894. * by default.
  17895. *
  17896. * @type {boolean}
  17897. * @default true
  17898. */
  17899. this.transparent = true;
  17900. /**
  17901. * Whether the material is affected by fog or not.
  17902. *
  17903. * @type {boolean}
  17904. * @default true
  17905. */
  17906. this.fog = true;
  17907. this.setValues( parameters );
  17908. }
  17909. copy( source ) {
  17910. super.copy( source );
  17911. this.color.copy( source.color );
  17912. this.map = source.map;
  17913. this.alphaMap = source.alphaMap;
  17914. this.rotation = source.rotation;
  17915. this.sizeAttenuation = source.sizeAttenuation;
  17916. this.fog = source.fog;
  17917. return this;
  17918. }
  17919. }
  17920. let _geometry;
  17921. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17922. const _worldScale = /*@__PURE__*/ new Vector3();
  17923. const _mvPosition = /*@__PURE__*/ new Vector3();
  17924. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17925. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17926. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17927. const _vA = /*@__PURE__*/ new Vector3();
  17928. const _vB = /*@__PURE__*/ new Vector3();
  17929. const _vC = /*@__PURE__*/ new Vector3();
  17930. const _uvA = /*@__PURE__*/ new Vector2();
  17931. const _uvB = /*@__PURE__*/ new Vector2();
  17932. const _uvC = /*@__PURE__*/ new Vector2();
  17933. /**
  17934. * A sprite is a plane that always faces towards the camera, generally with a
  17935. * partially transparent texture applied.
  17936. *
  17937. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  17938. * have no effect.
  17939. *
  17940. * ```js
  17941. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  17942. * const material = new THREE.SpriteMaterial( { map: map } );
  17943. *
  17944. * const sprite = new THREE.Sprite( material );
  17945. * scene.add( sprite );
  17946. * ```
  17947. *
  17948. * @augments Object3D
  17949. */
  17950. class Sprite extends Object3D {
  17951. /**
  17952. * Constructs a new sprite.
  17953. *
  17954. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  17955. */
  17956. constructor( material = new SpriteMaterial() ) {
  17957. super();
  17958. /**
  17959. * This flag can be used for type testing.
  17960. *
  17961. * @type {boolean}
  17962. * @readonly
  17963. * @default true
  17964. */
  17965. this.isSprite = true;
  17966. this.type = 'Sprite';
  17967. if ( _geometry === undefined ) {
  17968. _geometry = new BufferGeometry();
  17969. const float32Array = new Float32Array( [
  17970. -0.5, -0.5, 0, 0, 0,
  17971. 0.5, -0.5, 0, 1, 0,
  17972. 0.5, 0.5, 0, 1, 1,
  17973. -0.5, 0.5, 0, 0, 1
  17974. ] );
  17975. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17976. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17977. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17978. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17979. }
  17980. /**
  17981. * The sprite geometry.
  17982. *
  17983. * @type {BufferGeometry}
  17984. */
  17985. this.geometry = _geometry;
  17986. /**
  17987. * The sprite material.
  17988. *
  17989. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  17990. */
  17991. this.material = material;
  17992. /**
  17993. * The sprite's anchor point, and the point around which the sprite rotates.
  17994. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  17995. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  17996. *
  17997. * @type {Vector2}
  17998. * @default (0.5,0.5)
  17999. */
  18000. this.center = new Vector2( 0.5, 0.5 );
  18001. /**
  18002. * The number of instances of this sprite.
  18003. * Can only be used with {@link WebGPURenderer}.
  18004. *
  18005. * @type {number}
  18006. * @default 1
  18007. */
  18008. this.count = 1;
  18009. }
  18010. /**
  18011. * Computes intersection points between a casted ray and this sprite.
  18012. *
  18013. * @param {Raycaster} raycaster - The raycaster.
  18014. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18015. */
  18016. raycast( raycaster, intersects ) {
  18017. if ( raycaster.camera === null ) {
  18018. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18019. }
  18020. _worldScale.setFromMatrixScale( this.matrixWorld );
  18021. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18022. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18023. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18024. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18025. _worldScale.multiplyScalar( - _mvPosition.z );
  18026. }
  18027. const rotation = this.material.rotation;
  18028. let sin, cos;
  18029. if ( rotation !== 0 ) {
  18030. cos = Math.cos( rotation );
  18031. sin = Math.sin( rotation );
  18032. }
  18033. const center = this.center;
  18034. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18035. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18036. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18037. _uvA.set( 0, 0 );
  18038. _uvB.set( 1, 0 );
  18039. _uvC.set( 1, 1 );
  18040. // check first triangle
  18041. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18042. if ( intersect === null ) {
  18043. // check second triangle
  18044. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18045. _uvB.set( 0, 1 );
  18046. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18047. if ( intersect === null ) {
  18048. return;
  18049. }
  18050. }
  18051. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18052. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18053. intersects.push( {
  18054. distance: distance,
  18055. point: _intersectPoint.clone(),
  18056. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18057. face: null,
  18058. object: this
  18059. } );
  18060. }
  18061. copy( source, recursive ) {
  18062. super.copy( source, recursive );
  18063. if ( source.center !== undefined ) this.center.copy( source.center );
  18064. this.material = source.material;
  18065. return this;
  18066. }
  18067. }
  18068. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18069. // compute position in camera space
  18070. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18071. // to check if rotation is not zero
  18072. if ( sin !== undefined ) {
  18073. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18074. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18075. } else {
  18076. _rotatedPosition.copy( _alignedPosition );
  18077. }
  18078. vertexPosition.copy( mvPosition );
  18079. vertexPosition.x += _rotatedPosition.x;
  18080. vertexPosition.y += _rotatedPosition.y;
  18081. // transform to world space
  18082. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18083. }
  18084. const _v1$2 = /*@__PURE__*/ new Vector3();
  18085. const _v2$1 = /*@__PURE__*/ new Vector3();
  18086. /**
  18087. * A component for providing a basic Level of Detail (LOD) mechanism.
  18088. *
  18089. * Every LOD level is associated with an object, and rendering can be switched
  18090. * between them at the distances specified. Typically you would create, say,
  18091. * three meshes, one for far away (low detail), one for mid range (medium
  18092. * detail) and one for close up (high detail).
  18093. *
  18094. * ```js
  18095. * const lod = new THREE.LOD();
  18096. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18097. *
  18098. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18099. * for( let i = 0; i < 3; i++ ) {
  18100. *
  18101. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18102. * const mesh = new THREE.Mesh( geometry, material );
  18103. * lod.addLevel( mesh, i * 75 );
  18104. *
  18105. * }
  18106. *
  18107. * scene.add( lod );
  18108. * ```
  18109. *
  18110. * @augments Object3D
  18111. */
  18112. class LOD extends Object3D {
  18113. /**
  18114. * Constructs a new LOD.
  18115. */
  18116. constructor() {
  18117. super();
  18118. /**
  18119. * This flag can be used for type testing.
  18120. *
  18121. * @type {boolean}
  18122. * @readonly
  18123. * @default true
  18124. */
  18125. this.isLOD = true;
  18126. /**
  18127. * The current LOD index.
  18128. *
  18129. * @private
  18130. * @type {number}
  18131. * @default 0
  18132. */
  18133. this._currentLevel = 0;
  18134. this.type = 'LOD';
  18135. Object.defineProperties( this, {
  18136. /**
  18137. * This array holds the LOD levels.
  18138. *
  18139. * @name LOD#levels
  18140. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18141. */
  18142. levels: {
  18143. enumerable: true,
  18144. value: []
  18145. }
  18146. } );
  18147. /**
  18148. * Whether the LOD object is updated automatically by the renderer per frame
  18149. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18150. * render loop by yourself.
  18151. *
  18152. * @type {boolean}
  18153. * @default true
  18154. */
  18155. this.autoUpdate = true;
  18156. }
  18157. copy( source ) {
  18158. super.copy( source, false );
  18159. const levels = source.levels;
  18160. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18161. const level = levels[ i ];
  18162. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18163. }
  18164. this.autoUpdate = source.autoUpdate;
  18165. return this;
  18166. }
  18167. /**
  18168. * Adds a mesh that will display at a certain distance and greater. Typically
  18169. * the further away the distance, the lower the detail on the mesh.
  18170. *
  18171. * @param {Object3D} object - The 3D object to display at this level.
  18172. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18173. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18174. * @return {LOD} A reference to this instance.
  18175. */
  18176. addLevel( object, distance = 0, hysteresis = 0 ) {
  18177. distance = Math.abs( distance );
  18178. const levels = this.levels;
  18179. let l;
  18180. for ( l = 0; l < levels.length; l ++ ) {
  18181. if ( distance < levels[ l ].distance ) {
  18182. break;
  18183. }
  18184. }
  18185. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18186. this.add( object );
  18187. return this;
  18188. }
  18189. /**
  18190. * Removes an existing level, based on the distance from the camera.
  18191. * Returns `true` when the level has been removed. Otherwise `false`.
  18192. *
  18193. * @param {number} distance - Distance of the level to remove.
  18194. * @return {boolean} Whether the level has been removed or not.
  18195. */
  18196. removeLevel( distance ) {
  18197. const levels = this.levels;
  18198. for ( let i = 0; i < levels.length; i ++ ) {
  18199. if ( levels[ i ].distance === distance ) {
  18200. const removedElements = levels.splice( i, 1 );
  18201. this.remove( removedElements[ 0 ].object );
  18202. return true;
  18203. }
  18204. }
  18205. return false;
  18206. }
  18207. /**
  18208. * Returns the currently active LOD level index.
  18209. *
  18210. * @return {number} The current active LOD level index.
  18211. */
  18212. getCurrentLevel() {
  18213. return this._currentLevel;
  18214. }
  18215. /**
  18216. * Returns a reference to the first 3D object that is greater than
  18217. * the given distance.
  18218. *
  18219. * @param {number} distance - The LOD distance.
  18220. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  18221. */
  18222. getObjectForDistance( distance ) {
  18223. const levels = this.levels;
  18224. if ( levels.length > 0 ) {
  18225. let i, l;
  18226. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18227. let levelDistance = levels[ i ].distance;
  18228. if ( levels[ i ].object.visible ) {
  18229. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18230. }
  18231. if ( distance < levelDistance ) {
  18232. break;
  18233. }
  18234. }
  18235. return levels[ i - 1 ].object;
  18236. }
  18237. return null;
  18238. }
  18239. /**
  18240. * Computes intersection points between a casted ray and this LOD.
  18241. *
  18242. * @param {Raycaster} raycaster - The raycaster.
  18243. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18244. */
  18245. raycast( raycaster, intersects ) {
  18246. const levels = this.levels;
  18247. if ( levels.length > 0 ) {
  18248. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18249. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18250. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18251. }
  18252. }
  18253. /**
  18254. * Updates the LOD by computing which LOD level should be visible according
  18255. * to the current distance of the given camera.
  18256. *
  18257. * @param {Camera} camera - The camera the scene is rendered with.
  18258. */
  18259. update( camera ) {
  18260. const levels = this.levels;
  18261. if ( levels.length > 1 ) {
  18262. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18263. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18264. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18265. levels[ 0 ].object.visible = true;
  18266. let i, l;
  18267. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18268. let levelDistance = levels[ i ].distance;
  18269. if ( levels[ i ].object.visible ) {
  18270. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18271. }
  18272. if ( distance >= levelDistance ) {
  18273. levels[ i - 1 ].object.visible = false;
  18274. levels[ i ].object.visible = true;
  18275. } else {
  18276. break;
  18277. }
  18278. }
  18279. this._currentLevel = i - 1;
  18280. for ( ; i < l; i ++ ) {
  18281. levels[ i ].object.visible = false;
  18282. }
  18283. }
  18284. }
  18285. toJSON( meta ) {
  18286. const data = super.toJSON( meta );
  18287. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18288. data.object.levels = [];
  18289. const levels = this.levels;
  18290. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18291. const level = levels[ i ];
  18292. data.object.levels.push( {
  18293. object: level.object.uuid,
  18294. distance: level.distance,
  18295. hysteresis: level.hysteresis
  18296. } );
  18297. }
  18298. return data;
  18299. }
  18300. }
  18301. const _basePosition = /*@__PURE__*/ new Vector3();
  18302. const _skinIndex = /*@__PURE__*/ new Vector4();
  18303. const _skinWeight = /*@__PURE__*/ new Vector4();
  18304. const _vector3 = /*@__PURE__*/ new Vector3();
  18305. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18306. const _vertex = /*@__PURE__*/ new Vector3();
  18307. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18308. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18309. const _ray$2 = /*@__PURE__*/ new Ray();
  18310. /**
  18311. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18312. * vertices of the geometry with skinning/skeleton animation.
  18313. *
  18314. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18315. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18316. * vertex to a certain extend.
  18317. *
  18318. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18319. * or {@link FBXLoader } import respective models.
  18320. *
  18321. * @augments Mesh
  18322. */
  18323. class SkinnedMesh extends Mesh {
  18324. /**
  18325. * Constructs a new skinned mesh.
  18326. *
  18327. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18328. * @param {Material|Array<Material>} [material] - The mesh material.
  18329. */
  18330. constructor( geometry, material ) {
  18331. super( geometry, material );
  18332. /**
  18333. * This flag can be used for type testing.
  18334. *
  18335. * @type {boolean}
  18336. * @readonly
  18337. * @default true
  18338. */
  18339. this.isSkinnedMesh = true;
  18340. this.type = 'SkinnedMesh';
  18341. /**
  18342. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18343. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18344. * across multiple skinned meshes.
  18345. *
  18346. * @type {(AttachedBindMode|DetachedBindMode)}
  18347. * @default AttachedBindMode
  18348. */
  18349. this.bindMode = AttachedBindMode;
  18350. /**
  18351. * The base matrix that is used for the bound bone transforms.
  18352. *
  18353. * @type {Matrix4}
  18354. */
  18355. this.bindMatrix = new Matrix4();
  18356. /**
  18357. * The base matrix that is used for resetting the bound bone transforms.
  18358. *
  18359. * @type {Matrix4}
  18360. */
  18361. this.bindMatrixInverse = new Matrix4();
  18362. /**
  18363. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18364. *
  18365. * @type {?Box3}
  18366. * @default null
  18367. */
  18368. this.boundingBox = null;
  18369. /**
  18370. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18371. *
  18372. * @type {?Sphere}
  18373. * @default null
  18374. */
  18375. this.boundingSphere = null;
  18376. }
  18377. /**
  18378. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18379. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18380. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18381. * the current animation state.
  18382. */
  18383. computeBoundingBox() {
  18384. const geometry = this.geometry;
  18385. if ( this.boundingBox === null ) {
  18386. this.boundingBox = new Box3();
  18387. }
  18388. this.boundingBox.makeEmpty();
  18389. const positionAttribute = geometry.getAttribute( 'position' );
  18390. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18391. this.getVertexPosition( i, _vertex );
  18392. this.boundingBox.expandByPoint( _vertex );
  18393. }
  18394. }
  18395. /**
  18396. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18397. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18398. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18399. * per frame in order to reflect the current animation state.
  18400. */
  18401. computeBoundingSphere() {
  18402. const geometry = this.geometry;
  18403. if ( this.boundingSphere === null ) {
  18404. this.boundingSphere = new Sphere();
  18405. }
  18406. this.boundingSphere.makeEmpty();
  18407. const positionAttribute = geometry.getAttribute( 'position' );
  18408. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18409. this.getVertexPosition( i, _vertex );
  18410. this.boundingSphere.expandByPoint( _vertex );
  18411. }
  18412. }
  18413. copy( source, recursive ) {
  18414. super.copy( source, recursive );
  18415. this.bindMode = source.bindMode;
  18416. this.bindMatrix.copy( source.bindMatrix );
  18417. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18418. this.skeleton = source.skeleton;
  18419. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18420. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18421. return this;
  18422. }
  18423. raycast( raycaster, intersects ) {
  18424. const material = this.material;
  18425. const matrixWorld = this.matrixWorld;
  18426. if ( material === undefined ) return;
  18427. // test with bounding sphere in world space
  18428. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18429. _sphere$5.copy( this.boundingSphere );
  18430. _sphere$5.applyMatrix4( matrixWorld );
  18431. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18432. // convert ray to local space of skinned mesh
  18433. _inverseMatrix$2.copy( matrixWorld ).invert();
  18434. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18435. // test with bounding box in local space
  18436. if ( this.boundingBox !== null ) {
  18437. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18438. }
  18439. // test for intersections with geometry
  18440. this._computeIntersections( raycaster, intersects, _ray$2 );
  18441. }
  18442. getVertexPosition( index, target ) {
  18443. super.getVertexPosition( index, target );
  18444. this.applyBoneTransform( index, target );
  18445. return target;
  18446. }
  18447. /**
  18448. * Binds the given skeleton to the skinned mesh.
  18449. *
  18450. * @param {Skeleton} skeleton - The skeleton to bind.
  18451. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18452. * the skinned mesh's world matrix will be used instead.
  18453. */
  18454. bind( skeleton, bindMatrix ) {
  18455. this.skeleton = skeleton;
  18456. if ( bindMatrix === undefined ) {
  18457. this.updateMatrixWorld( true );
  18458. this.skeleton.calculateInverses();
  18459. bindMatrix = this.matrixWorld;
  18460. }
  18461. this.bindMatrix.copy( bindMatrix );
  18462. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18463. }
  18464. /**
  18465. * This method sets the skinned mesh in the rest pose).
  18466. */
  18467. pose() {
  18468. this.skeleton.pose();
  18469. }
  18470. /**
  18471. * Normalizes the skin weights which are defined as a buffer attribute
  18472. * in the skinned mesh's geometry.
  18473. */
  18474. normalizeSkinWeights() {
  18475. const vector = new Vector4();
  18476. const skinWeight = this.geometry.attributes.skinWeight;
  18477. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18478. vector.fromBufferAttribute( skinWeight, i );
  18479. const scale = 1.0 / vector.manhattanLength();
  18480. if ( scale !== Infinity ) {
  18481. vector.multiplyScalar( scale );
  18482. } else {
  18483. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18484. }
  18485. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18486. }
  18487. }
  18488. updateMatrixWorld( force ) {
  18489. super.updateMatrixWorld( force );
  18490. if ( this.bindMode === AttachedBindMode ) {
  18491. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18492. } else if ( this.bindMode === DetachedBindMode ) {
  18493. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18494. } else {
  18495. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18496. }
  18497. }
  18498. /**
  18499. * Applies the bone transform associated with the given index to the given
  18500. * vertex position. Returns the updated vector.
  18501. *
  18502. * @param {number} index - The vertex index.
  18503. * @param {Vector3} target - The target object that is used to store the method's result.
  18504. * the skinned mesh's world matrix will be used instead.
  18505. * @return {Vector3} The updated vertex position.
  18506. */
  18507. applyBoneTransform( index, target ) {
  18508. const skeleton = this.skeleton;
  18509. const geometry = this.geometry;
  18510. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18511. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18512. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18513. target.set( 0, 0, 0 );
  18514. for ( let i = 0; i < 4; i ++ ) {
  18515. const weight = _skinWeight.getComponent( i );
  18516. if ( weight !== 0 ) {
  18517. const boneIndex = _skinIndex.getComponent( i );
  18518. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18519. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18520. }
  18521. }
  18522. return target.applyMatrix4( this.bindMatrixInverse );
  18523. }
  18524. }
  18525. /**
  18526. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18527. * the {@link SkinnedMesh}.
  18528. *
  18529. * ```js
  18530. * const root = new THREE.Bone();
  18531. * const child = new THREE.Bone();
  18532. *
  18533. * root.add( child );
  18534. * child.position.y = 5;
  18535. * ```
  18536. *
  18537. * @augments Object3D
  18538. */
  18539. class Bone extends Object3D {
  18540. /**
  18541. * Constructs a new bone.
  18542. */
  18543. constructor() {
  18544. super();
  18545. /**
  18546. * This flag can be used for type testing.
  18547. *
  18548. * @type {boolean}
  18549. * @readonly
  18550. * @default true
  18551. */
  18552. this.isBone = true;
  18553. this.type = 'Bone';
  18554. }
  18555. }
  18556. /**
  18557. * Creates a texture directly from raw buffer data.
  18558. *
  18559. * The interpretation of the data depends on type and format: If the type is
  18560. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18561. * texel data. If the format is `RGBAFormat`, data needs four values for
  18562. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18563. *
  18564. * @augments Texture
  18565. */
  18566. class DataTexture extends Texture {
  18567. /**
  18568. * Constructs a new data texture.
  18569. *
  18570. * @param {?TypedArray} [data=null] - The buffer data.
  18571. * @param {number} [width=1] - The width of the texture.
  18572. * @param {number} [height=1] - The height of the texture.
  18573. * @param {number} [format=RGBAFormat] - The texture format.
  18574. * @param {number} [type=UnsignedByteType] - The texture type.
  18575. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18576. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18577. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18578. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18579. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18580. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18581. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18582. */
  18583. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18584. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18585. /**
  18586. * This flag can be used for type testing.
  18587. *
  18588. * @type {boolean}
  18589. * @readonly
  18590. * @default true
  18591. */
  18592. this.isDataTexture = true;
  18593. /**
  18594. * The image definition of a data texture.
  18595. *
  18596. * @type {{data:TypedArray,width:number,height:number}}
  18597. */
  18598. this.image = { data: data, width: width, height: height };
  18599. /**
  18600. * Whether to generate mipmaps (if possible) for a texture.
  18601. *
  18602. * Overwritten and set to `false` by default.
  18603. *
  18604. * @type {boolean}
  18605. * @default false
  18606. */
  18607. this.generateMipmaps = false;
  18608. /**
  18609. * If set to `true`, the texture is flipped along the vertical axis when
  18610. * uploaded to the GPU.
  18611. *
  18612. * Overwritten and set to `false` by default.
  18613. *
  18614. * @type {boolean}
  18615. * @default false
  18616. */
  18617. this.flipY = false;
  18618. /**
  18619. * Specifies the alignment requirements for the start of each pixel row in memory.
  18620. *
  18621. * Overwritten and set to `1` by default.
  18622. *
  18623. * @type {boolean}
  18624. * @default 1
  18625. */
  18626. this.unpackAlignment = 1;
  18627. }
  18628. }
  18629. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18630. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18631. /**
  18632. * Class for representing the armatures in `three.js`. The skeleton
  18633. * is defined by a hierarchy of bones.
  18634. *
  18635. * ```js
  18636. * const bones = [];
  18637. *
  18638. * const shoulder = new THREE.Bone();
  18639. * const elbow = new THREE.Bone();
  18640. * const hand = new THREE.Bone();
  18641. *
  18642. * shoulder.add( elbow );
  18643. * elbow.add( hand );
  18644. *
  18645. * bones.push( shoulder , elbow, hand);
  18646. *
  18647. * shoulder.position.y = -5;
  18648. * elbow.position.y = 0;
  18649. * hand.position.y = 5;
  18650. *
  18651. * const armSkeleton = new THREE.Skeleton( bones );
  18652. * ```
  18653. */
  18654. class Skeleton {
  18655. /**
  18656. * Constructs a new skeleton.
  18657. *
  18658. * @param {Array<Bone>} [bones] - An array of bones.
  18659. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18660. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18661. */
  18662. constructor( bones = [], boneInverses = [] ) {
  18663. this.uuid = generateUUID();
  18664. /**
  18665. * An array of bones defining the skeleton.
  18666. *
  18667. * @type {Array<Bone>}
  18668. */
  18669. this.bones = bones.slice( 0 );
  18670. /**
  18671. * An array of bone inverse matrices.
  18672. *
  18673. * @type {Array<Matrix4>}
  18674. */
  18675. this.boneInverses = boneInverses;
  18676. /**
  18677. * An array buffer holding the bone data.
  18678. * Input data for {@link Skeleton#boneTexture}.
  18679. *
  18680. * @type {?Float32Array}
  18681. * @default null
  18682. */
  18683. this.boneMatrices = null;
  18684. /**
  18685. * A texture holding the bone data for use
  18686. * in the vertex shader.
  18687. *
  18688. * @type {?DataTexture}
  18689. * @default null
  18690. */
  18691. this.boneTexture = null;
  18692. this.init();
  18693. }
  18694. /**
  18695. * Initializes the skeleton. This method gets automatically called by the constructor
  18696. * but depending on how the skeleton is created it might be necessary to call this method
  18697. * manually.
  18698. */
  18699. init() {
  18700. const bones = this.bones;
  18701. const boneInverses = this.boneInverses;
  18702. this.boneMatrices = new Float32Array( bones.length * 16 );
  18703. // calculate inverse bone matrices if necessary
  18704. if ( boneInverses.length === 0 ) {
  18705. this.calculateInverses();
  18706. } else {
  18707. // handle special case
  18708. if ( bones.length !== boneInverses.length ) {
  18709. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18710. this.boneInverses = [];
  18711. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18712. this.boneInverses.push( new Matrix4() );
  18713. }
  18714. }
  18715. }
  18716. }
  18717. /**
  18718. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18719. * and fills it with new matrices.
  18720. */
  18721. calculateInverses() {
  18722. this.boneInverses.length = 0;
  18723. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18724. const inverse = new Matrix4();
  18725. if ( this.bones[ i ] ) {
  18726. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18727. }
  18728. this.boneInverses.push( inverse );
  18729. }
  18730. }
  18731. /**
  18732. * Resets the skeleton to the base pose.
  18733. */
  18734. pose() {
  18735. // recover the bind-time world matrices
  18736. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18737. const bone = this.bones[ i ];
  18738. if ( bone ) {
  18739. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18740. }
  18741. }
  18742. // compute the local matrices, positions, rotations and scales
  18743. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18744. const bone = this.bones[ i ];
  18745. if ( bone ) {
  18746. if ( bone.parent && bone.parent.isBone ) {
  18747. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18748. bone.matrix.multiply( bone.matrixWorld );
  18749. } else {
  18750. bone.matrix.copy( bone.matrixWorld );
  18751. }
  18752. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18753. }
  18754. }
  18755. }
  18756. /**
  18757. * Resets the skeleton to the base pose.
  18758. */
  18759. update() {
  18760. const bones = this.bones;
  18761. const boneInverses = this.boneInverses;
  18762. const boneMatrices = this.boneMatrices;
  18763. const boneTexture = this.boneTexture;
  18764. // flatten bone matrices to array
  18765. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18766. // compute the offset between the current and the original transform
  18767. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18768. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18769. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18770. }
  18771. if ( boneTexture !== null ) {
  18772. boneTexture.needsUpdate = true;
  18773. }
  18774. }
  18775. /**
  18776. * Returns a new skeleton with copied values from this instance.
  18777. *
  18778. * @return {Skeleton} A clone of this instance.
  18779. */
  18780. clone() {
  18781. return new Skeleton( this.bones, this.boneInverses );
  18782. }
  18783. /**
  18784. * Computes a data texture for passing bone data to the vertex shader.
  18785. *
  18786. * @return {Skeleton} A reference of this instance.
  18787. */
  18788. computeBoneTexture() {
  18789. // layout (1 matrix = 4 pixels)
  18790. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18791. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18792. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18793. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18794. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18795. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18796. size = Math.ceil( size / 4 ) * 4;
  18797. size = Math.max( size, 4 );
  18798. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18799. boneMatrices.set( this.boneMatrices ); // copy current values
  18800. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18801. boneTexture.needsUpdate = true;
  18802. this.boneMatrices = boneMatrices;
  18803. this.boneTexture = boneTexture;
  18804. return this;
  18805. }
  18806. /**
  18807. * Searches through the skeleton's bone array and returns the first with a
  18808. * matching name.
  18809. *
  18810. * @param {string} name - The name of the bone.
  18811. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18812. */
  18813. getBoneByName( name ) {
  18814. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18815. const bone = this.bones[ i ];
  18816. if ( bone.name === name ) {
  18817. return bone;
  18818. }
  18819. }
  18820. return undefined;
  18821. }
  18822. /**
  18823. * Frees the GPU-related resources allocated by this instance. Call this
  18824. * method whenever this instance is no longer used in your app.
  18825. */
  18826. dispose( ) {
  18827. if ( this.boneTexture !== null ) {
  18828. this.boneTexture.dispose();
  18829. this.boneTexture = null;
  18830. }
  18831. }
  18832. /**
  18833. * Setups the skeleton by the given JSON and bones.
  18834. *
  18835. * @param {Object} json - The skeleton as serialized JSON.
  18836. * @param {Object<string, Bone>} bones - An array of bones.
  18837. * @return {Skeleton} A reference of this instance.
  18838. */
  18839. fromJSON( json, bones ) {
  18840. this.uuid = json.uuid;
  18841. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18842. const uuid = json.bones[ i ];
  18843. let bone = bones[ uuid ];
  18844. if ( bone === undefined ) {
  18845. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18846. bone = new Bone();
  18847. }
  18848. this.bones.push( bone );
  18849. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18850. }
  18851. this.init();
  18852. return this;
  18853. }
  18854. /**
  18855. * Serializes the skeleton into JSON.
  18856. *
  18857. * @return {Object} A JSON object representing the serialized skeleton.
  18858. * @see {@link ObjectLoader#parse}
  18859. */
  18860. toJSON() {
  18861. const data = {
  18862. metadata: {
  18863. version: 4.7,
  18864. type: 'Skeleton',
  18865. generator: 'Skeleton.toJSON'
  18866. },
  18867. bones: [],
  18868. boneInverses: []
  18869. };
  18870. data.uuid = this.uuid;
  18871. const bones = this.bones;
  18872. const boneInverses = this.boneInverses;
  18873. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18874. const bone = bones[ i ];
  18875. data.bones.push( bone.uuid );
  18876. const boneInverse = boneInverses[ i ];
  18877. data.boneInverses.push( boneInverse.toArray() );
  18878. }
  18879. return data;
  18880. }
  18881. }
  18882. /**
  18883. * An instanced version of a buffer attribute.
  18884. *
  18885. * @augments BufferAttribute
  18886. */
  18887. class InstancedBufferAttribute extends BufferAttribute {
  18888. /**
  18889. * Constructs a new instanced buffer attribute.
  18890. *
  18891. * @param {TypedArray} array - The array holding the attribute data.
  18892. * @param {number} itemSize - The item size.
  18893. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18894. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18895. */
  18896. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18897. super( array, itemSize, normalized );
  18898. /**
  18899. * This flag can be used for type testing.
  18900. *
  18901. * @type {boolean}
  18902. * @readonly
  18903. * @default true
  18904. */
  18905. this.isInstancedBufferAttribute = true;
  18906. /**
  18907. * Defines how often a value of this buffer attribute should be repeated. A
  18908. * value of one means that each value of the instanced attribute is used for
  18909. * a single instance. A value of two means that each value is used for two
  18910. * consecutive instances (and so on).
  18911. *
  18912. * @type {number}
  18913. * @default 1
  18914. */
  18915. this.meshPerAttribute = meshPerAttribute;
  18916. }
  18917. copy( source ) {
  18918. super.copy( source );
  18919. this.meshPerAttribute = source.meshPerAttribute;
  18920. return this;
  18921. }
  18922. toJSON() {
  18923. const data = super.toJSON();
  18924. data.meshPerAttribute = this.meshPerAttribute;
  18925. data.isInstancedBufferAttribute = true;
  18926. return data;
  18927. }
  18928. }
  18929. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18930. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18931. const _instanceIntersects = [];
  18932. const _box3 = /*@__PURE__*/ new Box3();
  18933. const _identity = /*@__PURE__*/ new Matrix4();
  18934. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18935. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18936. /**
  18937. * A special version of a mesh with instanced rendering support. Use
  18938. * this class if you have to render a large number of objects with the same
  18939. * geometry and material(s) but with different world transformations. The usage
  18940. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18941. * improve the overall rendering performance in your application.
  18942. *
  18943. * @augments Mesh
  18944. */
  18945. class InstancedMesh extends Mesh {
  18946. /**
  18947. * Constructs a new instanced mesh.
  18948. *
  18949. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18950. * @param {Material|Array<Material>} [material] - The mesh material.
  18951. * @param {number} count - The number of instances.
  18952. */
  18953. constructor( geometry, material, count ) {
  18954. super( geometry, material );
  18955. /**
  18956. * This flag can be used for type testing.
  18957. *
  18958. * @type {boolean}
  18959. * @readonly
  18960. * @default true
  18961. */
  18962. this.isInstancedMesh = true;
  18963. /**
  18964. * Represents the local transformation of all instances. You have to set its
  18965. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18966. * via {@link InstancedMesh#setMatrixAt}.
  18967. *
  18968. * @type {InstancedBufferAttribute}
  18969. */
  18970. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18971. /**
  18972. * Represents the color of all instances. You have to set its
  18973. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18974. * via {@link InstancedMesh#setColorAt}.
  18975. *
  18976. * @type {?InstancedBufferAttribute}
  18977. * @default null
  18978. */
  18979. this.instanceColor = null;
  18980. /**
  18981. * Represents the morph target weights of all instances. You have to set its
  18982. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18983. * via {@link InstancedMesh#setMorphAt}.
  18984. *
  18985. * @type {?DataTexture}
  18986. * @default null
  18987. */
  18988. this.morphTexture = null;
  18989. /**
  18990. * The number of instances.
  18991. *
  18992. * @type {number}
  18993. */
  18994. this.count = count;
  18995. /**
  18996. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18997. *
  18998. * @type {?Box3}
  18999. * @default null
  19000. */
  19001. this.boundingBox = null;
  19002. /**
  19003. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19004. *
  19005. * @type {?Sphere}
  19006. * @default null
  19007. */
  19008. this.boundingSphere = null;
  19009. for ( let i = 0; i < count; i ++ ) {
  19010. this.setMatrixAt( i, _identity );
  19011. }
  19012. }
  19013. /**
  19014. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19015. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19016. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19017. */
  19018. computeBoundingBox() {
  19019. const geometry = this.geometry;
  19020. const count = this.count;
  19021. if ( this.boundingBox === null ) {
  19022. this.boundingBox = new Box3();
  19023. }
  19024. if ( geometry.boundingBox === null ) {
  19025. geometry.computeBoundingBox();
  19026. }
  19027. this.boundingBox.makeEmpty();
  19028. for ( let i = 0; i < count; i ++ ) {
  19029. this.getMatrixAt( i, _instanceLocalMatrix );
  19030. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19031. this.boundingBox.union( _box3 );
  19032. }
  19033. }
  19034. /**
  19035. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19036. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19037. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19038. */
  19039. computeBoundingSphere() {
  19040. const geometry = this.geometry;
  19041. const count = this.count;
  19042. if ( this.boundingSphere === null ) {
  19043. this.boundingSphere = new Sphere();
  19044. }
  19045. if ( geometry.boundingSphere === null ) {
  19046. geometry.computeBoundingSphere();
  19047. }
  19048. this.boundingSphere.makeEmpty();
  19049. for ( let i = 0; i < count; i ++ ) {
  19050. this.getMatrixAt( i, _instanceLocalMatrix );
  19051. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19052. this.boundingSphere.union( _sphere$4 );
  19053. }
  19054. }
  19055. copy( source, recursive ) {
  19056. super.copy( source, recursive );
  19057. this.instanceMatrix.copy( source.instanceMatrix );
  19058. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19059. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19060. this.count = source.count;
  19061. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19062. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19063. return this;
  19064. }
  19065. /**
  19066. * Gets the color of the defined instance.
  19067. *
  19068. * @param {number} index - The instance index.
  19069. * @param {Color} color - The target object that is used to store the method's result.
  19070. */
  19071. getColorAt( index, color ) {
  19072. color.fromArray( this.instanceColor.array, index * 3 );
  19073. }
  19074. /**
  19075. * Gets the local transformation matrix of the defined instance.
  19076. *
  19077. * @param {number} index - The instance index.
  19078. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19079. */
  19080. getMatrixAt( index, matrix ) {
  19081. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19082. }
  19083. /**
  19084. * Gets the morph target weights of the defined instance.
  19085. *
  19086. * @param {number} index - The instance index.
  19087. * @param {Mesh} object - The target object that is used to store the method's result.
  19088. */
  19089. getMorphAt( index, object ) {
  19090. const objectInfluences = object.morphTargetInfluences;
  19091. const array = this.morphTexture.source.data.data;
  19092. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19093. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19094. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19095. objectInfluences[ i ] = array[ dataIndex + i ];
  19096. }
  19097. }
  19098. raycast( raycaster, intersects ) {
  19099. const matrixWorld = this.matrixWorld;
  19100. const raycastTimes = this.count;
  19101. _mesh$1.geometry = this.geometry;
  19102. _mesh$1.material = this.material;
  19103. if ( _mesh$1.material === undefined ) return;
  19104. // test with bounding sphere first
  19105. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19106. _sphere$4.copy( this.boundingSphere );
  19107. _sphere$4.applyMatrix4( matrixWorld );
  19108. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19109. // now test each instance
  19110. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19111. // calculate the world matrix for each instance
  19112. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19113. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19114. // the mesh represents this single instance
  19115. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19116. _mesh$1.raycast( raycaster, _instanceIntersects );
  19117. // process the result of raycast
  19118. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19119. const intersect = _instanceIntersects[ i ];
  19120. intersect.instanceId = instanceId;
  19121. intersect.object = this;
  19122. intersects.push( intersect );
  19123. }
  19124. _instanceIntersects.length = 0;
  19125. }
  19126. }
  19127. /**
  19128. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19129. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19130. *
  19131. * @param {number} index - The instance index.
  19132. * @param {Color} color - The instance color.
  19133. */
  19134. setColorAt( index, color ) {
  19135. if ( this.instanceColor === null ) {
  19136. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19137. }
  19138. color.toArray( this.instanceColor.array, index * 3 );
  19139. }
  19140. /**
  19141. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19142. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19143. *
  19144. * @param {number} index - The instance index.
  19145. * @param {Matrix4} matrix - The local transformation.
  19146. */
  19147. setMatrixAt( index, matrix ) {
  19148. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19149. }
  19150. /**
  19151. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19152. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19153. *
  19154. * @param {number} index - The instance index.
  19155. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19156. * of a single instance.
  19157. */
  19158. setMorphAt( index, object ) {
  19159. const objectInfluences = object.morphTargetInfluences;
  19160. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19161. if ( this.morphTexture === null ) {
  19162. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19163. }
  19164. const array = this.morphTexture.source.data.data;
  19165. let morphInfluencesSum = 0;
  19166. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19167. morphInfluencesSum += objectInfluences[ i ];
  19168. }
  19169. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19170. const dataIndex = len * index;
  19171. array[ dataIndex ] = morphBaseInfluence;
  19172. array.set( objectInfluences, dataIndex + 1 );
  19173. }
  19174. updateMorphTargets() {
  19175. }
  19176. /**
  19177. * Frees the GPU-related resources allocated by this instance. Call this
  19178. * method whenever this instance is no longer used in your app.
  19179. */
  19180. dispose() {
  19181. this.dispatchEvent( { type: 'dispose' } );
  19182. if ( this.morphTexture !== null ) {
  19183. this.morphTexture.dispose();
  19184. this.morphTexture = null;
  19185. }
  19186. }
  19187. }
  19188. const _vector1 = /*@__PURE__*/ new Vector3();
  19189. const _vector2 = /*@__PURE__*/ new Vector3();
  19190. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19191. /**
  19192. * A two dimensional surface that extends infinitely in 3D space, represented
  19193. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  19194. * by a unit length normal vector and a constant.
  19195. */
  19196. class Plane {
  19197. /**
  19198. * Constructs a new plane.
  19199. *
  19200. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19201. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19202. */
  19203. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19204. /**
  19205. * This flag can be used for type testing.
  19206. *
  19207. * @type {boolean}
  19208. * @readonly
  19209. * @default true
  19210. */
  19211. this.isPlane = true;
  19212. /**
  19213. * A unit length vector defining the normal of the plane.
  19214. *
  19215. * @type {Vector3}
  19216. */
  19217. this.normal = normal;
  19218. /**
  19219. * The signed distance from the origin to the plane.
  19220. *
  19221. * @type {number}
  19222. * @default 0
  19223. */
  19224. this.constant = constant;
  19225. }
  19226. /**
  19227. * Sets the plane components by copying the given values.
  19228. *
  19229. * @param {Vector3} normal - The normal.
  19230. * @param {number} constant - The constant.
  19231. * @return {Plane} A reference to this plane.
  19232. */
  19233. set( normal, constant ) {
  19234. this.normal.copy( normal );
  19235. this.constant = constant;
  19236. return this;
  19237. }
  19238. /**
  19239. * Sets the plane components by defining `x`, `y`, `z` as the
  19240. * plane normal and `w` as the constant.
  19241. *
  19242. * @param {number} x - The value for the normal's x component.
  19243. * @param {number} y - The value for the normal's y component.
  19244. * @param {number} z - The value for the normal's z component.
  19245. * @param {number} w - The constant value.
  19246. * @return {Plane} A reference to this plane.
  19247. */
  19248. setComponents( x, y, z, w ) {
  19249. this.normal.set( x, y, z );
  19250. this.constant = w;
  19251. return this;
  19252. }
  19253. /**
  19254. * Sets the plane from the given normal and coplanar point (that is a point
  19255. * that lies onto the plane).
  19256. *
  19257. * @param {Vector3} normal - The normal.
  19258. * @param {Vector3} point - A coplanar point.
  19259. * @return {Plane} A reference to this plane.
  19260. */
  19261. setFromNormalAndCoplanarPoint( normal, point ) {
  19262. this.normal.copy( normal );
  19263. this.constant = - point.dot( this.normal );
  19264. return this;
  19265. }
  19266. /**
  19267. * Sets the plane from three coplanar points. The winding order is
  19268. * assumed to be counter-clockwise, and determines the direction of
  19269. * the plane normal.
  19270. *
  19271. * @param {Vector3} a - The first coplanar point.
  19272. * @param {Vector3} b - The second coplanar point.
  19273. * @param {Vector3} c - The third coplanar point.
  19274. * @return {Plane} A reference to this plane.
  19275. */
  19276. setFromCoplanarPoints( a, b, c ) {
  19277. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19278. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19279. this.setFromNormalAndCoplanarPoint( normal, a );
  19280. return this;
  19281. }
  19282. /**
  19283. * Copies the values of the given plane to this instance.
  19284. *
  19285. * @param {Plane} plane - The plane to copy.
  19286. * @return {Plane} A reference to this plane.
  19287. */
  19288. copy( plane ) {
  19289. this.normal.copy( plane.normal );
  19290. this.constant = plane.constant;
  19291. return this;
  19292. }
  19293. /**
  19294. * Normalizes the plane normal and adjusts the constant accordingly.
  19295. *
  19296. * @return {Plane} A reference to this plane.
  19297. */
  19298. normalize() {
  19299. // Note: will lead to a divide by zero if the plane is invalid.
  19300. const inverseNormalLength = 1.0 / this.normal.length();
  19301. this.normal.multiplyScalar( inverseNormalLength );
  19302. this.constant *= inverseNormalLength;
  19303. return this;
  19304. }
  19305. /**
  19306. * Negates both the plane normal and the constant.
  19307. *
  19308. * @return {Plane} A reference to this plane.
  19309. */
  19310. negate() {
  19311. this.constant *= -1;
  19312. this.normal.negate();
  19313. return this;
  19314. }
  19315. /**
  19316. * Returns the signed distance from the given point to this plane.
  19317. *
  19318. * @param {Vector3} point - The point to compute the distance for.
  19319. * @return {number} The signed distance.
  19320. */
  19321. distanceToPoint( point ) {
  19322. return this.normal.dot( point ) + this.constant;
  19323. }
  19324. /**
  19325. * Returns the signed distance from the given sphere to this plane.
  19326. *
  19327. * @param {Sphere} sphere - The sphere to compute the distance for.
  19328. * @return {number} The signed distance.
  19329. */
  19330. distanceToSphere( sphere ) {
  19331. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19332. }
  19333. /**
  19334. * Projects a the given point onto the plane.
  19335. *
  19336. * @param {Vector3} point - The point to project.
  19337. * @param {Vector3} target - The target vector that is used to store the method's result.
  19338. * @return {Vector3} The projected point on the plane.
  19339. */
  19340. projectPoint( point, target ) {
  19341. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19342. }
  19343. /**
  19344. * Returns the intersection point of the passed line and the plane. Returns
  19345. * `null` if the line does not intersect. Returns the line's starting point if
  19346. * the line is coplanar with the plane.
  19347. *
  19348. * @param {Line3} line - The line to compute the intersection for.
  19349. * @param {Vector3} target - The target vector that is used to store the method's result.
  19350. * @return {?Vector3} The intersection point.
  19351. */
  19352. intersectLine( line, target ) {
  19353. const direction = line.delta( _vector1 );
  19354. const denominator = this.normal.dot( direction );
  19355. if ( denominator === 0 ) {
  19356. // line is coplanar, return origin
  19357. if ( this.distanceToPoint( line.start ) === 0 ) {
  19358. return target.copy( line.start );
  19359. }
  19360. // Unsure if this is the correct method to handle this case.
  19361. return null;
  19362. }
  19363. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19364. if ( t < 0 || t > 1 ) {
  19365. return null;
  19366. }
  19367. return target.copy( line.start ).addScaledVector( direction, t );
  19368. }
  19369. /**
  19370. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19371. *
  19372. * @param {Line3} line - The line to test.
  19373. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19374. */
  19375. intersectsLine( line ) {
  19376. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19377. const startSign = this.distanceToPoint( line.start );
  19378. const endSign = this.distanceToPoint( line.end );
  19379. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19380. }
  19381. /**
  19382. * Returns `true` if the given bounding box intersects with the plane.
  19383. *
  19384. * @param {Box3} box - The bounding box to test.
  19385. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19386. */
  19387. intersectsBox( box ) {
  19388. return box.intersectsPlane( this );
  19389. }
  19390. /**
  19391. * Returns `true` if the given bounding sphere intersects with the plane.
  19392. *
  19393. * @param {Sphere} sphere - The bounding sphere to test.
  19394. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19395. */
  19396. intersectsSphere( sphere ) {
  19397. return sphere.intersectsPlane( this );
  19398. }
  19399. /**
  19400. * Returns a coplanar vector to the plane, by calculating the
  19401. * projection of the normal at the origin onto the plane.
  19402. *
  19403. * @param {Vector3} target - The target vector that is used to store the method's result.
  19404. * @return {Vector3} The coplanar point.
  19405. */
  19406. coplanarPoint( target ) {
  19407. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19408. }
  19409. /**
  19410. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19411. *
  19412. * The optional normal matrix can be pre-computed like so:
  19413. * ```js
  19414. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19415. * ```
  19416. *
  19417. * @param {Matrix4} matrix - The transformation matrix.
  19418. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19419. * @return {Plane} A reference to this plane.
  19420. */
  19421. applyMatrix4( matrix, optionalNormalMatrix ) {
  19422. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19423. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19424. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19425. this.constant = - referencePoint.dot( normal );
  19426. return this;
  19427. }
  19428. /**
  19429. * Translates the plane by the distance defined by the given offset vector.
  19430. * Note that this only affects the plane constant and will not affect the normal vector.
  19431. *
  19432. * @param {Vector3} offset - The offset vector.
  19433. * @return {Plane} A reference to this plane.
  19434. */
  19435. translate( offset ) {
  19436. this.constant -= offset.dot( this.normal );
  19437. return this;
  19438. }
  19439. /**
  19440. * Returns `true` if this plane is equal with the given one.
  19441. *
  19442. * @param {Plane} plane - The plane to test for equality.
  19443. * @return {boolean} Whether this plane is equal with the given one.
  19444. */
  19445. equals( plane ) {
  19446. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19447. }
  19448. /**
  19449. * Returns a new plane with copied values from this instance.
  19450. *
  19451. * @return {Plane} A clone of this instance.
  19452. */
  19453. clone() {
  19454. return new this.constructor().copy( this );
  19455. }
  19456. }
  19457. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19458. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19459. const _vector$6 = /*@__PURE__*/ new Vector3();
  19460. /**
  19461. * Frustums are used to determine what is inside the camera's field of view.
  19462. * They help speed up the rendering process - objects which lie outside a camera's
  19463. * frustum can safely be excluded from rendering.
  19464. *
  19465. * This class is mainly intended for use internally by a renderer.
  19466. */
  19467. class Frustum {
  19468. /**
  19469. * Constructs a new frustum.
  19470. *
  19471. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19472. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19473. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19474. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19475. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19476. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19477. */
  19478. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19479. /**
  19480. * This array holds the planes that enclose the frustum.
  19481. *
  19482. * @type {Array<Plane>}
  19483. */
  19484. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19485. }
  19486. /**
  19487. * Sets the frustum planes by copying the given planes.
  19488. *
  19489. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19490. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19491. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19492. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19493. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19494. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19495. * @return {Frustum} A reference to this frustum.
  19496. */
  19497. set( p0, p1, p2, p3, p4, p5 ) {
  19498. const planes = this.planes;
  19499. planes[ 0 ].copy( p0 );
  19500. planes[ 1 ].copy( p1 );
  19501. planes[ 2 ].copy( p2 );
  19502. planes[ 3 ].copy( p3 );
  19503. planes[ 4 ].copy( p4 );
  19504. planes[ 5 ].copy( p5 );
  19505. return this;
  19506. }
  19507. /**
  19508. * Copies the values of the given frustum to this instance.
  19509. *
  19510. * @param {Frustum} frustum - The frustum to copy.
  19511. * @return {Frustum} A reference to this frustum.
  19512. */
  19513. copy( frustum ) {
  19514. const planes = this.planes;
  19515. for ( let i = 0; i < 6; i ++ ) {
  19516. planes[ i ].copy( frustum.planes[ i ] );
  19517. }
  19518. return this;
  19519. }
  19520. /**
  19521. * Sets the frustum planes from the given projection matrix.
  19522. *
  19523. * @param {Matrix4} m - The projection matrix.
  19524. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19525. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19526. * @return {Frustum} A reference to this frustum.
  19527. */
  19528. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19529. const planes = this.planes;
  19530. const me = m.elements;
  19531. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19532. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19533. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19534. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19535. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19536. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19537. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19538. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19539. if ( reversedDepth ) {
  19540. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19541. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19542. } else {
  19543. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19544. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19545. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19546. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19547. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19548. } else {
  19549. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19550. }
  19551. }
  19552. return this;
  19553. }
  19554. /**
  19555. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19556. *
  19557. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19558. *
  19559. * @param {Object3D} object - The 3D object to test.
  19560. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19561. */
  19562. intersectsObject( object ) {
  19563. if ( object.boundingSphere !== undefined ) {
  19564. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19565. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19566. } else {
  19567. const geometry = object.geometry;
  19568. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19569. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19570. }
  19571. return this.intersectsSphere( _sphere$3 );
  19572. }
  19573. /**
  19574. * Returns `true` if the given sprite is intersecting this frustum.
  19575. *
  19576. * @param {Sprite} sprite - The sprite to test.
  19577. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19578. */
  19579. intersectsSprite( sprite ) {
  19580. _sphere$3.center.set( 0, 0, 0 );
  19581. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19582. _sphere$3.radius = 0.7071067811865476 + offset;
  19583. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19584. return this.intersectsSphere( _sphere$3 );
  19585. }
  19586. /**
  19587. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19588. *
  19589. * @param {Sphere} sphere - The bounding sphere to test.
  19590. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19591. */
  19592. intersectsSphere( sphere ) {
  19593. const planes = this.planes;
  19594. const center = sphere.center;
  19595. const negRadius = - sphere.radius;
  19596. for ( let i = 0; i < 6; i ++ ) {
  19597. const distance = planes[ i ].distanceToPoint( center );
  19598. if ( distance < negRadius ) {
  19599. return false;
  19600. }
  19601. }
  19602. return true;
  19603. }
  19604. /**
  19605. * Returns `true` if the given bounding box is intersecting this frustum.
  19606. *
  19607. * @param {Box3} box - The bounding box to test.
  19608. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19609. */
  19610. intersectsBox( box ) {
  19611. const planes = this.planes;
  19612. for ( let i = 0; i < 6; i ++ ) {
  19613. const plane = planes[ i ];
  19614. // corner at max distance
  19615. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19616. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19617. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19618. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19619. return false;
  19620. }
  19621. }
  19622. return true;
  19623. }
  19624. /**
  19625. * Returns `true` if the given point lies within the frustum.
  19626. *
  19627. * @param {Vector3} point - The point to test.
  19628. * @return {boolean} Whether the point lies within this frustum or not.
  19629. */
  19630. containsPoint( point ) {
  19631. const planes = this.planes;
  19632. for ( let i = 0; i < 6; i ++ ) {
  19633. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19634. return false;
  19635. }
  19636. }
  19637. return true;
  19638. }
  19639. /**
  19640. * Returns a new frustum with copied values from this instance.
  19641. *
  19642. * @return {Frustum} A clone of this instance.
  19643. */
  19644. clone() {
  19645. return new this.constructor().copy( this );
  19646. }
  19647. }
  19648. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19649. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19650. /**
  19651. * FrustumArray is used to determine if an object is visible in at least one camera
  19652. * from an array of cameras. This is particularly useful for multi-view renderers.
  19653. */
  19654. class FrustumArray {
  19655. /**
  19656. * Constructs a new frustum array.
  19657. *
  19658. */
  19659. constructor() {
  19660. /**
  19661. * The coordinate system to use.
  19662. *
  19663. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19664. * @default WebGLCoordinateSystem
  19665. */
  19666. this.coordinateSystem = WebGLCoordinateSystem;
  19667. }
  19668. /**
  19669. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19670. * from the camera array.
  19671. *
  19672. * @param {Object3D} object - The 3D object to test.
  19673. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19674. * @return {boolean} Whether the 3D object is visible in any camera.
  19675. */
  19676. intersectsObject( object, cameraArray ) {
  19677. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19678. return false;
  19679. }
  19680. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19681. const camera = cameraArray.cameras[ i ];
  19682. _projScreenMatrix$2.multiplyMatrices(
  19683. camera.projectionMatrix,
  19684. camera.matrixWorldInverse
  19685. );
  19686. _frustum$1.setFromProjectionMatrix(
  19687. _projScreenMatrix$2,
  19688. camera.coordinateSystem,
  19689. camera.reversedDepth
  19690. );
  19691. if ( _frustum$1.intersectsObject( object ) ) {
  19692. return true; // Object is visible in at least one camera
  19693. }
  19694. }
  19695. return false; // Not visible in any camera
  19696. }
  19697. /**
  19698. * Returns `true` if the given sprite is intersecting any frustum
  19699. * from the camera array.
  19700. *
  19701. * @param {Sprite} sprite - The sprite to test.
  19702. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19703. * @return {boolean} Whether the sprite is visible in any camera.
  19704. */
  19705. intersectsSprite( sprite, cameraArray ) {
  19706. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19707. return false;
  19708. }
  19709. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19710. const camera = cameraArray.cameras[ i ];
  19711. _projScreenMatrix$2.multiplyMatrices(
  19712. camera.projectionMatrix,
  19713. camera.matrixWorldInverse
  19714. );
  19715. _frustum$1.setFromProjectionMatrix(
  19716. _projScreenMatrix$2,
  19717. camera.coordinateSystem,
  19718. camera.reversedDepth
  19719. );
  19720. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19721. return true; // Sprite is visible in at least one camera
  19722. }
  19723. }
  19724. return false; // Not visible in any camera
  19725. }
  19726. /**
  19727. * Returns `true` if the given bounding sphere is intersecting any frustum
  19728. * from the camera array.
  19729. *
  19730. * @param {Sphere} sphere - The bounding sphere to test.
  19731. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19732. * @return {boolean} Whether the sphere is visible in any camera.
  19733. */
  19734. intersectsSphere( sphere, cameraArray ) {
  19735. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19736. return false;
  19737. }
  19738. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19739. const camera = cameraArray.cameras[ i ];
  19740. _projScreenMatrix$2.multiplyMatrices(
  19741. camera.projectionMatrix,
  19742. camera.matrixWorldInverse
  19743. );
  19744. _frustum$1.setFromProjectionMatrix(
  19745. _projScreenMatrix$2,
  19746. camera.coordinateSystem,
  19747. camera.reversedDepth
  19748. );
  19749. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19750. return true; // Sphere is visible in at least one camera
  19751. }
  19752. }
  19753. return false; // Not visible in any camera
  19754. }
  19755. /**
  19756. * Returns `true` if the given bounding box is intersecting any frustum
  19757. * from the camera array.
  19758. *
  19759. * @param {Box3} box - The bounding box to test.
  19760. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19761. * @return {boolean} Whether the box is visible in any camera.
  19762. */
  19763. intersectsBox( box, cameraArray ) {
  19764. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19765. return false;
  19766. }
  19767. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19768. const camera = cameraArray.cameras[ i ];
  19769. _projScreenMatrix$2.multiplyMatrices(
  19770. camera.projectionMatrix,
  19771. camera.matrixWorldInverse
  19772. );
  19773. _frustum$1.setFromProjectionMatrix(
  19774. _projScreenMatrix$2,
  19775. camera.coordinateSystem,
  19776. camera.reversedDepth
  19777. );
  19778. if ( _frustum$1.intersectsBox( box ) ) {
  19779. return true; // Box is visible in at least one camera
  19780. }
  19781. }
  19782. return false; // Not visible in any camera
  19783. }
  19784. /**
  19785. * Returns `true` if the given point lies within any frustum
  19786. * from the camera array.
  19787. *
  19788. * @param {Vector3} point - The point to test.
  19789. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19790. * @return {boolean} Whether the point is visible in any camera.
  19791. */
  19792. containsPoint( point, cameraArray ) {
  19793. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19794. return false;
  19795. }
  19796. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19797. const camera = cameraArray.cameras[ i ];
  19798. _projScreenMatrix$2.multiplyMatrices(
  19799. camera.projectionMatrix,
  19800. camera.matrixWorldInverse
  19801. );
  19802. _frustum$1.setFromProjectionMatrix(
  19803. _projScreenMatrix$2,
  19804. camera.coordinateSystem,
  19805. camera.reversedDepth
  19806. );
  19807. if ( _frustum$1.containsPoint( point ) ) {
  19808. return true; // Point is visible in at least one camera
  19809. }
  19810. }
  19811. return false; // Not visible in any camera
  19812. }
  19813. /**
  19814. * Returns a new frustum array with copied values from this instance.
  19815. *
  19816. * @return {FrustumArray} A clone of this instance.
  19817. */
  19818. clone() {
  19819. return new FrustumArray();
  19820. }
  19821. }
  19822. function ascIdSort( a, b ) {
  19823. return a - b;
  19824. }
  19825. function sortOpaque( a, b ) {
  19826. return a.z - b.z;
  19827. }
  19828. function sortTransparent( a, b ) {
  19829. return b.z - a.z;
  19830. }
  19831. class MultiDrawRenderList {
  19832. constructor() {
  19833. this.index = 0;
  19834. this.pool = [];
  19835. this.list = [];
  19836. }
  19837. push( start, count, z, index ) {
  19838. const pool = this.pool;
  19839. const list = this.list;
  19840. if ( this.index >= pool.length ) {
  19841. pool.push( {
  19842. start: -1,
  19843. count: -1,
  19844. z: -1,
  19845. index: -1,
  19846. } );
  19847. }
  19848. const item = pool[ this.index ];
  19849. list.push( item );
  19850. this.index ++;
  19851. item.start = start;
  19852. item.count = count;
  19853. item.z = z;
  19854. item.index = index;
  19855. }
  19856. reset() {
  19857. this.list.length = 0;
  19858. this.index = 0;
  19859. }
  19860. }
  19861. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19862. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19863. const _frustum = /*@__PURE__*/ new Frustum();
  19864. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19865. const _box$1 = /*@__PURE__*/ new Box3();
  19866. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19867. const _vector$5 = /*@__PURE__*/ new Vector3();
  19868. const _forward$1 = /*@__PURE__*/ new Vector3();
  19869. const _temp = /*@__PURE__*/ new Vector3();
  19870. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19871. const _mesh = /*@__PURE__*/ new Mesh();
  19872. const _batchIntersects = [];
  19873. // copies data from attribute "src" into "target" starting at "targetOffset"
  19874. function copyAttributeData( src, target, targetOffset = 0 ) {
  19875. const itemSize = target.itemSize;
  19876. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19877. // use the component getters and setters if the array data cannot
  19878. // be copied directly
  19879. const vertexCount = src.count;
  19880. for ( let i = 0; i < vertexCount; i ++ ) {
  19881. for ( let c = 0; c < itemSize; c ++ ) {
  19882. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19883. }
  19884. }
  19885. } else {
  19886. // faster copy approach using typed array set function
  19887. target.array.set( src.array, targetOffset * itemSize );
  19888. }
  19889. target.needsUpdate = true;
  19890. }
  19891. // safely copies array contents to a potentially smaller array
  19892. function copyArrayContents( src, target ) {
  19893. if ( src.constructor !== target.constructor ) {
  19894. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19895. const len = Math.min( src.length, target.length );
  19896. for ( let i = 0; i < len; i ++ ) {
  19897. target[ i ] = src[ i ];
  19898. }
  19899. } else {
  19900. // if the arrays use the same data layout we can use a fast block copy
  19901. const len = Math.min( src.length, target.length );
  19902. target.set( new src.constructor( src.buffer, 0, len ) );
  19903. }
  19904. }
  19905. /**
  19906. * A special version of a mesh with multi draw batch rendering support. Use
  19907. * this class if you have to render a large number of objects with the same
  19908. * material but with different geometries or world transformations. The usage of
  19909. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19910. * rendering performance in your application.
  19911. *
  19912. * ```js
  19913. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19914. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19915. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19916. *
  19917. * // initialize and add geometries into the batched mesh
  19918. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19919. * const boxGeometryId = batchedMesh.addGeometry( box );
  19920. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19921. *
  19922. * // create instances of those geometries
  19923. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19924. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19925. *
  19926. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19927. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19928. *
  19929. * // position the geometries
  19930. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19931. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19932. *
  19933. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19934. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19935. *
  19936. * scene.add( batchedMesh );
  19937. * ```
  19938. *
  19939. * @augments Mesh
  19940. */
  19941. class BatchedMesh extends Mesh {
  19942. /**
  19943. * Constructs a new batched mesh.
  19944. *
  19945. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19946. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19947. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19948. * @param {Material|Array<Material>} [material] - The mesh material.
  19949. */
  19950. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19951. super( new BufferGeometry(), material );
  19952. /**
  19953. * This flag can be used for type testing.
  19954. *
  19955. * @type {boolean}
  19956. * @readonly
  19957. * @default true
  19958. */
  19959. this.isBatchedMesh = true;
  19960. /**
  19961. * When set ot `true`, the individual objects of a batch are frustum culled.
  19962. *
  19963. * @type {boolean}
  19964. * @default true
  19965. */
  19966. this.perObjectFrustumCulled = true;
  19967. /**
  19968. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19969. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19970. * rendered front to back.
  19971. *
  19972. * @type {boolean}
  19973. * @default true
  19974. */
  19975. this.sortObjects = true;
  19976. /**
  19977. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19978. *
  19979. * @type {?Box3}
  19980. * @default null
  19981. */
  19982. this.boundingBox = null;
  19983. /**
  19984. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19985. *
  19986. * @type {?Sphere}
  19987. * @default null
  19988. */
  19989. this.boundingSphere = null;
  19990. /**
  19991. * Takes a sort a function that is run before render. The function takes a list of instances to
  19992. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19993. * sort with.
  19994. *
  19995. * @type {?Function}
  19996. * @default null
  19997. */
  19998. this.customSort = null;
  19999. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20000. this._instanceInfo = [];
  20001. this._geometryInfo = [];
  20002. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20003. this._availableInstanceIds = [];
  20004. this._availableGeometryIds = [];
  20005. // used to track where the next point is that geometry should be inserted
  20006. this._nextIndexStart = 0;
  20007. this._nextVertexStart = 0;
  20008. this._geometryCount = 0;
  20009. // flags
  20010. this._visibilityChanged = true;
  20011. this._geometryInitialized = false;
  20012. // cached user options
  20013. this._maxInstanceCount = maxInstanceCount;
  20014. this._maxVertexCount = maxVertexCount;
  20015. this._maxIndexCount = maxIndexCount;
  20016. // buffers for multi draw
  20017. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20018. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20019. this._multiDrawCount = 0;
  20020. this._multiDrawInstances = null;
  20021. // Local matrix per geometry by using data texture
  20022. this._matricesTexture = null;
  20023. this._indirectTexture = null;
  20024. this._colorsTexture = null;
  20025. this._initMatricesTexture();
  20026. this._initIndirectTexture();
  20027. }
  20028. /**
  20029. * The maximum number of individual instances that can be stored in the batch.
  20030. *
  20031. * @type {number}
  20032. * @readonly
  20033. */
  20034. get maxInstanceCount() {
  20035. return this._maxInstanceCount;
  20036. }
  20037. /**
  20038. * The instance count.
  20039. *
  20040. * @type {number}
  20041. * @readonly
  20042. */
  20043. get instanceCount() {
  20044. return this._instanceInfo.length - this._availableInstanceIds.length;
  20045. }
  20046. /**
  20047. * The number of unused vertices.
  20048. *
  20049. * @type {number}
  20050. * @readonly
  20051. */
  20052. get unusedVertexCount() {
  20053. return this._maxVertexCount - this._nextVertexStart;
  20054. }
  20055. /**
  20056. * The number of unused indices.
  20057. *
  20058. * @type {number}
  20059. * @readonly
  20060. */
  20061. get unusedIndexCount() {
  20062. return this._maxIndexCount - this._nextIndexStart;
  20063. }
  20064. _initMatricesTexture() {
  20065. // layout (1 matrix = 4 pixels)
  20066. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20067. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20068. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20069. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20070. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20071. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20072. size = Math.ceil( size / 4 ) * 4;
  20073. size = Math.max( size, 4 );
  20074. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20075. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20076. this._matricesTexture = matricesTexture;
  20077. }
  20078. _initIndirectTexture() {
  20079. let size = Math.sqrt( this._maxInstanceCount );
  20080. size = Math.ceil( size );
  20081. const indirectArray = new Uint32Array( size * size );
  20082. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20083. this._indirectTexture = indirectTexture;
  20084. }
  20085. _initColorsTexture() {
  20086. let size = Math.sqrt( this._maxInstanceCount );
  20087. size = Math.ceil( size );
  20088. // 4 floats per RGBA pixel initialized to white
  20089. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20090. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20091. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20092. this._colorsTexture = colorsTexture;
  20093. }
  20094. _initializeGeometry( reference ) {
  20095. const geometry = this.geometry;
  20096. const maxVertexCount = this._maxVertexCount;
  20097. const maxIndexCount = this._maxIndexCount;
  20098. if ( this._geometryInitialized === false ) {
  20099. for ( const attributeName in reference.attributes ) {
  20100. const srcAttribute = reference.getAttribute( attributeName );
  20101. const { array, itemSize, normalized } = srcAttribute;
  20102. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20103. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20104. geometry.setAttribute( attributeName, dstAttribute );
  20105. }
  20106. if ( reference.getIndex() !== null ) {
  20107. // Reserve last u16 index for primitive restart.
  20108. const indexArray = maxVertexCount > 65535
  20109. ? new Uint32Array( maxIndexCount )
  20110. : new Uint16Array( maxIndexCount );
  20111. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20112. }
  20113. this._geometryInitialized = true;
  20114. }
  20115. }
  20116. // Make sure the geometry is compatible with the existing combined geometry attributes
  20117. _validateGeometry( geometry ) {
  20118. // check to ensure the geometries are using consistent attributes and indices
  20119. const batchGeometry = this.geometry;
  20120. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20121. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20122. }
  20123. for ( const attributeName in batchGeometry.attributes ) {
  20124. if ( ! geometry.hasAttribute( attributeName ) ) {
  20125. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20126. }
  20127. const srcAttribute = geometry.getAttribute( attributeName );
  20128. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20129. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20130. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20131. }
  20132. }
  20133. }
  20134. /**
  20135. * Validates the instance defined by the given ID.
  20136. *
  20137. * @param {number} instanceId - The instance to validate.
  20138. */
  20139. validateInstanceId( instanceId ) {
  20140. const instanceInfo = this._instanceInfo;
  20141. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20142. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20143. }
  20144. }
  20145. /**
  20146. * Validates the geometry defined by the given ID.
  20147. *
  20148. * @param {number} geometryId - The geometry to validate.
  20149. */
  20150. validateGeometryId( geometryId ) {
  20151. const geometryInfoList = this._geometryInfo;
  20152. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20153. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20154. }
  20155. }
  20156. /**
  20157. * Takes a sort a function that is run before render. The function takes a list of instances to
  20158. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20159. *
  20160. * @param {Function} func - The custom sort function.
  20161. * @return {BatchedMesh} A reference to this batched mesh.
  20162. */
  20163. setCustomSort( func ) {
  20164. this.customSort = func;
  20165. return this;
  20166. }
  20167. /**
  20168. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20169. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20170. * otherwise they are `null`.
  20171. */
  20172. computeBoundingBox() {
  20173. if ( this.boundingBox === null ) {
  20174. this.boundingBox = new Box3();
  20175. }
  20176. const boundingBox = this.boundingBox;
  20177. const instanceInfo = this._instanceInfo;
  20178. boundingBox.makeEmpty();
  20179. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20180. if ( instanceInfo[ i ].active === false ) continue;
  20181. const geometryId = instanceInfo[ i ].geometryIndex;
  20182. this.getMatrixAt( i, _matrix$1 );
  20183. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20184. boundingBox.union( _box$1 );
  20185. }
  20186. }
  20187. /**
  20188. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20189. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20190. * otherwise they are `null`.
  20191. */
  20192. computeBoundingSphere() {
  20193. if ( this.boundingSphere === null ) {
  20194. this.boundingSphere = new Sphere();
  20195. }
  20196. const boundingSphere = this.boundingSphere;
  20197. const instanceInfo = this._instanceInfo;
  20198. boundingSphere.makeEmpty();
  20199. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20200. if ( instanceInfo[ i ].active === false ) continue;
  20201. const geometryId = instanceInfo[ i ].geometryIndex;
  20202. this.getMatrixAt( i, _matrix$1 );
  20203. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20204. boundingSphere.union( _sphere$2 );
  20205. }
  20206. }
  20207. /**
  20208. * Adds a new instance to the batch using the geometry of the given ID and returns
  20209. * a new id referring to the new instance to be used by other functions.
  20210. *
  20211. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20212. * @return {number} The instance ID.
  20213. */
  20214. addInstance( geometryId ) {
  20215. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20216. // ensure we're not over geometry
  20217. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20218. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20219. }
  20220. const instanceInfo = {
  20221. visible: true,
  20222. active: true,
  20223. geometryIndex: geometryId,
  20224. };
  20225. let drawId = null;
  20226. // Prioritize using previously freed instance ids
  20227. if ( this._availableInstanceIds.length > 0 ) {
  20228. this._availableInstanceIds.sort( ascIdSort );
  20229. drawId = this._availableInstanceIds.shift();
  20230. this._instanceInfo[ drawId ] = instanceInfo;
  20231. } else {
  20232. drawId = this._instanceInfo.length;
  20233. this._instanceInfo.push( instanceInfo );
  20234. }
  20235. const matricesTexture = this._matricesTexture;
  20236. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20237. matricesTexture.needsUpdate = true;
  20238. const colorsTexture = this._colorsTexture;
  20239. if ( colorsTexture ) {
  20240. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20241. colorsTexture.needsUpdate = true;
  20242. }
  20243. this._visibilityChanged = true;
  20244. return drawId;
  20245. }
  20246. /**
  20247. * Adds the given geometry to the batch and returns the associated
  20248. * geometry id referring to it to be used in other functions.
  20249. *
  20250. * @param {BufferGeometry} geometry - The geometry to add.
  20251. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20252. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20253. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20254. * Defaults to the length of the given geometry vertex buffer.
  20255. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20256. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20257. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20258. * the length of the given geometry index buffer.
  20259. * @return {number} The geometry ID.
  20260. */
  20261. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20262. this._initializeGeometry( geometry );
  20263. this._validateGeometry( geometry );
  20264. const geometryInfo = {
  20265. // geometry information
  20266. vertexStart: -1,
  20267. vertexCount: -1,
  20268. reservedVertexCount: -1,
  20269. indexStart: -1,
  20270. indexCount: -1,
  20271. reservedIndexCount: -1,
  20272. // draw range information
  20273. start: -1,
  20274. count: -1,
  20275. // state
  20276. boundingBox: null,
  20277. boundingSphere: null,
  20278. active: true,
  20279. };
  20280. const geometryInfoList = this._geometryInfo;
  20281. geometryInfo.vertexStart = this._nextVertexStart;
  20282. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20283. const index = geometry.getIndex();
  20284. const hasIndex = index !== null;
  20285. if ( hasIndex ) {
  20286. geometryInfo.indexStart = this._nextIndexStart;
  20287. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20288. }
  20289. if (
  20290. geometryInfo.indexStart !== -1 &&
  20291. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20292. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20293. ) {
  20294. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20295. }
  20296. // update id
  20297. let geometryId;
  20298. if ( this._availableGeometryIds.length > 0 ) {
  20299. this._availableGeometryIds.sort( ascIdSort );
  20300. geometryId = this._availableGeometryIds.shift();
  20301. geometryInfoList[ geometryId ] = geometryInfo;
  20302. } else {
  20303. geometryId = this._geometryCount;
  20304. this._geometryCount ++;
  20305. geometryInfoList.push( geometryInfo );
  20306. }
  20307. // update the geometry
  20308. this.setGeometryAt( geometryId, geometry );
  20309. // increment the next geometry position
  20310. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20311. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20312. return geometryId;
  20313. }
  20314. /**
  20315. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20316. * is not enough space reserved for geometry. Calling this will change all instances that are
  20317. * rendering that geometry.
  20318. *
  20319. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20320. * @param {BufferGeometry} geometry - The new geometry.
  20321. * @return {number} The geometry ID.
  20322. */
  20323. setGeometryAt( geometryId, geometry ) {
  20324. if ( geometryId >= this._geometryCount ) {
  20325. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20326. }
  20327. this._validateGeometry( geometry );
  20328. const batchGeometry = this.geometry;
  20329. const hasIndex = batchGeometry.getIndex() !== null;
  20330. const dstIndex = batchGeometry.getIndex();
  20331. const srcIndex = geometry.getIndex();
  20332. const geometryInfo = this._geometryInfo[ geometryId ];
  20333. if (
  20334. hasIndex &&
  20335. srcIndex.count > geometryInfo.reservedIndexCount ||
  20336. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20337. ) {
  20338. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20339. }
  20340. // copy geometry buffer data over
  20341. const vertexStart = geometryInfo.vertexStart;
  20342. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20343. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20344. for ( const attributeName in batchGeometry.attributes ) {
  20345. // copy attribute data
  20346. const srcAttribute = geometry.getAttribute( attributeName );
  20347. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20348. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20349. // fill the rest in with zeroes
  20350. const itemSize = srcAttribute.itemSize;
  20351. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20352. const index = vertexStart + i;
  20353. for ( let c = 0; c < itemSize; c ++ ) {
  20354. dstAttribute.setComponent( index, c, 0 );
  20355. }
  20356. }
  20357. dstAttribute.needsUpdate = true;
  20358. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20359. }
  20360. // copy index
  20361. if ( hasIndex ) {
  20362. const indexStart = geometryInfo.indexStart;
  20363. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20364. geometryInfo.indexCount = geometry.getIndex().count;
  20365. // copy index data over
  20366. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20367. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20368. }
  20369. // fill the rest in with zeroes
  20370. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20371. dstIndex.setX( indexStart + i, vertexStart );
  20372. }
  20373. dstIndex.needsUpdate = true;
  20374. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20375. }
  20376. // update the draw range
  20377. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20378. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20379. // store the bounding boxes
  20380. geometryInfo.boundingBox = null;
  20381. if ( geometry.boundingBox !== null ) {
  20382. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20383. }
  20384. geometryInfo.boundingSphere = null;
  20385. if ( geometry.boundingSphere !== null ) {
  20386. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20387. }
  20388. this._visibilityChanged = true;
  20389. return geometryId;
  20390. }
  20391. /**
  20392. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20393. * this geometry will also be removed as a side effect.
  20394. *
  20395. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20396. * @return {BatchedMesh} A reference to this batched mesh.
  20397. */
  20398. deleteGeometry( geometryId ) {
  20399. const geometryInfoList = this._geometryInfo;
  20400. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20401. return this;
  20402. }
  20403. // delete any instances associated with this geometry
  20404. const instanceInfo = this._instanceInfo;
  20405. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20406. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20407. this.deleteInstance( i );
  20408. }
  20409. }
  20410. geometryInfoList[ geometryId ].active = false;
  20411. this._availableGeometryIds.push( geometryId );
  20412. this._visibilityChanged = true;
  20413. return this;
  20414. }
  20415. /**
  20416. * Deletes an existing instance from the batch using the given ID.
  20417. *
  20418. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20419. * @return {BatchedMesh} A reference to this batched mesh.
  20420. */
  20421. deleteInstance( instanceId ) {
  20422. this.validateInstanceId( instanceId );
  20423. this._instanceInfo[ instanceId ].active = false;
  20424. this._availableInstanceIds.push( instanceId );
  20425. this._visibilityChanged = true;
  20426. return this;
  20427. }
  20428. /**
  20429. * Repacks the sub geometries in [name] to remove any unused space remaining from
  20430. * previously deleted geometry, freeing up space to add new geometry.
  20431. *
  20432. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20433. * @return {BatchedMesh} A reference to this batched mesh.
  20434. */
  20435. optimize() {
  20436. // track the next indices to copy data to
  20437. let nextVertexStart = 0;
  20438. let nextIndexStart = 0;
  20439. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20440. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20441. const geometryInfoList = this._geometryInfo;
  20442. const indices = geometryInfoList
  20443. .map( ( e, i ) => i )
  20444. .sort( ( a, b ) => {
  20445. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20446. } );
  20447. const geometry = this.geometry;
  20448. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20449. // if a geometry range is inactive then don't copy anything
  20450. const index = indices[ i ];
  20451. const geometryInfo = geometryInfoList[ index ];
  20452. if ( geometryInfo.active === false ) {
  20453. continue;
  20454. }
  20455. // if a geometry contains an index buffer then shift it, as well
  20456. if ( geometry.index !== null ) {
  20457. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20458. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20459. const index = geometry.index;
  20460. const array = index.array;
  20461. // shift the index pointers based on how the vertex data will shift
  20462. // adjusting the index must happen first so the original vertex start value is available
  20463. const elementDelta = nextVertexStart - vertexStart;
  20464. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20465. array[ j ] = array[ j ] + elementDelta;
  20466. }
  20467. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20468. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20469. geometryInfo.indexStart = nextIndexStart;
  20470. }
  20471. nextIndexStart += geometryInfo.reservedIndexCount;
  20472. }
  20473. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20474. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20475. const { vertexStart, reservedVertexCount } = geometryInfo;
  20476. const attributes = geometry.attributes;
  20477. for ( const key in attributes ) {
  20478. const attribute = attributes[ key ];
  20479. const { array, itemSize } = attribute;
  20480. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20481. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20482. }
  20483. geometryInfo.vertexStart = nextVertexStart;
  20484. }
  20485. nextVertexStart += geometryInfo.reservedVertexCount;
  20486. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20487. // step the next geometry points to the shifted position
  20488. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20489. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20490. }
  20491. return this;
  20492. }
  20493. /**
  20494. * Returns the bounding box for the given geometry.
  20495. *
  20496. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20497. * @param {Box3} target - The target object that is used to store the method's result.
  20498. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20499. */
  20500. getBoundingBoxAt( geometryId, target ) {
  20501. if ( geometryId >= this._geometryCount ) {
  20502. return null;
  20503. }
  20504. // compute bounding box
  20505. const geometry = this.geometry;
  20506. const geometryInfo = this._geometryInfo[ geometryId ];
  20507. if ( geometryInfo.boundingBox === null ) {
  20508. const box = new Box3();
  20509. const index = geometry.index;
  20510. const position = geometry.attributes.position;
  20511. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20512. let iv = i;
  20513. if ( index ) {
  20514. iv = index.getX( iv );
  20515. }
  20516. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20517. }
  20518. geometryInfo.boundingBox = box;
  20519. }
  20520. target.copy( geometryInfo.boundingBox );
  20521. return target;
  20522. }
  20523. /**
  20524. * Returns the bounding sphere for the given geometry.
  20525. *
  20526. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20527. * @param {Sphere} target - The target object that is used to store the method's result.
  20528. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20529. */
  20530. getBoundingSphereAt( geometryId, target ) {
  20531. if ( geometryId >= this._geometryCount ) {
  20532. return null;
  20533. }
  20534. // compute bounding sphere
  20535. const geometry = this.geometry;
  20536. const geometryInfo = this._geometryInfo[ geometryId ];
  20537. if ( geometryInfo.boundingSphere === null ) {
  20538. const sphere = new Sphere();
  20539. this.getBoundingBoxAt( geometryId, _box$1 );
  20540. _box$1.getCenter( sphere.center );
  20541. const index = geometry.index;
  20542. const position = geometry.attributes.position;
  20543. let maxRadiusSq = 0;
  20544. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20545. let iv = i;
  20546. if ( index ) {
  20547. iv = index.getX( iv );
  20548. }
  20549. _vector$5.fromBufferAttribute( position, iv );
  20550. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20551. }
  20552. sphere.radius = Math.sqrt( maxRadiusSq );
  20553. geometryInfo.boundingSphere = sphere;
  20554. }
  20555. target.copy( geometryInfo.boundingSphere );
  20556. return target;
  20557. }
  20558. /**
  20559. * Sets the given local transformation matrix to the defined instance.
  20560. * Negatively scaled matrices are not supported.
  20561. *
  20562. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20563. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20564. * @return {BatchedMesh} A reference to this batched mesh.
  20565. */
  20566. setMatrixAt( instanceId, matrix ) {
  20567. this.validateInstanceId( instanceId );
  20568. const matricesTexture = this._matricesTexture;
  20569. const matricesArray = this._matricesTexture.image.data;
  20570. matrix.toArray( matricesArray, instanceId * 16 );
  20571. matricesTexture.needsUpdate = true;
  20572. return this;
  20573. }
  20574. /**
  20575. * Returns the local transformation matrix of the defined instance.
  20576. *
  20577. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20578. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20579. * @return {Matrix4} The instance's local transformation matrix.
  20580. */
  20581. getMatrixAt( instanceId, matrix ) {
  20582. this.validateInstanceId( instanceId );
  20583. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20584. }
  20585. /**
  20586. * Sets the given color to the defined instance.
  20587. *
  20588. * @param {number} instanceId - The ID of an instance to set the color of.
  20589. * @param {Color} color - The color to set the instance to.
  20590. * @return {BatchedMesh} A reference to this batched mesh.
  20591. */
  20592. setColorAt( instanceId, color ) {
  20593. this.validateInstanceId( instanceId );
  20594. if ( this._colorsTexture === null ) {
  20595. this._initColorsTexture();
  20596. }
  20597. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20598. this._colorsTexture.needsUpdate = true;
  20599. return this;
  20600. }
  20601. /**
  20602. * Returns the color of the defined instance.
  20603. *
  20604. * @param {number} instanceId - The ID of an instance to get the color of.
  20605. * @param {Color} color - The target object that is used to store the method's result.
  20606. * @return {Color} The instance's color.
  20607. */
  20608. getColorAt( instanceId, color ) {
  20609. this.validateInstanceId( instanceId );
  20610. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20611. }
  20612. /**
  20613. * Sets the visibility of the instance.
  20614. *
  20615. * @param {number} instanceId - The id of the instance to set the visibility of.
  20616. * @param {boolean} visible - Whether the instance is visible or not.
  20617. * @return {BatchedMesh} A reference to this batched mesh.
  20618. */
  20619. setVisibleAt( instanceId, visible ) {
  20620. this.validateInstanceId( instanceId );
  20621. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20622. return this;
  20623. }
  20624. this._instanceInfo[ instanceId ].visible = visible;
  20625. this._visibilityChanged = true;
  20626. return this;
  20627. }
  20628. /**
  20629. * Returns the visibility state of the defined instance.
  20630. *
  20631. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20632. * @return {boolean} Whether the instance is visible or not.
  20633. */
  20634. getVisibleAt( instanceId ) {
  20635. this.validateInstanceId( instanceId );
  20636. return this._instanceInfo[ instanceId ].visible;
  20637. }
  20638. /**
  20639. * Sets the geometry ID of the instance at the given index.
  20640. *
  20641. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20642. * @param {number} geometryId - The geometry ID to be use by the instance.
  20643. * @return {BatchedMesh} A reference to this batched mesh.
  20644. */
  20645. setGeometryIdAt( instanceId, geometryId ) {
  20646. this.validateInstanceId( instanceId );
  20647. this.validateGeometryId( geometryId );
  20648. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20649. return this;
  20650. }
  20651. /**
  20652. * Returns the geometry ID of the defined instance.
  20653. *
  20654. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20655. * @return {number} The instance's geometry ID.
  20656. */
  20657. getGeometryIdAt( instanceId ) {
  20658. this.validateInstanceId( instanceId );
  20659. return this._instanceInfo[ instanceId ].geometryIndex;
  20660. }
  20661. /**
  20662. * Get the range representing the subset of triangles related to the attached geometry,
  20663. * indicating the starting offset and count, or `null` if invalid.
  20664. *
  20665. * @param {number} geometryId - The id of the geometry to get the range of.
  20666. * @param {Object} [target] - The target object that is used to store the method's result.
  20667. * @return {{
  20668. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20669. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20670. * start:number,count:number
  20671. * }} The result object with range data.
  20672. */
  20673. getGeometryRangeAt( geometryId, target = {} ) {
  20674. this.validateGeometryId( geometryId );
  20675. const geometryInfo = this._geometryInfo[ geometryId ];
  20676. target.vertexStart = geometryInfo.vertexStart;
  20677. target.vertexCount = geometryInfo.vertexCount;
  20678. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20679. target.indexStart = geometryInfo.indexStart;
  20680. target.indexCount = geometryInfo.indexCount;
  20681. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20682. target.start = geometryInfo.start;
  20683. target.count = geometryInfo.count;
  20684. return target;
  20685. }
  20686. /**
  20687. * Resizes the necessary buffers to support the provided number of instances.
  20688. * If the provided arguments shrink the number of instances but there are not enough
  20689. * unused Ids at the end of the list then an error is thrown.
  20690. *
  20691. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20692. */
  20693. setInstanceCount( maxInstanceCount ) {
  20694. // shrink the available instances as much as possible
  20695. const availableInstanceIds = this._availableInstanceIds;
  20696. const instanceInfo = this._instanceInfo;
  20697. availableInstanceIds.sort( ascIdSort );
  20698. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20699. instanceInfo.pop();
  20700. availableInstanceIds.pop();
  20701. }
  20702. // throw an error if it can't be shrunk to the desired size
  20703. if ( maxInstanceCount < instanceInfo.length ) {
  20704. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20705. }
  20706. // copy the multi draw counts
  20707. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20708. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20709. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20710. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20711. this._multiDrawCounts = multiDrawCounts;
  20712. this._multiDrawStarts = multiDrawStarts;
  20713. this._maxInstanceCount = maxInstanceCount;
  20714. // update texture data for instance sampling
  20715. const indirectTexture = this._indirectTexture;
  20716. const matricesTexture = this._matricesTexture;
  20717. const colorsTexture = this._colorsTexture;
  20718. indirectTexture.dispose();
  20719. this._initIndirectTexture();
  20720. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20721. matricesTexture.dispose();
  20722. this._initMatricesTexture();
  20723. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20724. if ( colorsTexture ) {
  20725. colorsTexture.dispose();
  20726. this._initColorsTexture();
  20727. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20728. }
  20729. }
  20730. /**
  20731. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20732. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20733. * end of the geometry attributes then an error is thrown.
  20734. *
  20735. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20736. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20737. */
  20738. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20739. // Check if we can shrink to the requested vertex attribute size
  20740. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20741. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20742. if ( requiredVertexLength > maxVertexCount ) {
  20743. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20744. }
  20745. // Check if we can shrink to the requested index attribute size
  20746. if ( this.geometry.index ) {
  20747. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20748. if ( requiredIndexLength > maxIndexCount ) {
  20749. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20750. }
  20751. }
  20752. //
  20753. // dispose of the previous geometry
  20754. const oldGeometry = this.geometry;
  20755. oldGeometry.dispose();
  20756. // recreate the geometry needed based on the previous variant
  20757. this._maxVertexCount = maxVertexCount;
  20758. this._maxIndexCount = maxIndexCount;
  20759. if ( this._geometryInitialized ) {
  20760. this._geometryInitialized = false;
  20761. this.geometry = new BufferGeometry();
  20762. this._initializeGeometry( oldGeometry );
  20763. }
  20764. // copy data from the previous geometry
  20765. const geometry = this.geometry;
  20766. if ( oldGeometry.index ) {
  20767. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20768. }
  20769. for ( const key in oldGeometry.attributes ) {
  20770. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20771. }
  20772. }
  20773. raycast( raycaster, intersects ) {
  20774. const instanceInfo = this._instanceInfo;
  20775. const geometryInfoList = this._geometryInfo;
  20776. const matrixWorld = this.matrixWorld;
  20777. const batchGeometry = this.geometry;
  20778. // iterate over each geometry
  20779. _mesh.material = this.material;
  20780. _mesh.geometry.index = batchGeometry.index;
  20781. _mesh.geometry.attributes = batchGeometry.attributes;
  20782. if ( _mesh.geometry.boundingBox === null ) {
  20783. _mesh.geometry.boundingBox = new Box3();
  20784. }
  20785. if ( _mesh.geometry.boundingSphere === null ) {
  20786. _mesh.geometry.boundingSphere = new Sphere();
  20787. }
  20788. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20789. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20790. continue;
  20791. }
  20792. const geometryId = instanceInfo[ i ].geometryIndex;
  20793. const geometryInfo = geometryInfoList[ geometryId ];
  20794. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20795. // get the intersects
  20796. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20797. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20798. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20799. _mesh.raycast( raycaster, _batchIntersects );
  20800. // add batch id to the intersects
  20801. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20802. const intersect = _batchIntersects[ j ];
  20803. intersect.object = this;
  20804. intersect.batchId = i;
  20805. intersects.push( intersect );
  20806. }
  20807. _batchIntersects.length = 0;
  20808. }
  20809. _mesh.material = null;
  20810. _mesh.geometry.index = null;
  20811. _mesh.geometry.attributes = {};
  20812. _mesh.geometry.setDrawRange( 0, Infinity );
  20813. }
  20814. copy( source ) {
  20815. super.copy( source );
  20816. this.geometry = source.geometry.clone();
  20817. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20818. this.sortObjects = source.sortObjects;
  20819. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20820. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20821. this._geometryInfo = source._geometryInfo.map( info => ( {
  20822. ...info,
  20823. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20824. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20825. } ) );
  20826. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20827. this._availableInstanceIds = source._availableInstanceIds.slice();
  20828. this._availableGeometryIds = source._availableGeometryIds.slice();
  20829. this._nextIndexStart = source._nextIndexStart;
  20830. this._nextVertexStart = source._nextVertexStart;
  20831. this._geometryCount = source._geometryCount;
  20832. this._maxInstanceCount = source._maxInstanceCount;
  20833. this._maxVertexCount = source._maxVertexCount;
  20834. this._maxIndexCount = source._maxIndexCount;
  20835. this._geometryInitialized = source._geometryInitialized;
  20836. this._multiDrawCounts = source._multiDrawCounts.slice();
  20837. this._multiDrawStarts = source._multiDrawStarts.slice();
  20838. this._indirectTexture = source._indirectTexture.clone();
  20839. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20840. this._matricesTexture = source._matricesTexture.clone();
  20841. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20842. if ( this._colorsTexture !== null ) {
  20843. this._colorsTexture = source._colorsTexture.clone();
  20844. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20845. }
  20846. return this;
  20847. }
  20848. /**
  20849. * Frees the GPU-related resources allocated by this instance. Call this
  20850. * method whenever this instance is no longer used in your app.
  20851. */
  20852. dispose() {
  20853. // Assuming the geometry is not shared with other meshes
  20854. this.geometry.dispose();
  20855. this._matricesTexture.dispose();
  20856. this._matricesTexture = null;
  20857. this._indirectTexture.dispose();
  20858. this._indirectTexture = null;
  20859. if ( this._colorsTexture !== null ) {
  20860. this._colorsTexture.dispose();
  20861. this._colorsTexture = null;
  20862. }
  20863. }
  20864. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20865. // if visibility has not changed and frustum culling and object sorting is not required
  20866. // then skip iterating over all items
  20867. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20868. return;
  20869. }
  20870. // the indexed version of the multi draw function requires specifying the start
  20871. // offset in bytes.
  20872. const index = geometry.getIndex();
  20873. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20874. const instanceInfo = this._instanceInfo;
  20875. const multiDrawStarts = this._multiDrawStarts;
  20876. const multiDrawCounts = this._multiDrawCounts;
  20877. const geometryInfoList = this._geometryInfo;
  20878. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20879. const indirectTexture = this._indirectTexture;
  20880. const indirectArray = indirectTexture.image.data;
  20881. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20882. // prepare the frustum in the local frame
  20883. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20884. _matrix$1
  20885. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20886. .multiply( this.matrixWorld );
  20887. _frustum.setFromProjectionMatrix(
  20888. _matrix$1,
  20889. camera.coordinateSystem,
  20890. camera.reversedDepth
  20891. );
  20892. }
  20893. let multiDrawCount = 0;
  20894. if ( this.sortObjects ) {
  20895. // get the camera position in the local frame
  20896. _matrix$1.copy( this.matrixWorld ).invert();
  20897. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20898. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20899. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20900. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20901. const geometryId = instanceInfo[ i ].geometryIndex;
  20902. // get the bounds in world space
  20903. this.getMatrixAt( i, _matrix$1 );
  20904. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20905. // determine whether the batched geometry is within the frustum
  20906. let culled = false;
  20907. if ( perObjectFrustumCulled ) {
  20908. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20909. }
  20910. if ( ! culled ) {
  20911. // get the distance from camera used for sorting
  20912. const geometryInfo = geometryInfoList[ geometryId ];
  20913. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20914. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20915. }
  20916. }
  20917. }
  20918. // Sort the draw ranges and prep for rendering
  20919. const list = _renderList.list;
  20920. const customSort = this.customSort;
  20921. if ( customSort === null ) {
  20922. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20923. } else {
  20924. customSort.call( this, list, camera );
  20925. }
  20926. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20927. const item = list[ i ];
  20928. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  20929. multiDrawCounts[ multiDrawCount ] = item.count;
  20930. indirectArray[ multiDrawCount ] = item.index;
  20931. multiDrawCount ++;
  20932. }
  20933. _renderList.reset();
  20934. } else {
  20935. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20936. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20937. const geometryId = instanceInfo[ i ].geometryIndex;
  20938. // determine whether the batched geometry is within the frustum
  20939. let culled = false;
  20940. if ( perObjectFrustumCulled ) {
  20941. // get the bounds in world space
  20942. this.getMatrixAt( i, _matrix$1 );
  20943. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20944. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20945. }
  20946. if ( ! culled ) {
  20947. const geometryInfo = geometryInfoList[ geometryId ];
  20948. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  20949. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  20950. indirectArray[ multiDrawCount ] = i;
  20951. multiDrawCount ++;
  20952. }
  20953. }
  20954. }
  20955. }
  20956. indirectTexture.needsUpdate = true;
  20957. this._multiDrawCount = multiDrawCount;
  20958. this._visibilityChanged = false;
  20959. }
  20960. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20961. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20962. }
  20963. }
  20964. /**
  20965. * A material for rendering line primitives.
  20966. *
  20967. * Materials define the appearance of renderable 3D objects.
  20968. *
  20969. * ```js
  20970. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20971. * ```
  20972. *
  20973. * @augments Material
  20974. */
  20975. class LineBasicMaterial extends Material {
  20976. /**
  20977. * Constructs a new line basic material.
  20978. *
  20979. * @param {Object} [parameters] - An object with one or more properties
  20980. * defining the material's appearance. Any property of the material
  20981. * (including any property from inherited materials) can be passed
  20982. * in here. Color values can be passed any type of value accepted
  20983. * by {@link Color#set}.
  20984. */
  20985. constructor( parameters ) {
  20986. super();
  20987. /**
  20988. * This flag can be used for type testing.
  20989. *
  20990. * @type {boolean}
  20991. * @readonly
  20992. * @default true
  20993. */
  20994. this.isLineBasicMaterial = true;
  20995. this.type = 'LineBasicMaterial';
  20996. /**
  20997. * Color of the material.
  20998. *
  20999. * @type {Color}
  21000. * @default (1,1,1)
  21001. */
  21002. this.color = new Color( 0xffffff );
  21003. /**
  21004. * Sets the color of the lines using data from a texture. The texture map
  21005. * color is modulated by the diffuse `color`.
  21006. *
  21007. * @type {?Texture}
  21008. * @default null
  21009. */
  21010. this.map = null;
  21011. /**
  21012. * Controls line thickness or lines.
  21013. *
  21014. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21015. * ignore this setting and always render line primitives with a
  21016. * width of one pixel.
  21017. *
  21018. * @type {number}
  21019. * @default 1
  21020. */
  21021. this.linewidth = 1;
  21022. /**
  21023. * Defines appearance of line ends.
  21024. *
  21025. * Can only be used with {@link SVGRenderer}.
  21026. *
  21027. * @type {('butt'|'round'|'square')}
  21028. * @default 'round'
  21029. */
  21030. this.linecap = 'round';
  21031. /**
  21032. * Defines appearance of line joints.
  21033. *
  21034. * Can only be used with {@link SVGRenderer}.
  21035. *
  21036. * @type {('round'|'bevel'|'miter')}
  21037. * @default 'round'
  21038. */
  21039. this.linejoin = 'round';
  21040. /**
  21041. * Whether the material is affected by fog or not.
  21042. *
  21043. * @type {boolean}
  21044. * @default true
  21045. */
  21046. this.fog = true;
  21047. this.setValues( parameters );
  21048. }
  21049. copy( source ) {
  21050. super.copy( source );
  21051. this.color.copy( source.color );
  21052. this.map = source.map;
  21053. this.linewidth = source.linewidth;
  21054. this.linecap = source.linecap;
  21055. this.linejoin = source.linejoin;
  21056. this.fog = source.fog;
  21057. return this;
  21058. }
  21059. }
  21060. const _vStart = /*@__PURE__*/ new Vector3();
  21061. const _vEnd = /*@__PURE__*/ new Vector3();
  21062. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21063. const _ray$1 = /*@__PURE__*/ new Ray();
  21064. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21065. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21066. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21067. /**
  21068. * A continuous line. The line are rendered by connecting consecutive
  21069. * vertices with straight lines.
  21070. *
  21071. * ```js
  21072. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21073. *
  21074. * const points = [];
  21075. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21076. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21077. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21078. *
  21079. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21080. *
  21081. * const line = new THREE.Line( geometry, material );
  21082. * scene.add( line );
  21083. * ```
  21084. *
  21085. * @augments Object3D
  21086. */
  21087. class Line extends Object3D {
  21088. /**
  21089. * Constructs a new line.
  21090. *
  21091. * @param {BufferGeometry} [geometry] - The line geometry.
  21092. * @param {Material|Array<Material>} [material] - The line material.
  21093. */
  21094. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21095. super();
  21096. /**
  21097. * This flag can be used for type testing.
  21098. *
  21099. * @type {boolean}
  21100. * @readonly
  21101. * @default true
  21102. */
  21103. this.isLine = true;
  21104. this.type = 'Line';
  21105. /**
  21106. * The line geometry.
  21107. *
  21108. * @type {BufferGeometry}
  21109. */
  21110. this.geometry = geometry;
  21111. /**
  21112. * The line material.
  21113. *
  21114. * @type {Material|Array<Material>}
  21115. * @default LineBasicMaterial
  21116. */
  21117. this.material = material;
  21118. /**
  21119. * A dictionary representing the morph targets in the geometry. The key is the
  21120. * morph targets name, the value its attribute index. This member is `undefined`
  21121. * by default and only set when morph targets are detected in the geometry.
  21122. *
  21123. * @type {Object<String,number>|undefined}
  21124. * @default undefined
  21125. */
  21126. this.morphTargetDictionary = undefined;
  21127. /**
  21128. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21129. * is applied. This member is `undefined` by default and only set when morph targets are
  21130. * detected in the geometry.
  21131. *
  21132. * @type {Array<number>|undefined}
  21133. * @default undefined
  21134. */
  21135. this.morphTargetInfluences = undefined;
  21136. this.updateMorphTargets();
  21137. }
  21138. copy( source, recursive ) {
  21139. super.copy( source, recursive );
  21140. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21141. this.geometry = source.geometry;
  21142. return this;
  21143. }
  21144. /**
  21145. * Computes an array of distance values which are necessary for rendering dashed lines.
  21146. * For each vertex in the geometry, the method calculates the cumulative length from the
  21147. * current point to the very beginning of the line.
  21148. *
  21149. * @return {Line} A reference to this line.
  21150. */
  21151. computeLineDistances() {
  21152. const geometry = this.geometry;
  21153. // we assume non-indexed geometry
  21154. if ( geometry.index === null ) {
  21155. const positionAttribute = geometry.attributes.position;
  21156. const lineDistances = [ 0 ];
  21157. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21158. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21159. _vEnd.fromBufferAttribute( positionAttribute, i );
  21160. lineDistances[ i ] = lineDistances[ i - 1 ];
  21161. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21162. }
  21163. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21164. } else {
  21165. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21166. }
  21167. return this;
  21168. }
  21169. /**
  21170. * Computes intersection points between a casted ray and this line.
  21171. *
  21172. * @param {Raycaster} raycaster - The raycaster.
  21173. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21174. */
  21175. raycast( raycaster, intersects ) {
  21176. const geometry = this.geometry;
  21177. const matrixWorld = this.matrixWorld;
  21178. const threshold = raycaster.params.Line.threshold;
  21179. const drawRange = geometry.drawRange;
  21180. // Checking boundingSphere distance to ray
  21181. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21182. _sphere$1.copy( geometry.boundingSphere );
  21183. _sphere$1.applyMatrix4( matrixWorld );
  21184. _sphere$1.radius += threshold;
  21185. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21186. //
  21187. _inverseMatrix$1.copy( matrixWorld ).invert();
  21188. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21189. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21190. const localThresholdSq = localThreshold * localThreshold;
  21191. const step = this.isLineSegments ? 2 : 1;
  21192. const index = geometry.index;
  21193. const attributes = geometry.attributes;
  21194. const positionAttribute = attributes.position;
  21195. if ( index !== null ) {
  21196. const start = Math.max( 0, drawRange.start );
  21197. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21198. for ( let i = start, l = end - 1; i < l; i += step ) {
  21199. const a = index.getX( i );
  21200. const b = index.getX( i + 1 );
  21201. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21202. if ( intersect ) {
  21203. intersects.push( intersect );
  21204. }
  21205. }
  21206. if ( this.isLineLoop ) {
  21207. const a = index.getX( end - 1 );
  21208. const b = index.getX( start );
  21209. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21210. if ( intersect ) {
  21211. intersects.push( intersect );
  21212. }
  21213. }
  21214. } else {
  21215. const start = Math.max( 0, drawRange.start );
  21216. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21217. for ( let i = start, l = end - 1; i < l; i += step ) {
  21218. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21219. if ( intersect ) {
  21220. intersects.push( intersect );
  21221. }
  21222. }
  21223. if ( this.isLineLoop ) {
  21224. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21225. if ( intersect ) {
  21226. intersects.push( intersect );
  21227. }
  21228. }
  21229. }
  21230. }
  21231. /**
  21232. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21233. * to make sure existing morph targets can influence this 3D object.
  21234. */
  21235. updateMorphTargets() {
  21236. const geometry = this.geometry;
  21237. const morphAttributes = geometry.morphAttributes;
  21238. const keys = Object.keys( morphAttributes );
  21239. if ( keys.length > 0 ) {
  21240. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21241. if ( morphAttribute !== undefined ) {
  21242. this.morphTargetInfluences = [];
  21243. this.morphTargetDictionary = {};
  21244. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21245. const name = morphAttribute[ m ].name || String( m );
  21246. this.morphTargetInfluences.push( 0 );
  21247. this.morphTargetDictionary[ name ] = m;
  21248. }
  21249. }
  21250. }
  21251. }
  21252. }
  21253. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21254. const positionAttribute = object.geometry.attributes.position;
  21255. _vStart.fromBufferAttribute( positionAttribute, a );
  21256. _vEnd.fromBufferAttribute( positionAttribute, b );
  21257. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21258. if ( distSq > thresholdSq ) return;
  21259. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21260. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21261. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21262. return {
  21263. distance: distance,
  21264. // What do we want? intersection point on the ray or on the segment??
  21265. // point: raycaster.ray.at( distance ),
  21266. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21267. index: i,
  21268. face: null,
  21269. faceIndex: null,
  21270. barycoord: null,
  21271. object: object
  21272. };
  21273. }
  21274. const _start = /*@__PURE__*/ new Vector3();
  21275. const _end = /*@__PURE__*/ new Vector3();
  21276. /**
  21277. * A series of lines drawn between pairs of vertices.
  21278. *
  21279. * @augments Line
  21280. */
  21281. class LineSegments extends Line {
  21282. /**
  21283. * Constructs a new line segments.
  21284. *
  21285. * @param {BufferGeometry} [geometry] - The line geometry.
  21286. * @param {Material|Array<Material>} [material] - The line material.
  21287. */
  21288. constructor( geometry, material ) {
  21289. super( geometry, material );
  21290. /**
  21291. * This flag can be used for type testing.
  21292. *
  21293. * @type {boolean}
  21294. * @readonly
  21295. * @default true
  21296. */
  21297. this.isLineSegments = true;
  21298. this.type = 'LineSegments';
  21299. }
  21300. computeLineDistances() {
  21301. const geometry = this.geometry;
  21302. // we assume non-indexed geometry
  21303. if ( geometry.index === null ) {
  21304. const positionAttribute = geometry.attributes.position;
  21305. const lineDistances = [];
  21306. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21307. _start.fromBufferAttribute( positionAttribute, i );
  21308. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21309. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21310. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21311. }
  21312. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21313. } else {
  21314. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21315. }
  21316. return this;
  21317. }
  21318. }
  21319. /**
  21320. * A continuous line. This is nearly the same as {@link Line} the only difference
  21321. * is that the last vertex is connected with the first vertex in order to close
  21322. * the line to form a loop.
  21323. *
  21324. * @augments Line
  21325. */
  21326. class LineLoop extends Line {
  21327. /**
  21328. * Constructs a new line loop.
  21329. *
  21330. * @param {BufferGeometry} [geometry] - The line geometry.
  21331. * @param {Material|Array<Material>} [material] - The line material.
  21332. */
  21333. constructor( geometry, material ) {
  21334. super( geometry, material );
  21335. /**
  21336. * This flag can be used for type testing.
  21337. *
  21338. * @type {boolean}
  21339. * @readonly
  21340. * @default true
  21341. */
  21342. this.isLineLoop = true;
  21343. this.type = 'LineLoop';
  21344. }
  21345. }
  21346. /**
  21347. * A material for rendering point primitives.
  21348. *
  21349. * Materials define the appearance of renderable 3D objects.
  21350. *
  21351. * ```js
  21352. * const vertices = [];
  21353. *
  21354. * for ( let i = 0; i < 10000; i ++ ) {
  21355. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21356. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21357. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21358. *
  21359. * vertices.push( x, y, z );
  21360. * }
  21361. *
  21362. * const geometry = new THREE.BufferGeometry();
  21363. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21364. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21365. * const points = new THREE.Points( geometry, material );
  21366. * scene.add( points );
  21367. * ```
  21368. *
  21369. * @augments Material
  21370. */
  21371. class PointsMaterial extends Material {
  21372. /**
  21373. * Constructs a new points material.
  21374. *
  21375. * @param {Object} [parameters] - An object with one or more properties
  21376. * defining the material's appearance. Any property of the material
  21377. * (including any property from inherited materials) can be passed
  21378. * in here. Color values can be passed any type of value accepted
  21379. * by {@link Color#set}.
  21380. */
  21381. constructor( parameters ) {
  21382. super();
  21383. /**
  21384. * This flag can be used for type testing.
  21385. *
  21386. * @type {boolean}
  21387. * @readonly
  21388. * @default true
  21389. */
  21390. this.isPointsMaterial = true;
  21391. this.type = 'PointsMaterial';
  21392. /**
  21393. * Color of the material.
  21394. *
  21395. * @type {Color}
  21396. * @default (1,1,1)
  21397. */
  21398. this.color = new Color( 0xffffff );
  21399. /**
  21400. * The color map. May optionally include an alpha channel, typically combined
  21401. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21402. * color is modulated by the diffuse `color`.
  21403. *
  21404. * @type {?Texture}
  21405. * @default null
  21406. */
  21407. this.map = null;
  21408. /**
  21409. * The alpha map is a grayscale texture that controls the opacity across the
  21410. * surface (black: fully transparent; white: fully opaque).
  21411. *
  21412. * Only the color of the texture is used, ignoring the alpha channel if one
  21413. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21414. * when sampling this texture due to the extra bit of precision provided for
  21415. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21416. * luminance/alpha textures will also still work as expected.
  21417. *
  21418. * @type {?Texture}
  21419. * @default null
  21420. */
  21421. this.alphaMap = null;
  21422. /**
  21423. * Defines the size of the points in pixels.
  21424. *
  21425. * Might be capped if the value exceeds hardware dependent parameters like [gl.ALIASED_POINT_SIZE_RANGE]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getParamete}.
  21426. *
  21427. * @type {number}
  21428. * @default 1
  21429. */
  21430. this.size = 1;
  21431. /**
  21432. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21433. *
  21434. * @type {boolean}
  21435. * @default true
  21436. */
  21437. this.sizeAttenuation = true;
  21438. /**
  21439. * Whether the material is affected by fog or not.
  21440. *
  21441. * @type {boolean}
  21442. * @default true
  21443. */
  21444. this.fog = true;
  21445. this.setValues( parameters );
  21446. }
  21447. copy( source ) {
  21448. super.copy( source );
  21449. this.color.copy( source.color );
  21450. this.map = source.map;
  21451. this.alphaMap = source.alphaMap;
  21452. this.size = source.size;
  21453. this.sizeAttenuation = source.sizeAttenuation;
  21454. this.fog = source.fog;
  21455. return this;
  21456. }
  21457. }
  21458. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21459. const _ray = /*@__PURE__*/ new Ray();
  21460. const _sphere = /*@__PURE__*/ new Sphere();
  21461. const _position$2 = /*@__PURE__*/ new Vector3();
  21462. /**
  21463. * A class for displaying points or point clouds.
  21464. *
  21465. * @augments Object3D
  21466. */
  21467. class Points extends Object3D {
  21468. /**
  21469. * Constructs a new point cloud.
  21470. *
  21471. * @param {BufferGeometry} [geometry] - The points geometry.
  21472. * @param {Material|Array<Material>} [material] - The points material.
  21473. */
  21474. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21475. super();
  21476. /**
  21477. * This flag can be used for type testing.
  21478. *
  21479. * @type {boolean}
  21480. * @readonly
  21481. * @default true
  21482. */
  21483. this.isPoints = true;
  21484. this.type = 'Points';
  21485. /**
  21486. * The points geometry.
  21487. *
  21488. * @type {BufferGeometry}
  21489. */
  21490. this.geometry = geometry;
  21491. /**
  21492. * The line material.
  21493. *
  21494. * @type {Material|Array<Material>}
  21495. * @default PointsMaterial
  21496. */
  21497. this.material = material;
  21498. /**
  21499. * A dictionary representing the morph targets in the geometry. The key is the
  21500. * morph targets name, the value its attribute index. This member is `undefined`
  21501. * by default and only set when morph targets are detected in the geometry.
  21502. *
  21503. * @type {Object<String,number>|undefined}
  21504. * @default undefined
  21505. */
  21506. this.morphTargetDictionary = undefined;
  21507. /**
  21508. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21509. * is applied. This member is `undefined` by default and only set when morph targets are
  21510. * detected in the geometry.
  21511. *
  21512. * @type {Array<number>|undefined}
  21513. * @default undefined
  21514. */
  21515. this.morphTargetInfluences = undefined;
  21516. this.updateMorphTargets();
  21517. }
  21518. copy( source, recursive ) {
  21519. super.copy( source, recursive );
  21520. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21521. this.geometry = source.geometry;
  21522. return this;
  21523. }
  21524. /**
  21525. * Computes intersection points between a casted ray and this point cloud.
  21526. *
  21527. * @param {Raycaster} raycaster - The raycaster.
  21528. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21529. */
  21530. raycast( raycaster, intersects ) {
  21531. const geometry = this.geometry;
  21532. const matrixWorld = this.matrixWorld;
  21533. const threshold = raycaster.params.Points.threshold;
  21534. const drawRange = geometry.drawRange;
  21535. // Checking boundingSphere distance to ray
  21536. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21537. _sphere.copy( geometry.boundingSphere );
  21538. _sphere.applyMatrix4( matrixWorld );
  21539. _sphere.radius += threshold;
  21540. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21541. //
  21542. _inverseMatrix.copy( matrixWorld ).invert();
  21543. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21544. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21545. const localThresholdSq = localThreshold * localThreshold;
  21546. const index = geometry.index;
  21547. const attributes = geometry.attributes;
  21548. const positionAttribute = attributes.position;
  21549. if ( index !== null ) {
  21550. const start = Math.max( 0, drawRange.start );
  21551. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21552. for ( let i = start, il = end; i < il; i ++ ) {
  21553. const a = index.getX( i );
  21554. _position$2.fromBufferAttribute( positionAttribute, a );
  21555. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21556. }
  21557. } else {
  21558. const start = Math.max( 0, drawRange.start );
  21559. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21560. for ( let i = start, l = end; i < l; i ++ ) {
  21561. _position$2.fromBufferAttribute( positionAttribute, i );
  21562. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21563. }
  21564. }
  21565. }
  21566. /**
  21567. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21568. * to make sure existing morph targets can influence this 3D object.
  21569. */
  21570. updateMorphTargets() {
  21571. const geometry = this.geometry;
  21572. const morphAttributes = geometry.morphAttributes;
  21573. const keys = Object.keys( morphAttributes );
  21574. if ( keys.length > 0 ) {
  21575. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21576. if ( morphAttribute !== undefined ) {
  21577. this.morphTargetInfluences = [];
  21578. this.morphTargetDictionary = {};
  21579. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21580. const name = morphAttribute[ m ].name || String( m );
  21581. this.morphTargetInfluences.push( 0 );
  21582. this.morphTargetDictionary[ name ] = m;
  21583. }
  21584. }
  21585. }
  21586. }
  21587. }
  21588. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21589. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21590. if ( rayPointDistanceSq < localThresholdSq ) {
  21591. const intersectPoint = new Vector3();
  21592. _ray.closestPointToPoint( point, intersectPoint );
  21593. intersectPoint.applyMatrix4( matrixWorld );
  21594. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21595. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21596. intersects.push( {
  21597. distance: distance,
  21598. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21599. point: intersectPoint,
  21600. index: index,
  21601. face: null,
  21602. faceIndex: null,
  21603. barycoord: null,
  21604. object: object
  21605. } );
  21606. }
  21607. }
  21608. /**
  21609. * A texture for use with a video.
  21610. *
  21611. * ```js
  21612. * // assuming you have created a HTML video element with id="video"
  21613. * const video = document.getElementById( 'video' );
  21614. * const texture = new THREE.VideoTexture( video );
  21615. * ```
  21616. *
  21617. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21618. * set to THREE.SRGBColorSpace.
  21619. *
  21620. * Note: After the initial use of a texture, its dimensions, format, and type
  21621. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21622. *
  21623. * @augments Texture
  21624. */
  21625. class VideoTexture extends Texture {
  21626. /**
  21627. * Constructs a new video texture.
  21628. *
  21629. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21630. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21631. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21632. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21633. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21634. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21635. * @param {number} [format=RGBAFormat] - The texture format.
  21636. * @param {number} [type=UnsignedByteType] - The texture type.
  21637. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21638. */
  21639. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21640. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21641. /**
  21642. * This flag can be used for type testing.
  21643. *
  21644. * @type {boolean}
  21645. * @readonly
  21646. * @default true
  21647. */
  21648. this.isVideoTexture = true;
  21649. /**
  21650. * Whether to generate mipmaps (if possible) for a texture.
  21651. *
  21652. * Overwritten and set to `false` by default.
  21653. *
  21654. * @type {boolean}
  21655. * @default false
  21656. */
  21657. this.generateMipmaps = false;
  21658. /**
  21659. * The video frame request callback identifier, which is a positive integer.
  21660. *
  21661. * Value of 0 represents no scheduled rVFC.
  21662. *
  21663. * @private
  21664. * @type {number}
  21665. */
  21666. this._requestVideoFrameCallbackId = 0;
  21667. const scope = this;
  21668. function updateVideo() {
  21669. scope.needsUpdate = true;
  21670. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21671. }
  21672. if ( 'requestVideoFrameCallback' in video ) {
  21673. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21674. }
  21675. }
  21676. clone() {
  21677. return new this.constructor( this.image ).copy( this );
  21678. }
  21679. /**
  21680. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21681. * to `true` every time a new frame is available.
  21682. *
  21683. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21684. */
  21685. update() {
  21686. const video = this.image;
  21687. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21688. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21689. this.needsUpdate = true;
  21690. }
  21691. }
  21692. dispose() {
  21693. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21694. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21695. }
  21696. super.dispose();
  21697. }
  21698. }
  21699. /**
  21700. * This class can be used as an alternative way to define video data. Instead of using
  21701. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21702. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21703. * video frames are decoded with the WebCodecs API.
  21704. *
  21705. * ```js
  21706. * const texture = new THREE.VideoFrameTexture();
  21707. * texture.setFrame( frame );
  21708. * ```
  21709. *
  21710. * @augments VideoTexture
  21711. */
  21712. class VideoFrameTexture extends VideoTexture {
  21713. /**
  21714. * Constructs a new video frame texture.
  21715. *
  21716. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21717. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21718. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21719. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21720. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21721. * @param {number} [format=RGBAFormat] - The texture format.
  21722. * @param {number} [type=UnsignedByteType] - The texture type.
  21723. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21724. */
  21725. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21726. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21727. /**
  21728. * This flag can be used for type testing.
  21729. *
  21730. * @type {boolean}
  21731. * @readonly
  21732. * @default true
  21733. */
  21734. this.isVideoFrameTexture = true;
  21735. }
  21736. /**
  21737. * This method overwritten with an empty implementation since
  21738. * this type of texture is updated via `setFrame()`.
  21739. */
  21740. update() {}
  21741. clone() {
  21742. return new this.constructor().copy( this ); // restoring Texture.clone()
  21743. }
  21744. /**
  21745. * Sets the current frame of the video. This will automatically update the texture
  21746. * so the data can be used for rendering.
  21747. *
  21748. * @param {VideoFrame} frame - The video frame.
  21749. */
  21750. setFrame( frame ) {
  21751. this.image = frame;
  21752. this.needsUpdate = true;
  21753. }
  21754. }
  21755. /**
  21756. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21757. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21758. * as a texture for further usage.
  21759. *
  21760. * ```js
  21761. * const pixelRatio = window.devicePixelRatio;
  21762. * const textureSize = 128 * pixelRatio;
  21763. *
  21764. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21765. *
  21766. * // calculate start position for copying part of the frame data
  21767. * const vector = new Vector2();
  21768. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21769. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21770. *
  21771. * renderer.render( scene, camera );
  21772. *
  21773. * // copy part of the rendered frame into the framebuffer texture
  21774. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21775. * ```
  21776. *
  21777. * @augments Texture
  21778. */
  21779. class FramebufferTexture extends Texture {
  21780. /**
  21781. * Constructs a new framebuffer texture.
  21782. *
  21783. * @param {number} [width] - The width of the texture.
  21784. * @param {number} [height] - The height of the texture.
  21785. */
  21786. constructor( width, height ) {
  21787. super( { width, height } );
  21788. /**
  21789. * This flag can be used for type testing.
  21790. *
  21791. * @type {boolean}
  21792. * @readonly
  21793. * @default true
  21794. */
  21795. this.isFramebufferTexture = true;
  21796. /**
  21797. * How the texture is sampled when a texel covers more than one pixel.
  21798. *
  21799. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21800. *
  21801. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21802. * @default NearestFilter
  21803. */
  21804. this.magFilter = NearestFilter;
  21805. /**
  21806. * How the texture is sampled when a texel covers less than one pixel.
  21807. *
  21808. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21809. *
  21810. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21811. * @default NearestFilter
  21812. */
  21813. this.minFilter = NearestFilter;
  21814. /**
  21815. * Whether to generate mipmaps (if possible) for a texture.
  21816. *
  21817. * Overwritten and set to `false` by default.
  21818. *
  21819. * @type {boolean}
  21820. * @default false
  21821. */
  21822. this.generateMipmaps = false;
  21823. this.needsUpdate = true;
  21824. }
  21825. }
  21826. /**
  21827. * Creates a texture based on data in compressed form.
  21828. *
  21829. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21830. *
  21831. * @augments Texture
  21832. */
  21833. class CompressedTexture extends Texture {
  21834. /**
  21835. * Constructs a new compressed texture.
  21836. *
  21837. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21838. * the data and dimensions.
  21839. * @param {number} width - The width of the texture.
  21840. * @param {number} height - The height of the texture.
  21841. * @param {number} [format=RGBAFormat] - The texture format.
  21842. * @param {number} [type=UnsignedByteType] - The texture type.
  21843. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21844. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21845. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21846. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21847. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21848. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21849. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21850. */
  21851. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21852. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21853. /**
  21854. * This flag can be used for type testing.
  21855. *
  21856. * @type {boolean}
  21857. * @readonly
  21858. * @default true
  21859. */
  21860. this.isCompressedTexture = true;
  21861. /**
  21862. * The image property of a compressed texture just defines its dimensions.
  21863. *
  21864. * @type {{width:number,height:number}}
  21865. */
  21866. this.image = { width: width, height: height };
  21867. /**
  21868. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21869. *
  21870. * @type {Array<Object>}
  21871. */
  21872. this.mipmaps = mipmaps;
  21873. /**
  21874. * If set to `true`, the texture is flipped along the vertical axis when
  21875. * uploaded to the GPU.
  21876. *
  21877. * Overwritten and set to `false` by default since it is not possible to
  21878. * flip compressed textures.
  21879. *
  21880. * @type {boolean}
  21881. * @default false
  21882. * @readonly
  21883. */
  21884. this.flipY = false;
  21885. /**
  21886. * Whether to generate mipmaps (if possible) for a texture.
  21887. *
  21888. * Overwritten and set to `false` by default since it is not
  21889. * possible to generate mipmaps for compressed data. Mipmaps
  21890. * must be embedded in the compressed texture file.
  21891. *
  21892. * @type {boolean}
  21893. * @default false
  21894. * @readonly
  21895. */
  21896. this.generateMipmaps = false;
  21897. }
  21898. }
  21899. /**
  21900. * Creates a texture 2D array based on data in compressed form.
  21901. *
  21902. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21903. *
  21904. * @augments CompressedTexture
  21905. */
  21906. class CompressedArrayTexture extends CompressedTexture {
  21907. /**
  21908. * Constructs a new compressed array texture.
  21909. *
  21910. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21911. * the data and dimensions.
  21912. * @param {number} width - The width of the texture.
  21913. * @param {number} height - The height of the texture.
  21914. * @param {number} depth - The depth of the texture.
  21915. * @param {number} [format=RGBAFormat] - The min filter value.
  21916. * @param {number} [type=UnsignedByteType] - The min filter value.
  21917. */
  21918. constructor( mipmaps, width, height, depth, format, type ) {
  21919. super( mipmaps, width, height, format, type );
  21920. /**
  21921. * This flag can be used for type testing.
  21922. *
  21923. * @type {boolean}
  21924. * @readonly
  21925. * @default true
  21926. */
  21927. this.isCompressedArrayTexture = true;
  21928. /**
  21929. * The image property of a compressed texture just defines its dimensions.
  21930. *
  21931. * @name CompressedArrayTexture#image
  21932. * @type {{width:number,height:number,depth:number}}
  21933. */
  21934. this.image.depth = depth;
  21935. /**
  21936. * This defines how the texture is wrapped in the depth and corresponds to
  21937. * *W* in UVW mapping.
  21938. *
  21939. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21940. * @default ClampToEdgeWrapping
  21941. */
  21942. this.wrapR = ClampToEdgeWrapping;
  21943. /**
  21944. * A set of all layers which need to be updated in the texture.
  21945. *
  21946. * @type {Set<number>}
  21947. */
  21948. this.layerUpdates = new Set();
  21949. }
  21950. /**
  21951. * Describes that a specific layer of the texture needs to be updated.
  21952. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21953. * entire compressed texture array is sent to the GPU. Marking specific
  21954. * layers will only transmit subsets of all mipmaps associated with a
  21955. * specific depth in the array which is often much more performant.
  21956. *
  21957. * @param {number} layerIndex - The layer index that should be updated.
  21958. */
  21959. addLayerUpdate( layerIndex ) {
  21960. this.layerUpdates.add( layerIndex );
  21961. }
  21962. /**
  21963. * Resets the layer updates registry.
  21964. */
  21965. clearLayerUpdates() {
  21966. this.layerUpdates.clear();
  21967. }
  21968. }
  21969. /**
  21970. * Creates a cube texture based on data in compressed form.
  21971. *
  21972. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21973. *
  21974. * @augments CompressedTexture
  21975. */
  21976. class CompressedCubeTexture extends CompressedTexture {
  21977. /**
  21978. * Constructs a new compressed texture.
  21979. *
  21980. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21981. * @param {number} [format=RGBAFormat] - The texture format.
  21982. * @param {number} [type=UnsignedByteType] - The texture type.
  21983. */
  21984. constructor( images, format, type ) {
  21985. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21986. /**
  21987. * This flag can be used for type testing.
  21988. *
  21989. * @type {boolean}
  21990. * @readonly
  21991. * @default true
  21992. */
  21993. this.isCompressedCubeTexture = true;
  21994. /**
  21995. * This flag can be used for type testing.
  21996. *
  21997. * @type {boolean}
  21998. * @readonly
  21999. * @default true
  22000. */
  22001. this.isCubeTexture = true;
  22002. this.image = images;
  22003. }
  22004. }
  22005. /**
  22006. * Creates a texture from a canvas element.
  22007. *
  22008. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22009. * to `true` immediately since a canvas can directly be used for rendering.
  22010. *
  22011. * @augments Texture
  22012. */
  22013. class CanvasTexture extends Texture {
  22014. /**
  22015. * Constructs a new texture.
  22016. *
  22017. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22018. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22019. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22020. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22021. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22022. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22023. * @param {number} [format=RGBAFormat] - The texture format.
  22024. * @param {number} [type=UnsignedByteType] - The texture type.
  22025. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22026. */
  22027. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22028. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22029. /**
  22030. * This flag can be used for type testing.
  22031. *
  22032. * @type {boolean}
  22033. * @readonly
  22034. * @default true
  22035. */
  22036. this.isCanvasTexture = true;
  22037. this.needsUpdate = true;
  22038. }
  22039. }
  22040. /**
  22041. * This class can be used to automatically save the depth information of a
  22042. * rendering into a texture.
  22043. *
  22044. * @augments Texture
  22045. */
  22046. class DepthTexture extends Texture {
  22047. /**
  22048. * Constructs a new depth texture.
  22049. *
  22050. * @param {number} width - The width of the texture.
  22051. * @param {number} height - The height of the texture.
  22052. * @param {number} [type=UnsignedIntType] - The texture type.
  22053. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22054. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22055. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22056. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22057. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22058. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22059. * @param {number} [format=DepthFormat] - The texture format.
  22060. * @param {number} [depth=1] - The depth of the texture.
  22061. */
  22062. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22063. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22064. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22065. }
  22066. const image = { width: width, height: height, depth: depth };
  22067. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22068. /**
  22069. * This flag can be used for type testing.
  22070. *
  22071. * @type {boolean}
  22072. * @readonly
  22073. * @default true
  22074. */
  22075. this.isDepthTexture = true;
  22076. /**
  22077. * If set to `true`, the texture is flipped along the vertical axis when
  22078. * uploaded to the GPU.
  22079. *
  22080. * Overwritten and set to `false` by default.
  22081. *
  22082. * @type {boolean}
  22083. * @default false
  22084. */
  22085. this.flipY = false;
  22086. /**
  22087. * Whether to generate mipmaps (if possible) for a texture.
  22088. *
  22089. * Overwritten and set to `false` by default.
  22090. *
  22091. * @type {boolean}
  22092. * @default false
  22093. */
  22094. this.generateMipmaps = false;
  22095. /**
  22096. * Code corresponding to the depth compare function.
  22097. *
  22098. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22099. * @default null
  22100. */
  22101. this.compareFunction = null;
  22102. }
  22103. copy( source ) {
  22104. super.copy( source );
  22105. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22106. this.compareFunction = source.compareFunction;
  22107. return this;
  22108. }
  22109. toJSON( meta ) {
  22110. const data = super.toJSON( meta );
  22111. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22112. return data;
  22113. }
  22114. }
  22115. /**
  22116. * A geometry class for representing a capsule.
  22117. *
  22118. * ```js
  22119. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22120. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22121. * const capsule = new THREE.Mesh( geometry, material );
  22122. * scene.add( capsule );
  22123. * ```
  22124. *
  22125. * @augments BufferGeometry
  22126. */
  22127. class CapsuleGeometry extends BufferGeometry {
  22128. /**
  22129. * Constructs a new capsule geometry.
  22130. *
  22131. * @param {number} [radius=1] - Radius of the capsule.
  22132. * @param {number} [height=1] - Height of the middle section.
  22133. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22134. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22135. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22136. */
  22137. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22138. super();
  22139. this.type = 'CapsuleGeometry';
  22140. /**
  22141. * Holds the constructor parameters that have been
  22142. * used to generate the geometry. Any modification
  22143. * after instantiation does not change the geometry.
  22144. *
  22145. * @type {Object}
  22146. */
  22147. this.parameters = {
  22148. radius: radius,
  22149. height: height,
  22150. capSegments: capSegments,
  22151. radialSegments: radialSegments,
  22152. heightSegments: heightSegments,
  22153. };
  22154. height = Math.max( 0, height );
  22155. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22156. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22157. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22158. // buffers
  22159. const indices = [];
  22160. const vertices = [];
  22161. const normals = [];
  22162. const uvs = [];
  22163. // helper variables
  22164. const halfHeight = height / 2;
  22165. const capArcLength = ( Math.PI / 2 ) * radius;
  22166. const cylinderPartLength = height;
  22167. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22168. const numVerticalSegments = capSegments * 2 + heightSegments;
  22169. const verticesPerRow = radialSegments + 1;
  22170. const normal = new Vector3();
  22171. const vertex = new Vector3();
  22172. // generate vertices, normals, and uvs
  22173. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22174. let currentArcLength = 0;
  22175. let profileY = 0;
  22176. let profileRadius = 0;
  22177. let normalYComponent = 0;
  22178. if ( iy <= capSegments ) {
  22179. // bottom cap
  22180. const segmentProgress = iy / capSegments;
  22181. const angle = ( segmentProgress * Math.PI ) / 2;
  22182. profileY = - halfHeight - radius * Math.cos( angle );
  22183. profileRadius = radius * Math.sin( angle );
  22184. normalYComponent = - radius * Math.cos( angle );
  22185. currentArcLength = segmentProgress * capArcLength;
  22186. } else if ( iy <= capSegments + heightSegments ) {
  22187. // middle section
  22188. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22189. profileY = - halfHeight + segmentProgress * height;
  22190. profileRadius = radius;
  22191. normalYComponent = 0;
  22192. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22193. } else {
  22194. // top cap
  22195. const segmentProgress =
  22196. ( iy - capSegments - heightSegments ) / capSegments;
  22197. const angle = ( segmentProgress * Math.PI ) / 2;
  22198. profileY = halfHeight + radius * Math.sin( angle );
  22199. profileRadius = radius * Math.cos( angle );
  22200. normalYComponent = radius * Math.sin( angle );
  22201. currentArcLength =
  22202. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22203. }
  22204. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22205. // special case for the poles
  22206. let uOffset = 0;
  22207. if ( iy === 0 ) {
  22208. uOffset = 0.5 / radialSegments;
  22209. } else if ( iy === numVerticalSegments ) {
  22210. uOffset = -0.5 / radialSegments;
  22211. }
  22212. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22213. const u = ix / radialSegments;
  22214. const theta = u * Math.PI * 2;
  22215. const sinTheta = Math.sin( theta );
  22216. const cosTheta = Math.cos( theta );
  22217. // vertex
  22218. vertex.x = - profileRadius * cosTheta;
  22219. vertex.y = profileY;
  22220. vertex.z = profileRadius * sinTheta;
  22221. vertices.push( vertex.x, vertex.y, vertex.z );
  22222. // normal
  22223. normal.set(
  22224. - profileRadius * cosTheta,
  22225. normalYComponent,
  22226. profileRadius * sinTheta
  22227. );
  22228. normal.normalize();
  22229. normals.push( normal.x, normal.y, normal.z );
  22230. // uv
  22231. uvs.push( u + uOffset, v );
  22232. }
  22233. if ( iy > 0 ) {
  22234. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22235. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22236. const i1 = prevIndexRow + ix;
  22237. const i2 = prevIndexRow + ix + 1;
  22238. const i3 = iy * verticesPerRow + ix;
  22239. const i4 = iy * verticesPerRow + ix + 1;
  22240. indices.push( i1, i2, i3 );
  22241. indices.push( i2, i4, i3 );
  22242. }
  22243. }
  22244. }
  22245. // build geometry
  22246. this.setIndex( indices );
  22247. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22248. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22249. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22250. }
  22251. copy( source ) {
  22252. super.copy( source );
  22253. this.parameters = Object.assign( {}, source.parameters );
  22254. return this;
  22255. }
  22256. /**
  22257. * Factory method for creating an instance of this class from the given
  22258. * JSON object.
  22259. *
  22260. * @param {Object} data - A JSON object representing the serialized geometry.
  22261. * @return {CapsuleGeometry} A new instance.
  22262. */
  22263. static fromJSON( data ) {
  22264. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22265. }
  22266. }
  22267. /**
  22268. * A simple shape of Euclidean geometry. It is constructed from a
  22269. * number of triangular segments that are oriented around a central point and
  22270. * extend as far out as a given radius. It is built counter-clockwise from a
  22271. * start angle and a given central angle. It can also be used to create
  22272. * regular polygons, where the number of segments determines the number of
  22273. * sides.
  22274. *
  22275. * ```js
  22276. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22277. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22278. * const circle = new THREE.Mesh( geometry, material );
  22279. * scene.add( circle )
  22280. * ```
  22281. *
  22282. * @augments BufferGeometry
  22283. */
  22284. class CircleGeometry extends BufferGeometry {
  22285. /**
  22286. * Constructs a new circle geometry.
  22287. *
  22288. * @param {number} [radius=1] - Radius of the circle.
  22289. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22290. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22291. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22292. * of the circular sector in radians. The default value results in a complete circle.
  22293. */
  22294. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22295. super();
  22296. this.type = 'CircleGeometry';
  22297. /**
  22298. * Holds the constructor parameters that have been
  22299. * used to generate the geometry. Any modification
  22300. * after instantiation does not change the geometry.
  22301. *
  22302. * @type {Object}
  22303. */
  22304. this.parameters = {
  22305. radius: radius,
  22306. segments: segments,
  22307. thetaStart: thetaStart,
  22308. thetaLength: thetaLength
  22309. };
  22310. segments = Math.max( 3, segments );
  22311. // buffers
  22312. const indices = [];
  22313. const vertices = [];
  22314. const normals = [];
  22315. const uvs = [];
  22316. // helper variables
  22317. const vertex = new Vector3();
  22318. const uv = new Vector2();
  22319. // center point
  22320. vertices.push( 0, 0, 0 );
  22321. normals.push( 0, 0, 1 );
  22322. uvs.push( 0.5, 0.5 );
  22323. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22324. const segment = thetaStart + s / segments * thetaLength;
  22325. // vertex
  22326. vertex.x = radius * Math.cos( segment );
  22327. vertex.y = radius * Math.sin( segment );
  22328. vertices.push( vertex.x, vertex.y, vertex.z );
  22329. // normal
  22330. normals.push( 0, 0, 1 );
  22331. // uvs
  22332. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22333. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22334. uvs.push( uv.x, uv.y );
  22335. }
  22336. // indices
  22337. for ( let i = 1; i <= segments; i ++ ) {
  22338. indices.push( i, i + 1, 0 );
  22339. }
  22340. // build geometry
  22341. this.setIndex( indices );
  22342. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22343. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22344. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22345. }
  22346. copy( source ) {
  22347. super.copy( source );
  22348. this.parameters = Object.assign( {}, source.parameters );
  22349. return this;
  22350. }
  22351. /**
  22352. * Factory method for creating an instance of this class from the given
  22353. * JSON object.
  22354. *
  22355. * @param {Object} data - A JSON object representing the serialized geometry.
  22356. * @return {CircleGeometry} A new instance.
  22357. */
  22358. static fromJSON( data ) {
  22359. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22360. }
  22361. }
  22362. /**
  22363. * A geometry class for representing a cylinder.
  22364. *
  22365. * ```js
  22366. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22367. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22368. * const cylinder = new THREE.Mesh( geometry, material );
  22369. * scene.add( cylinder );
  22370. * ```
  22371. *
  22372. * @augments BufferGeometry
  22373. */
  22374. class CylinderGeometry extends BufferGeometry {
  22375. /**
  22376. * Constructs a new cylinder geometry.
  22377. *
  22378. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22379. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22380. * @param {number} [height=1] - Height of the cylinder.
  22381. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22382. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22383. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22384. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22385. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22386. * The default value results in a complete cylinder.
  22387. */
  22388. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22389. super();
  22390. this.type = 'CylinderGeometry';
  22391. /**
  22392. * Holds the constructor parameters that have been
  22393. * used to generate the geometry. Any modification
  22394. * after instantiation does not change the geometry.
  22395. *
  22396. * @type {Object}
  22397. */
  22398. this.parameters = {
  22399. radiusTop: radiusTop,
  22400. radiusBottom: radiusBottom,
  22401. height: height,
  22402. radialSegments: radialSegments,
  22403. heightSegments: heightSegments,
  22404. openEnded: openEnded,
  22405. thetaStart: thetaStart,
  22406. thetaLength: thetaLength
  22407. };
  22408. const scope = this;
  22409. radialSegments = Math.floor( radialSegments );
  22410. heightSegments = Math.floor( heightSegments );
  22411. // buffers
  22412. const indices = [];
  22413. const vertices = [];
  22414. const normals = [];
  22415. const uvs = [];
  22416. // helper variables
  22417. let index = 0;
  22418. const indexArray = [];
  22419. const halfHeight = height / 2;
  22420. let groupStart = 0;
  22421. // generate geometry
  22422. generateTorso();
  22423. if ( openEnded === false ) {
  22424. if ( radiusTop > 0 ) generateCap( true );
  22425. if ( radiusBottom > 0 ) generateCap( false );
  22426. }
  22427. // build geometry
  22428. this.setIndex( indices );
  22429. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22430. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22431. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22432. function generateTorso() {
  22433. const normal = new Vector3();
  22434. const vertex = new Vector3();
  22435. let groupCount = 0;
  22436. // this will be used to calculate the normal
  22437. const slope = ( radiusBottom - radiusTop ) / height;
  22438. // generate vertices, normals and uvs
  22439. for ( let y = 0; y <= heightSegments; y ++ ) {
  22440. const indexRow = [];
  22441. const v = y / heightSegments;
  22442. // calculate the radius of the current row
  22443. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22444. for ( let x = 0; x <= radialSegments; x ++ ) {
  22445. const u = x / radialSegments;
  22446. const theta = u * thetaLength + thetaStart;
  22447. const sinTheta = Math.sin( theta );
  22448. const cosTheta = Math.cos( theta );
  22449. // vertex
  22450. vertex.x = radius * sinTheta;
  22451. vertex.y = - v * height + halfHeight;
  22452. vertex.z = radius * cosTheta;
  22453. vertices.push( vertex.x, vertex.y, vertex.z );
  22454. // normal
  22455. normal.set( sinTheta, slope, cosTheta ).normalize();
  22456. normals.push( normal.x, normal.y, normal.z );
  22457. // uv
  22458. uvs.push( u, 1 - v );
  22459. // save index of vertex in respective row
  22460. indexRow.push( index ++ );
  22461. }
  22462. // now save vertices of the row in our index array
  22463. indexArray.push( indexRow );
  22464. }
  22465. // generate indices
  22466. for ( let x = 0; x < radialSegments; x ++ ) {
  22467. for ( let y = 0; y < heightSegments; y ++ ) {
  22468. // we use the index array to access the correct indices
  22469. const a = indexArray[ y ][ x ];
  22470. const b = indexArray[ y + 1 ][ x ];
  22471. const c = indexArray[ y + 1 ][ x + 1 ];
  22472. const d = indexArray[ y ][ x + 1 ];
  22473. // faces
  22474. if ( radiusTop > 0 || y !== 0 ) {
  22475. indices.push( a, b, d );
  22476. groupCount += 3;
  22477. }
  22478. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22479. indices.push( b, c, d );
  22480. groupCount += 3;
  22481. }
  22482. }
  22483. }
  22484. // add a group to the geometry. this will ensure multi material support
  22485. scope.addGroup( groupStart, groupCount, 0 );
  22486. // calculate new start value for groups
  22487. groupStart += groupCount;
  22488. }
  22489. function generateCap( top ) {
  22490. // save the index of the first center vertex
  22491. const centerIndexStart = index;
  22492. const uv = new Vector2();
  22493. const vertex = new Vector3();
  22494. let groupCount = 0;
  22495. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22496. const sign = ( top === true ) ? 1 : -1;
  22497. // first we generate the center vertex data of the cap.
  22498. // because the geometry needs one set of uvs per face,
  22499. // we must generate a center vertex per face/segment
  22500. for ( let x = 1; x <= radialSegments; x ++ ) {
  22501. // vertex
  22502. vertices.push( 0, halfHeight * sign, 0 );
  22503. // normal
  22504. normals.push( 0, sign, 0 );
  22505. // uv
  22506. uvs.push( 0.5, 0.5 );
  22507. // increase index
  22508. index ++;
  22509. }
  22510. // save the index of the last center vertex
  22511. const centerIndexEnd = index;
  22512. // now we generate the surrounding vertices, normals and uvs
  22513. for ( let x = 0; x <= radialSegments; x ++ ) {
  22514. const u = x / radialSegments;
  22515. const theta = u * thetaLength + thetaStart;
  22516. const cosTheta = Math.cos( theta );
  22517. const sinTheta = Math.sin( theta );
  22518. // vertex
  22519. vertex.x = radius * sinTheta;
  22520. vertex.y = halfHeight * sign;
  22521. vertex.z = radius * cosTheta;
  22522. vertices.push( vertex.x, vertex.y, vertex.z );
  22523. // normal
  22524. normals.push( 0, sign, 0 );
  22525. // uv
  22526. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22527. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22528. uvs.push( uv.x, uv.y );
  22529. // increase index
  22530. index ++;
  22531. }
  22532. // generate indices
  22533. for ( let x = 0; x < radialSegments; x ++ ) {
  22534. const c = centerIndexStart + x;
  22535. const i = centerIndexEnd + x;
  22536. if ( top === true ) {
  22537. // face top
  22538. indices.push( i, i + 1, c );
  22539. } else {
  22540. // face bottom
  22541. indices.push( i + 1, i, c );
  22542. }
  22543. groupCount += 3;
  22544. }
  22545. // add a group to the geometry. this will ensure multi material support
  22546. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22547. // calculate new start value for groups
  22548. groupStart += groupCount;
  22549. }
  22550. }
  22551. copy( source ) {
  22552. super.copy( source );
  22553. this.parameters = Object.assign( {}, source.parameters );
  22554. return this;
  22555. }
  22556. /**
  22557. * Factory method for creating an instance of this class from the given
  22558. * JSON object.
  22559. *
  22560. * @param {Object} data - A JSON object representing the serialized geometry.
  22561. * @return {CylinderGeometry} A new instance.
  22562. */
  22563. static fromJSON( data ) {
  22564. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22565. }
  22566. }
  22567. /**
  22568. * A geometry class for representing a cone.
  22569. *
  22570. * ```js
  22571. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22572. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22573. * const cone = new THREE.Mesh(geometry, material );
  22574. * scene.add( cone );
  22575. * ```
  22576. *
  22577. * @augments CylinderGeometry
  22578. */
  22579. class ConeGeometry extends CylinderGeometry {
  22580. /**
  22581. * Constructs a new cone geometry.
  22582. *
  22583. * @param {number} [radius=1] - Radius of the cone base.
  22584. * @param {number} [height=1] - Height of the cone.
  22585. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22586. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22587. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22588. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22589. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22590. * The default value results in a complete cone.
  22591. */
  22592. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22593. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22594. this.type = 'ConeGeometry';
  22595. /**
  22596. * Holds the constructor parameters that have been
  22597. * used to generate the geometry. Any modification
  22598. * after instantiation does not change the geometry.
  22599. *
  22600. * @type {Object}
  22601. */
  22602. this.parameters = {
  22603. radius: radius,
  22604. height: height,
  22605. radialSegments: radialSegments,
  22606. heightSegments: heightSegments,
  22607. openEnded: openEnded,
  22608. thetaStart: thetaStart,
  22609. thetaLength: thetaLength
  22610. };
  22611. }
  22612. /**
  22613. * Factory method for creating an instance of this class from the given
  22614. * JSON object.
  22615. *
  22616. * @param {Object} data - A JSON object representing the serialized geometry.
  22617. * @return {ConeGeometry} A new instance.
  22618. */
  22619. static fromJSON( data ) {
  22620. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22621. }
  22622. }
  22623. /**
  22624. * A polyhedron is a solid in three dimensions with flat faces. This class
  22625. * will take an array of vertices, project them onto a sphere, and then
  22626. * divide them up to the desired level of detail.
  22627. *
  22628. * @augments BufferGeometry
  22629. */
  22630. class PolyhedronGeometry extends BufferGeometry {
  22631. /**
  22632. * Constructs a new polyhedron geometry.
  22633. *
  22634. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22635. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22636. * @param {number} [radius=1] - The radius of the shape.
  22637. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22638. */
  22639. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22640. super();
  22641. this.type = 'PolyhedronGeometry';
  22642. /**
  22643. * Holds the constructor parameters that have been
  22644. * used to generate the geometry. Any modification
  22645. * after instantiation does not change the geometry.
  22646. *
  22647. * @type {Object}
  22648. */
  22649. this.parameters = {
  22650. vertices: vertices,
  22651. indices: indices,
  22652. radius: radius,
  22653. detail: detail
  22654. };
  22655. // default buffer data
  22656. const vertexBuffer = [];
  22657. const uvBuffer = [];
  22658. // the subdivision creates the vertex buffer data
  22659. subdivide( detail );
  22660. // all vertices should lie on a conceptual sphere with a given radius
  22661. applyRadius( radius );
  22662. // finally, create the uv data
  22663. generateUVs();
  22664. // build non-indexed geometry
  22665. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22666. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22667. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22668. if ( detail === 0 ) {
  22669. this.computeVertexNormals(); // flat normals
  22670. } else {
  22671. this.normalizeNormals(); // smooth normals
  22672. }
  22673. // helper functions
  22674. function subdivide( detail ) {
  22675. const a = new Vector3();
  22676. const b = new Vector3();
  22677. const c = new Vector3();
  22678. // iterate over all faces and apply a subdivision with the given detail value
  22679. for ( let i = 0; i < indices.length; i += 3 ) {
  22680. // get the vertices of the face
  22681. getVertexByIndex( indices[ i + 0 ], a );
  22682. getVertexByIndex( indices[ i + 1 ], b );
  22683. getVertexByIndex( indices[ i + 2 ], c );
  22684. // perform subdivision
  22685. subdivideFace( a, b, c, detail );
  22686. }
  22687. }
  22688. function subdivideFace( a, b, c, detail ) {
  22689. const cols = detail + 1;
  22690. // we use this multidimensional array as a data structure for creating the subdivision
  22691. const v = [];
  22692. // construct all of the vertices for this subdivision
  22693. for ( let i = 0; i <= cols; i ++ ) {
  22694. v[ i ] = [];
  22695. const aj = a.clone().lerp( c, i / cols );
  22696. const bj = b.clone().lerp( c, i / cols );
  22697. const rows = cols - i;
  22698. for ( let j = 0; j <= rows; j ++ ) {
  22699. if ( j === 0 && i === cols ) {
  22700. v[ i ][ j ] = aj;
  22701. } else {
  22702. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22703. }
  22704. }
  22705. }
  22706. // construct all of the faces
  22707. for ( let i = 0; i < cols; i ++ ) {
  22708. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22709. const k = Math.floor( j / 2 );
  22710. if ( j % 2 === 0 ) {
  22711. pushVertex( v[ i ][ k + 1 ] );
  22712. pushVertex( v[ i + 1 ][ k ] );
  22713. pushVertex( v[ i ][ k ] );
  22714. } else {
  22715. pushVertex( v[ i ][ k + 1 ] );
  22716. pushVertex( v[ i + 1 ][ k + 1 ] );
  22717. pushVertex( v[ i + 1 ][ k ] );
  22718. }
  22719. }
  22720. }
  22721. }
  22722. function applyRadius( radius ) {
  22723. const vertex = new Vector3();
  22724. // iterate over the entire buffer and apply the radius to each vertex
  22725. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22726. vertex.x = vertexBuffer[ i + 0 ];
  22727. vertex.y = vertexBuffer[ i + 1 ];
  22728. vertex.z = vertexBuffer[ i + 2 ];
  22729. vertex.normalize().multiplyScalar( radius );
  22730. vertexBuffer[ i + 0 ] = vertex.x;
  22731. vertexBuffer[ i + 1 ] = vertex.y;
  22732. vertexBuffer[ i + 2 ] = vertex.z;
  22733. }
  22734. }
  22735. function generateUVs() {
  22736. const vertex = new Vector3();
  22737. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22738. vertex.x = vertexBuffer[ i + 0 ];
  22739. vertex.y = vertexBuffer[ i + 1 ];
  22740. vertex.z = vertexBuffer[ i + 2 ];
  22741. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22742. const v = inclination( vertex ) / Math.PI + 0.5;
  22743. uvBuffer.push( u, 1 - v );
  22744. }
  22745. correctUVs();
  22746. correctSeam();
  22747. }
  22748. function correctSeam() {
  22749. // handle case when face straddles the seam, see #3269
  22750. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22751. // uv data of a single face
  22752. const x0 = uvBuffer[ i + 0 ];
  22753. const x1 = uvBuffer[ i + 2 ];
  22754. const x2 = uvBuffer[ i + 4 ];
  22755. const max = Math.max( x0, x1, x2 );
  22756. const min = Math.min( x0, x1, x2 );
  22757. // 0.9 is somewhat arbitrary
  22758. if ( max > 0.9 && min < 0.1 ) {
  22759. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22760. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22761. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22762. }
  22763. }
  22764. }
  22765. function pushVertex( vertex ) {
  22766. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22767. }
  22768. function getVertexByIndex( index, vertex ) {
  22769. const stride = index * 3;
  22770. vertex.x = vertices[ stride + 0 ];
  22771. vertex.y = vertices[ stride + 1 ];
  22772. vertex.z = vertices[ stride + 2 ];
  22773. }
  22774. function correctUVs() {
  22775. const a = new Vector3();
  22776. const b = new Vector3();
  22777. const c = new Vector3();
  22778. const centroid = new Vector3();
  22779. const uvA = new Vector2();
  22780. const uvB = new Vector2();
  22781. const uvC = new Vector2();
  22782. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22783. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22784. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22785. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22786. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22787. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22788. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22789. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22790. const azi = azimuth( centroid );
  22791. correctUV( uvA, j + 0, a, azi );
  22792. correctUV( uvB, j + 2, b, azi );
  22793. correctUV( uvC, j + 4, c, azi );
  22794. }
  22795. }
  22796. function correctUV( uv, stride, vector, azimuth ) {
  22797. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22798. uvBuffer[ stride ] = uv.x - 1;
  22799. }
  22800. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22801. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22802. }
  22803. }
  22804. // Angle around the Y axis, counter-clockwise when looking from above.
  22805. function azimuth( vector ) {
  22806. return Math.atan2( vector.z, - vector.x );
  22807. }
  22808. // Angle above the XZ plane.
  22809. function inclination( vector ) {
  22810. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22811. }
  22812. }
  22813. copy( source ) {
  22814. super.copy( source );
  22815. this.parameters = Object.assign( {}, source.parameters );
  22816. return this;
  22817. }
  22818. /**
  22819. * Factory method for creating an instance of this class from the given
  22820. * JSON object.
  22821. *
  22822. * @param {Object} data - A JSON object representing the serialized geometry.
  22823. * @return {PolyhedronGeometry} A new instance.
  22824. */
  22825. static fromJSON( data ) {
  22826. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22827. }
  22828. }
  22829. /**
  22830. * A geometry class for representing a dodecahedron.
  22831. *
  22832. * ```js
  22833. * const geometry = new THREE.DodecahedronGeometry();
  22834. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22835. * const dodecahedron = new THREE.Mesh( geometry, material );
  22836. * scene.add( dodecahedron );
  22837. * ```
  22838. *
  22839. * @augments PolyhedronGeometry
  22840. */
  22841. class DodecahedronGeometry extends PolyhedronGeometry {
  22842. /**
  22843. * Constructs a new dodecahedron geometry.
  22844. *
  22845. * @param {number} [radius=1] - Radius of the dodecahedron.
  22846. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22847. */
  22848. constructor( radius = 1, detail = 0 ) {
  22849. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22850. const r = 1 / t;
  22851. const vertices = [
  22852. // (±1, ±1, ±1)
  22853. -1, -1, -1, -1, -1, 1,
  22854. -1, 1, -1, -1, 1, 1,
  22855. 1, -1, -1, 1, -1, 1,
  22856. 1, 1, -1, 1, 1, 1,
  22857. // (0, ±1/φ, ±φ)
  22858. 0, - r, - t, 0, - r, t,
  22859. 0, r, - t, 0, r, t,
  22860. // (±1/φ, ±φ, 0)
  22861. - r, - t, 0, - r, t, 0,
  22862. r, - t, 0, r, t, 0,
  22863. // (±φ, 0, ±1/φ)
  22864. - t, 0, - r, t, 0, - r,
  22865. - t, 0, r, t, 0, r
  22866. ];
  22867. const indices = [
  22868. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22869. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22870. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22871. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22872. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22873. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22874. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22875. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22876. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22877. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22878. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22879. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22880. ];
  22881. super( vertices, indices, radius, detail );
  22882. this.type = 'DodecahedronGeometry';
  22883. /**
  22884. * Holds the constructor parameters that have been
  22885. * used to generate the geometry. Any modification
  22886. * after instantiation does not change the geometry.
  22887. *
  22888. * @type {Object}
  22889. */
  22890. this.parameters = {
  22891. radius: radius,
  22892. detail: detail
  22893. };
  22894. }
  22895. /**
  22896. * Factory method for creating an instance of this class from the given
  22897. * JSON object.
  22898. *
  22899. * @param {Object} data - A JSON object representing the serialized geometry.
  22900. * @return {DodecahedronGeometry} A new instance.
  22901. */
  22902. static fromJSON( data ) {
  22903. return new DodecahedronGeometry( data.radius, data.detail );
  22904. }
  22905. }
  22906. const _v0 = /*@__PURE__*/ new Vector3();
  22907. const _v1$1 = /*@__PURE__*/ new Vector3();
  22908. const _normal = /*@__PURE__*/ new Vector3();
  22909. const _triangle = /*@__PURE__*/ new Triangle();
  22910. /**
  22911. * Can be used as a helper object to view the edges of a geometry.
  22912. *
  22913. * ```js
  22914. * const geometry = new THREE.BoxGeometry();
  22915. * const edges = new THREE.EdgesGeometry( geometry );
  22916. * const line = new THREE.LineSegments( edges );
  22917. * scene.add( line );
  22918. * ```
  22919. *
  22920. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22921. *
  22922. * @augments BufferGeometry
  22923. */
  22924. class EdgesGeometry extends BufferGeometry {
  22925. /**
  22926. * Constructs a new edges geometry.
  22927. *
  22928. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22929. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22930. * between the face normals of the adjoining faces exceeds this value.
  22931. */
  22932. constructor( geometry = null, thresholdAngle = 1 ) {
  22933. super();
  22934. this.type = 'EdgesGeometry';
  22935. /**
  22936. * Holds the constructor parameters that have been
  22937. * used to generate the geometry. Any modification
  22938. * after instantiation does not change the geometry.
  22939. *
  22940. * @type {Object}
  22941. */
  22942. this.parameters = {
  22943. geometry: geometry,
  22944. thresholdAngle: thresholdAngle
  22945. };
  22946. if ( geometry !== null ) {
  22947. const precisionPoints = 4;
  22948. const precision = Math.pow( 10, precisionPoints );
  22949. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22950. const indexAttr = geometry.getIndex();
  22951. const positionAttr = geometry.getAttribute( 'position' );
  22952. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22953. const indexArr = [ 0, 0, 0 ];
  22954. const vertKeys = [ 'a', 'b', 'c' ];
  22955. const hashes = new Array( 3 );
  22956. const edgeData = {};
  22957. const vertices = [];
  22958. for ( let i = 0; i < indexCount; i += 3 ) {
  22959. if ( indexAttr ) {
  22960. indexArr[ 0 ] = indexAttr.getX( i );
  22961. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22962. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22963. } else {
  22964. indexArr[ 0 ] = i;
  22965. indexArr[ 1 ] = i + 1;
  22966. indexArr[ 2 ] = i + 2;
  22967. }
  22968. const { a, b, c } = _triangle;
  22969. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22970. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22971. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22972. _triangle.getNormal( _normal );
  22973. // create hashes for the edge from the vertices
  22974. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22975. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22976. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22977. // skip degenerate triangles
  22978. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22979. continue;
  22980. }
  22981. // iterate over every edge
  22982. for ( let j = 0; j < 3; j ++ ) {
  22983. // get the first and next vertex making up the edge
  22984. const jNext = ( j + 1 ) % 3;
  22985. const vecHash0 = hashes[ j ];
  22986. const vecHash1 = hashes[ jNext ];
  22987. const v0 = _triangle[ vertKeys[ j ] ];
  22988. const v1 = _triangle[ vertKeys[ jNext ] ];
  22989. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22990. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22991. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22992. // if we found a sibling edge add it into the vertex array if
  22993. // it meets the angle threshold and delete the edge from the map.
  22994. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22995. vertices.push( v0.x, v0.y, v0.z );
  22996. vertices.push( v1.x, v1.y, v1.z );
  22997. }
  22998. edgeData[ reverseHash ] = null;
  22999. } else if ( ! ( hash in edgeData ) ) {
  23000. // if we've already got an edge here then skip adding a new one
  23001. edgeData[ hash ] = {
  23002. index0: indexArr[ j ],
  23003. index1: indexArr[ jNext ],
  23004. normal: _normal.clone(),
  23005. };
  23006. }
  23007. }
  23008. }
  23009. // iterate over all remaining, unmatched edges and add them to the vertex array
  23010. for ( const key in edgeData ) {
  23011. if ( edgeData[ key ] ) {
  23012. const { index0, index1 } = edgeData[ key ];
  23013. _v0.fromBufferAttribute( positionAttr, index0 );
  23014. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23015. vertices.push( _v0.x, _v0.y, _v0.z );
  23016. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23017. }
  23018. }
  23019. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23020. }
  23021. }
  23022. copy( source ) {
  23023. super.copy( source );
  23024. this.parameters = Object.assign( {}, source.parameters );
  23025. return this;
  23026. }
  23027. }
  23028. /**
  23029. * An abstract base class for creating an analytic curve object that contains methods
  23030. * for interpolation.
  23031. *
  23032. * @abstract
  23033. */
  23034. class Curve {
  23035. /**
  23036. * Constructs a new curve.
  23037. */
  23038. constructor() {
  23039. /**
  23040. * The type property is used for detecting the object type
  23041. * in context of serialization/deserialization.
  23042. *
  23043. * @type {string}
  23044. * @readonly
  23045. */
  23046. this.type = 'Curve';
  23047. /**
  23048. * This value determines the amount of divisions when calculating the
  23049. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23050. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23051. * recommended to increase the value of this property if the curve is very large.
  23052. *
  23053. * @type {number}
  23054. * @default 200
  23055. */
  23056. this.arcLengthDivisions = 200;
  23057. /**
  23058. * Must be set to `true` if the curve parameters have changed.
  23059. *
  23060. * @type {boolean}
  23061. * @default false
  23062. */
  23063. this.needsUpdate = false;
  23064. /**
  23065. * An internal cache that holds precomputed curve length values.
  23066. *
  23067. * @private
  23068. * @type {?Array<number>}
  23069. * @default null
  23070. */
  23071. this.cacheArcLengths = null;
  23072. }
  23073. /**
  23074. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23075. * for the given interpolation factor.
  23076. *
  23077. * @abstract
  23078. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23079. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23080. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23081. */
  23082. getPoint( /* t, optionalTarget */ ) {
  23083. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  23084. }
  23085. /**
  23086. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23087. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23088. * of the curve which equidistant samples.
  23089. *
  23090. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23091. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23092. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23093. */
  23094. getPointAt( u, optionalTarget ) {
  23095. const t = this.getUtoTmapping( u );
  23096. return this.getPoint( t, optionalTarget );
  23097. }
  23098. /**
  23099. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23100. * the curve shape.
  23101. *
  23102. * @param {number} [divisions=5] - The number of divisions.
  23103. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23104. */
  23105. getPoints( divisions = 5 ) {
  23106. const points = [];
  23107. for ( let d = 0; d <= divisions; d ++ ) {
  23108. points.push( this.getPoint( d / divisions ) );
  23109. }
  23110. return points;
  23111. }
  23112. // Get sequence of points using getPointAt( u )
  23113. /**
  23114. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23115. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23116. * curve.
  23117. *
  23118. * @param {number} [divisions=5] - The number of divisions.
  23119. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23120. */
  23121. getSpacedPoints( divisions = 5 ) {
  23122. const points = [];
  23123. for ( let d = 0; d <= divisions; d ++ ) {
  23124. points.push( this.getPointAt( d / divisions ) );
  23125. }
  23126. return points;
  23127. }
  23128. /**
  23129. * Returns the total arc length of the curve.
  23130. *
  23131. * @return {number} The length of the curve.
  23132. */
  23133. getLength() {
  23134. const lengths = this.getLengths();
  23135. return lengths[ lengths.length - 1 ];
  23136. }
  23137. /**
  23138. * Returns an array of cumulative segment lengths of the curve.
  23139. *
  23140. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23141. * @return {Array<number>} An array holding the cumulative segment lengths.
  23142. */
  23143. getLengths( divisions = this.arcLengthDivisions ) {
  23144. if ( this.cacheArcLengths &&
  23145. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23146. ! this.needsUpdate ) {
  23147. return this.cacheArcLengths;
  23148. }
  23149. this.needsUpdate = false;
  23150. const cache = [];
  23151. let current, last = this.getPoint( 0 );
  23152. let sum = 0;
  23153. cache.push( 0 );
  23154. for ( let p = 1; p <= divisions; p ++ ) {
  23155. current = this.getPoint( p / divisions );
  23156. sum += current.distanceTo( last );
  23157. cache.push( sum );
  23158. last = current;
  23159. }
  23160. this.cacheArcLengths = cache;
  23161. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23162. }
  23163. /**
  23164. * Update the cumulative segment distance cache. The method must be called
  23165. * every time curve parameters are changed. If an updated curve is part of a
  23166. * composed curve like {@link CurvePath}, this method must be called on the
  23167. * composed curve, too.
  23168. */
  23169. updateArcLengths() {
  23170. this.needsUpdate = true;
  23171. this.getLengths();
  23172. }
  23173. /**
  23174. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23175. * interpolation factor in the same range that can be ued to sample equidistant points
  23176. * from a curve.
  23177. *
  23178. * @param {number} u - The interpolation factor.
  23179. * @param {?number} distance - An optional distance on the curve.
  23180. * @return {number} The updated interpolation factor.
  23181. */
  23182. getUtoTmapping( u, distance = null ) {
  23183. const arcLengths = this.getLengths();
  23184. let i = 0;
  23185. const il = arcLengths.length;
  23186. let targetArcLength; // The targeted u distance value to get
  23187. if ( distance ) {
  23188. targetArcLength = distance;
  23189. } else {
  23190. targetArcLength = u * arcLengths[ il - 1 ];
  23191. }
  23192. // binary search for the index with largest value smaller than target u distance
  23193. let low = 0, high = il - 1, comparison;
  23194. while ( low <= high ) {
  23195. 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
  23196. comparison = arcLengths[ i ] - targetArcLength;
  23197. if ( comparison < 0 ) {
  23198. low = i + 1;
  23199. } else if ( comparison > 0 ) {
  23200. high = i - 1;
  23201. } else {
  23202. high = i;
  23203. break;
  23204. // DONE
  23205. }
  23206. }
  23207. i = high;
  23208. if ( arcLengths[ i ] === targetArcLength ) {
  23209. return i / ( il - 1 );
  23210. }
  23211. // we could get finer grain at lengths, or use simple interpolation between two points
  23212. const lengthBefore = arcLengths[ i ];
  23213. const lengthAfter = arcLengths[ i + 1 ];
  23214. const segmentLength = lengthAfter - lengthBefore;
  23215. // determine where we are between the 'before' and 'after' points
  23216. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23217. // add that fractional amount to t
  23218. const t = ( i + segmentFraction ) / ( il - 1 );
  23219. return t;
  23220. }
  23221. /**
  23222. * Returns a unit vector tangent for the given interpolation factor.
  23223. * If the derived curve does not implement its tangent derivation,
  23224. * two points a small delta apart will be used to find its gradient
  23225. * which seems to give a reasonable approximation.
  23226. *
  23227. * @param {number} t - The interpolation factor.
  23228. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23229. * @return {(Vector2|Vector3)} The tangent vector.
  23230. */
  23231. getTangent( t, optionalTarget ) {
  23232. const delta = 0.0001;
  23233. let t1 = t - delta;
  23234. let t2 = t + delta;
  23235. // Capping in case of danger
  23236. if ( t1 < 0 ) t1 = 0;
  23237. if ( t2 > 1 ) t2 = 1;
  23238. const pt1 = this.getPoint( t1 );
  23239. const pt2 = this.getPoint( t2 );
  23240. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23241. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23242. return tangent;
  23243. }
  23244. /**
  23245. * Same as {@link Curve#getTangent} but with equidistant samples.
  23246. *
  23247. * @param {number} u - The interpolation factor.
  23248. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23249. * @return {(Vector2|Vector3)} The tangent vector.
  23250. * @see {@link Curve#getPointAt}
  23251. */
  23252. getTangentAt( u, optionalTarget ) {
  23253. const t = this.getUtoTmapping( u );
  23254. return this.getTangent( t, optionalTarget );
  23255. }
  23256. /**
  23257. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23258. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23259. *
  23260. * @param {number} segments - The number of segments.
  23261. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23262. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23263. */
  23264. computeFrenetFrames( segments, closed = false ) {
  23265. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23266. const normal = new Vector3();
  23267. const tangents = [];
  23268. const normals = [];
  23269. const binormals = [];
  23270. const vec = new Vector3();
  23271. const mat = new Matrix4();
  23272. // compute the tangent vectors for each segment on the curve
  23273. for ( let i = 0; i <= segments; i ++ ) {
  23274. const u = i / segments;
  23275. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23276. }
  23277. // select an initial normal vector perpendicular to the first tangent vector,
  23278. // and in the direction of the minimum tangent xyz component
  23279. normals[ 0 ] = new Vector3();
  23280. binormals[ 0 ] = new Vector3();
  23281. let min = Number.MAX_VALUE;
  23282. const tx = Math.abs( tangents[ 0 ].x );
  23283. const ty = Math.abs( tangents[ 0 ].y );
  23284. const tz = Math.abs( tangents[ 0 ].z );
  23285. if ( tx <= min ) {
  23286. min = tx;
  23287. normal.set( 1, 0, 0 );
  23288. }
  23289. if ( ty <= min ) {
  23290. min = ty;
  23291. normal.set( 0, 1, 0 );
  23292. }
  23293. if ( tz <= min ) {
  23294. normal.set( 0, 0, 1 );
  23295. }
  23296. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23297. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23298. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23299. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23300. for ( let i = 1; i <= segments; i ++ ) {
  23301. normals[ i ] = normals[ i - 1 ].clone();
  23302. binormals[ i ] = binormals[ i - 1 ].clone();
  23303. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23304. if ( vec.length() > Number.EPSILON ) {
  23305. vec.normalize();
  23306. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23307. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23308. }
  23309. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23310. }
  23311. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23312. if ( closed === true ) {
  23313. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23314. theta /= segments;
  23315. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23316. theta = - theta;
  23317. }
  23318. for ( let i = 1; i <= segments; i ++ ) {
  23319. // twist a little...
  23320. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23321. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23322. }
  23323. }
  23324. return {
  23325. tangents: tangents,
  23326. normals: normals,
  23327. binormals: binormals
  23328. };
  23329. }
  23330. /**
  23331. * Returns a new curve with copied values from this instance.
  23332. *
  23333. * @return {Curve} A clone of this instance.
  23334. */
  23335. clone() {
  23336. return new this.constructor().copy( this );
  23337. }
  23338. /**
  23339. * Copies the values of the given curve to this instance.
  23340. *
  23341. * @param {Curve} source - The curve to copy.
  23342. * @return {Curve} A reference to this curve.
  23343. */
  23344. copy( source ) {
  23345. this.arcLengthDivisions = source.arcLengthDivisions;
  23346. return this;
  23347. }
  23348. /**
  23349. * Serializes the curve into JSON.
  23350. *
  23351. * @return {Object} A JSON object representing the serialized curve.
  23352. * @see {@link ObjectLoader#parse}
  23353. */
  23354. toJSON() {
  23355. const data = {
  23356. metadata: {
  23357. version: 4.7,
  23358. type: 'Curve',
  23359. generator: 'Curve.toJSON'
  23360. }
  23361. };
  23362. data.arcLengthDivisions = this.arcLengthDivisions;
  23363. data.type = this.type;
  23364. return data;
  23365. }
  23366. /**
  23367. * Deserializes the curve from the given JSON.
  23368. *
  23369. * @param {Object} json - The JSON holding the serialized curve.
  23370. * @return {Curve} A reference to this curve.
  23371. */
  23372. fromJSON( json ) {
  23373. this.arcLengthDivisions = json.arcLengthDivisions;
  23374. return this;
  23375. }
  23376. }
  23377. /**
  23378. * A curve representing an ellipse.
  23379. *
  23380. * ```js
  23381. * const curve = new THREE.EllipseCurve(
  23382. * 0, 0,
  23383. * 10, 10,
  23384. * 0, 2 * Math.PI,
  23385. * false,
  23386. * 0
  23387. * );
  23388. *
  23389. * const points = curve.getPoints( 50 );
  23390. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23391. *
  23392. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23393. *
  23394. * // Create the final object to add to the scene
  23395. * const ellipse = new THREE.Line( geometry, material );
  23396. * ```
  23397. *
  23398. * @augments Curve
  23399. */
  23400. class EllipseCurve extends Curve {
  23401. /**
  23402. * Constructs a new ellipse curve.
  23403. *
  23404. * @param {number} [aX=0] - The X center of the ellipse.
  23405. * @param {number} [aY=0] - The Y center of the ellipse.
  23406. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23407. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23408. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23409. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23410. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23411. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23412. */
  23413. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23414. super();
  23415. /**
  23416. * This flag can be used for type testing.
  23417. *
  23418. * @type {boolean}
  23419. * @readonly
  23420. * @default true
  23421. */
  23422. this.isEllipseCurve = true;
  23423. this.type = 'EllipseCurve';
  23424. /**
  23425. * The X center of the ellipse.
  23426. *
  23427. * @type {number}
  23428. * @default 0
  23429. */
  23430. this.aX = aX;
  23431. /**
  23432. * The Y center of the ellipse.
  23433. *
  23434. * @type {number}
  23435. * @default 0
  23436. */
  23437. this.aY = aY;
  23438. /**
  23439. * The radius of the ellipse in the x direction.
  23440. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23441. *
  23442. * @type {number}
  23443. * @default 1
  23444. */
  23445. this.xRadius = xRadius;
  23446. /**
  23447. * The radius of the ellipse in the y direction.
  23448. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23449. *
  23450. * @type {number}
  23451. * @default 1
  23452. */
  23453. this.yRadius = yRadius;
  23454. /**
  23455. * The start angle of the curve in radians starting from the positive X axis.
  23456. *
  23457. * @type {number}
  23458. * @default 0
  23459. */
  23460. this.aStartAngle = aStartAngle;
  23461. /**
  23462. * The end angle of the curve in radians starting from the positive X axis.
  23463. *
  23464. * @type {number}
  23465. * @default Math.PI*2
  23466. */
  23467. this.aEndAngle = aEndAngle;
  23468. /**
  23469. * Whether the ellipse is drawn clockwise or not.
  23470. *
  23471. * @type {boolean}
  23472. * @default false
  23473. */
  23474. this.aClockwise = aClockwise;
  23475. /**
  23476. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23477. *
  23478. * @type {number}
  23479. * @default 0
  23480. */
  23481. this.aRotation = aRotation;
  23482. }
  23483. /**
  23484. * Returns a point on the curve.
  23485. *
  23486. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23487. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23488. * @return {Vector2} The position on the curve.
  23489. */
  23490. getPoint( t, optionalTarget = new Vector2() ) {
  23491. const point = optionalTarget;
  23492. const twoPi = Math.PI * 2;
  23493. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23494. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23495. // ensures that deltaAngle is 0 .. 2 PI
  23496. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23497. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23498. if ( deltaAngle < Number.EPSILON ) {
  23499. if ( samePoints ) {
  23500. deltaAngle = 0;
  23501. } else {
  23502. deltaAngle = twoPi;
  23503. }
  23504. }
  23505. if ( this.aClockwise === true && ! samePoints ) {
  23506. if ( deltaAngle === twoPi ) {
  23507. deltaAngle = - twoPi;
  23508. } else {
  23509. deltaAngle = deltaAngle - twoPi;
  23510. }
  23511. }
  23512. const angle = this.aStartAngle + t * deltaAngle;
  23513. let x = this.aX + this.xRadius * Math.cos( angle );
  23514. let y = this.aY + this.yRadius * Math.sin( angle );
  23515. if ( this.aRotation !== 0 ) {
  23516. const cos = Math.cos( this.aRotation );
  23517. const sin = Math.sin( this.aRotation );
  23518. const tx = x - this.aX;
  23519. const ty = y - this.aY;
  23520. // Rotate the point about the center of the ellipse.
  23521. x = tx * cos - ty * sin + this.aX;
  23522. y = tx * sin + ty * cos + this.aY;
  23523. }
  23524. return point.set( x, y );
  23525. }
  23526. copy( source ) {
  23527. super.copy( source );
  23528. this.aX = source.aX;
  23529. this.aY = source.aY;
  23530. this.xRadius = source.xRadius;
  23531. this.yRadius = source.yRadius;
  23532. this.aStartAngle = source.aStartAngle;
  23533. this.aEndAngle = source.aEndAngle;
  23534. this.aClockwise = source.aClockwise;
  23535. this.aRotation = source.aRotation;
  23536. return this;
  23537. }
  23538. toJSON() {
  23539. const data = super.toJSON();
  23540. data.aX = this.aX;
  23541. data.aY = this.aY;
  23542. data.xRadius = this.xRadius;
  23543. data.yRadius = this.yRadius;
  23544. data.aStartAngle = this.aStartAngle;
  23545. data.aEndAngle = this.aEndAngle;
  23546. data.aClockwise = this.aClockwise;
  23547. data.aRotation = this.aRotation;
  23548. return data;
  23549. }
  23550. fromJSON( json ) {
  23551. super.fromJSON( json );
  23552. this.aX = json.aX;
  23553. this.aY = json.aY;
  23554. this.xRadius = json.xRadius;
  23555. this.yRadius = json.yRadius;
  23556. this.aStartAngle = json.aStartAngle;
  23557. this.aEndAngle = json.aEndAngle;
  23558. this.aClockwise = json.aClockwise;
  23559. this.aRotation = json.aRotation;
  23560. return this;
  23561. }
  23562. }
  23563. /**
  23564. * A curve representing an arc.
  23565. *
  23566. * @augments EllipseCurve
  23567. */
  23568. class ArcCurve extends EllipseCurve {
  23569. /**
  23570. * Constructs a new arc curve.
  23571. *
  23572. * @param {number} [aX=0] - The X center of the ellipse.
  23573. * @param {number} [aY=0] - The Y center of the ellipse.
  23574. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23575. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23576. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23577. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23578. */
  23579. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23580. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23581. /**
  23582. * This flag can be used for type testing.
  23583. *
  23584. * @type {boolean}
  23585. * @readonly
  23586. * @default true
  23587. */
  23588. this.isArcCurve = true;
  23589. this.type = 'ArcCurve';
  23590. }
  23591. }
  23592. function CubicPoly() {
  23593. /**
  23594. * Centripetal CatmullRom Curve - which is useful for avoiding
  23595. * cusps and self-intersections in non-uniform catmull rom curves.
  23596. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23597. *
  23598. * curve.type accepts centripetal(default), chordal and catmullrom
  23599. * curve.tension is used for catmullrom which defaults to 0.5
  23600. */
  23601. /*
  23602. Based on an optimized c++ solution in
  23603. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23604. - http://ideone.com/NoEbVM
  23605. This CubicPoly class could be used for reusing some variables and calculations,
  23606. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23607. which can be placed in CurveUtils.
  23608. */
  23609. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23610. /*
  23611. * Compute coefficients for a cubic polynomial
  23612. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23613. * such that
  23614. * p(0) = x0, p(1) = x1
  23615. * and
  23616. * p'(0) = t0, p'(1) = t1.
  23617. */
  23618. function init( x0, x1, t0, t1 ) {
  23619. c0 = x0;
  23620. c1 = t0;
  23621. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23622. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23623. }
  23624. return {
  23625. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23626. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23627. },
  23628. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23629. // compute tangents when parameterized in [t1,t2]
  23630. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23631. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23632. // rescale tangents for parametrization in [0,1]
  23633. t1 *= dt1;
  23634. t2 *= dt1;
  23635. init( x1, x2, t1, t2 );
  23636. },
  23637. calc: function ( t ) {
  23638. const t2 = t * t;
  23639. const t3 = t2 * t;
  23640. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23641. }
  23642. };
  23643. }
  23644. //
  23645. const tmp = /*@__PURE__*/ new Vector3();
  23646. const px = /*@__PURE__*/ new CubicPoly();
  23647. const py = /*@__PURE__*/ new CubicPoly();
  23648. const pz = /*@__PURE__*/ new CubicPoly();
  23649. /**
  23650. * A curve representing a Catmull-Rom spline.
  23651. *
  23652. * ```js
  23653. * //Create a closed wavey loop
  23654. * const curve = new THREE.CatmullRomCurve3( [
  23655. * new THREE.Vector3( -10, 0, 10 ),
  23656. * new THREE.Vector3( -5, 5, 5 ),
  23657. * new THREE.Vector3( 0, 0, 0 ),
  23658. * new THREE.Vector3( 5, -5, 5 ),
  23659. * new THREE.Vector3( 10, 0, 10 )
  23660. * ] );
  23661. *
  23662. * const points = curve.getPoints( 50 );
  23663. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23664. *
  23665. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23666. *
  23667. * // Create the final object to add to the scene
  23668. * const curveObject = new THREE.Line( geometry, material );
  23669. * ```
  23670. *
  23671. * @augments Curve
  23672. */
  23673. class CatmullRomCurve3 extends Curve {
  23674. /**
  23675. * Constructs a new Catmull-Rom curve.
  23676. *
  23677. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23678. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23679. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23680. * @param {number} [tension=0.5] - Tension of the curve.
  23681. */
  23682. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23683. super();
  23684. /**
  23685. * This flag can be used for type testing.
  23686. *
  23687. * @type {boolean}
  23688. * @readonly
  23689. * @default true
  23690. */
  23691. this.isCatmullRomCurve3 = true;
  23692. this.type = 'CatmullRomCurve3';
  23693. /**
  23694. * An array of 3D points defining the curve.
  23695. *
  23696. * @type {Array<Vector3>}
  23697. */
  23698. this.points = points;
  23699. /**
  23700. * Whether the curve is closed or not.
  23701. *
  23702. * @type {boolean}
  23703. * @default false
  23704. */
  23705. this.closed = closed;
  23706. /**
  23707. * The curve type.
  23708. *
  23709. * @type {('centripetal'|'chordal'|'catmullrom')}
  23710. * @default 'centripetal'
  23711. */
  23712. this.curveType = curveType;
  23713. /**
  23714. * Tension of the curve.
  23715. *
  23716. * @type {number}
  23717. * @default 0.5
  23718. */
  23719. this.tension = tension;
  23720. }
  23721. /**
  23722. * Returns a point on the curve.
  23723. *
  23724. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23725. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23726. * @return {Vector3} The position on the curve.
  23727. */
  23728. getPoint( t, optionalTarget = new Vector3() ) {
  23729. const point = optionalTarget;
  23730. const points = this.points;
  23731. const l = points.length;
  23732. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23733. let intPoint = Math.floor( p );
  23734. let weight = p - intPoint;
  23735. if ( this.closed ) {
  23736. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23737. } else if ( weight === 0 && intPoint === l - 1 ) {
  23738. intPoint = l - 2;
  23739. weight = 1;
  23740. }
  23741. let p0, p3; // 4 points (p1 & p2 defined below)
  23742. if ( this.closed || intPoint > 0 ) {
  23743. p0 = points[ ( intPoint - 1 ) % l ];
  23744. } else {
  23745. // extrapolate first point
  23746. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23747. p0 = tmp;
  23748. }
  23749. const p1 = points[ intPoint % l ];
  23750. const p2 = points[ ( intPoint + 1 ) % l ];
  23751. if ( this.closed || intPoint + 2 < l ) {
  23752. p3 = points[ ( intPoint + 2 ) % l ];
  23753. } else {
  23754. // extrapolate last point
  23755. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23756. p3 = tmp;
  23757. }
  23758. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23759. // init Centripetal / Chordal Catmull-Rom
  23760. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23761. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23762. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23763. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23764. // safety check for repeated points
  23765. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23766. if ( dt0 < 1e-4 ) dt0 = dt1;
  23767. if ( dt2 < 1e-4 ) dt2 = dt1;
  23768. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23769. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23770. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23771. } else if ( this.curveType === 'catmullrom' ) {
  23772. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23773. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23774. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23775. }
  23776. point.set(
  23777. px.calc( weight ),
  23778. py.calc( weight ),
  23779. pz.calc( weight )
  23780. );
  23781. return point;
  23782. }
  23783. copy( source ) {
  23784. super.copy( source );
  23785. this.points = [];
  23786. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23787. const point = source.points[ i ];
  23788. this.points.push( point.clone() );
  23789. }
  23790. this.closed = source.closed;
  23791. this.curveType = source.curveType;
  23792. this.tension = source.tension;
  23793. return this;
  23794. }
  23795. toJSON() {
  23796. const data = super.toJSON();
  23797. data.points = [];
  23798. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23799. const point = this.points[ i ];
  23800. data.points.push( point.toArray() );
  23801. }
  23802. data.closed = this.closed;
  23803. data.curveType = this.curveType;
  23804. data.tension = this.tension;
  23805. return data;
  23806. }
  23807. fromJSON( json ) {
  23808. super.fromJSON( json );
  23809. this.points = [];
  23810. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23811. const point = json.points[ i ];
  23812. this.points.push( new Vector3().fromArray( point ) );
  23813. }
  23814. this.closed = json.closed;
  23815. this.curveType = json.curveType;
  23816. this.tension = json.tension;
  23817. return this;
  23818. }
  23819. }
  23820. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23821. /**
  23822. * Computes a point on a Catmull-Rom spline.
  23823. *
  23824. * @param {number} t - The interpolation factor.
  23825. * @param {number} p0 - The first control point.
  23826. * @param {number} p1 - The second control point.
  23827. * @param {number} p2 - The third control point.
  23828. * @param {number} p3 - The fourth control point.
  23829. * @return {number} The calculated point on a Catmull-Rom spline.
  23830. */
  23831. function CatmullRom( t, p0, p1, p2, p3 ) {
  23832. const v0 = ( p2 - p0 ) * 0.5;
  23833. const v1 = ( p3 - p1 ) * 0.5;
  23834. const t2 = t * t;
  23835. const t3 = t * t2;
  23836. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23837. }
  23838. //
  23839. function QuadraticBezierP0( t, p ) {
  23840. const k = 1 - t;
  23841. return k * k * p;
  23842. }
  23843. function QuadraticBezierP1( t, p ) {
  23844. return 2 * ( 1 - t ) * t * p;
  23845. }
  23846. function QuadraticBezierP2( t, p ) {
  23847. return t * t * p;
  23848. }
  23849. /**
  23850. * Computes a point on a Quadratic Bezier curve.
  23851. *
  23852. * @param {number} t - The interpolation factor.
  23853. * @param {number} p0 - The first control point.
  23854. * @param {number} p1 - The second control point.
  23855. * @param {number} p2 - The third control point.
  23856. * @return {number} The calculated point on a Quadratic Bezier curve.
  23857. */
  23858. function QuadraticBezier( t, p0, p1, p2 ) {
  23859. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23860. QuadraticBezierP2( t, p2 );
  23861. }
  23862. //
  23863. function CubicBezierP0( t, p ) {
  23864. const k = 1 - t;
  23865. return k * k * k * p;
  23866. }
  23867. function CubicBezierP1( t, p ) {
  23868. const k = 1 - t;
  23869. return 3 * k * k * t * p;
  23870. }
  23871. function CubicBezierP2( t, p ) {
  23872. return 3 * ( 1 - t ) * t * t * p;
  23873. }
  23874. function CubicBezierP3( t, p ) {
  23875. return t * t * t * p;
  23876. }
  23877. /**
  23878. * Computes a point on a Cubic Bezier curve.
  23879. *
  23880. * @param {number} t - The interpolation factor.
  23881. * @param {number} p0 - The first control point.
  23882. * @param {number} p1 - The second control point.
  23883. * @param {number} p2 - The third control point.
  23884. * @param {number} p3 - The fourth control point.
  23885. * @return {number} The calculated point on a Cubic Bezier curve.
  23886. */
  23887. function CubicBezier( t, p0, p1, p2, p3 ) {
  23888. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23889. CubicBezierP3( t, p3 );
  23890. }
  23891. /**
  23892. * A curve representing a 2D Cubic Bezier curve.
  23893. *
  23894. * ```js
  23895. * const curve = new THREE.CubicBezierCurve(
  23896. * new THREE.Vector2( - 0, 0 ),
  23897. * new THREE.Vector2( - 5, 15 ),
  23898. * new THREE.Vector2( 20, 15 ),
  23899. * new THREE.Vector2( 10, 0 )
  23900. * );
  23901. *
  23902. * const points = curve.getPoints( 50 );
  23903. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23904. *
  23905. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23906. *
  23907. * // Create the final object to add to the scene
  23908. * const curveObject = new THREE.Line( geometry, material );
  23909. * ```
  23910. *
  23911. * @augments Curve
  23912. */
  23913. class CubicBezierCurve extends Curve {
  23914. /**
  23915. * Constructs a new Cubic Bezier curve.
  23916. *
  23917. * @param {Vector2} [v0] - The start point.
  23918. * @param {Vector2} [v1] - The first control point.
  23919. * @param {Vector2} [v2] - The second control point.
  23920. * @param {Vector2} [v3] - The end point.
  23921. */
  23922. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23923. super();
  23924. /**
  23925. * This flag can be used for type testing.
  23926. *
  23927. * @type {boolean}
  23928. * @readonly
  23929. * @default true
  23930. */
  23931. this.isCubicBezierCurve = true;
  23932. this.type = 'CubicBezierCurve';
  23933. /**
  23934. * The start point.
  23935. *
  23936. * @type {Vector2}
  23937. */
  23938. this.v0 = v0;
  23939. /**
  23940. * The first control point.
  23941. *
  23942. * @type {Vector2}
  23943. */
  23944. this.v1 = v1;
  23945. /**
  23946. * The second control point.
  23947. *
  23948. * @type {Vector2}
  23949. */
  23950. this.v2 = v2;
  23951. /**
  23952. * The end point.
  23953. *
  23954. * @type {Vector2}
  23955. */
  23956. this.v3 = v3;
  23957. }
  23958. /**
  23959. * Returns a point on the curve.
  23960. *
  23961. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23962. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23963. * @return {Vector2} The position on the curve.
  23964. */
  23965. getPoint( t, optionalTarget = new Vector2() ) {
  23966. const point = optionalTarget;
  23967. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23968. point.set(
  23969. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23970. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23971. );
  23972. return point;
  23973. }
  23974. copy( source ) {
  23975. super.copy( source );
  23976. this.v0.copy( source.v0 );
  23977. this.v1.copy( source.v1 );
  23978. this.v2.copy( source.v2 );
  23979. this.v3.copy( source.v3 );
  23980. return this;
  23981. }
  23982. toJSON() {
  23983. const data = super.toJSON();
  23984. data.v0 = this.v0.toArray();
  23985. data.v1 = this.v1.toArray();
  23986. data.v2 = this.v2.toArray();
  23987. data.v3 = this.v3.toArray();
  23988. return data;
  23989. }
  23990. fromJSON( json ) {
  23991. super.fromJSON( json );
  23992. this.v0.fromArray( json.v0 );
  23993. this.v1.fromArray( json.v1 );
  23994. this.v2.fromArray( json.v2 );
  23995. this.v3.fromArray( json.v3 );
  23996. return this;
  23997. }
  23998. }
  23999. /**
  24000. * A curve representing a 3D Cubic Bezier curve.
  24001. *
  24002. * @augments Curve
  24003. */
  24004. class CubicBezierCurve3 extends Curve {
  24005. /**
  24006. * Constructs a new Cubic Bezier curve.
  24007. *
  24008. * @param {Vector3} [v0] - The start point.
  24009. * @param {Vector3} [v1] - The first control point.
  24010. * @param {Vector3} [v2] - The second control point.
  24011. * @param {Vector3} [v3] - The end point.
  24012. */
  24013. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24014. super();
  24015. /**
  24016. * This flag can be used for type testing.
  24017. *
  24018. * @type {boolean}
  24019. * @readonly
  24020. * @default true
  24021. */
  24022. this.isCubicBezierCurve3 = true;
  24023. this.type = 'CubicBezierCurve3';
  24024. /**
  24025. * The start point.
  24026. *
  24027. * @type {Vector3}
  24028. */
  24029. this.v0 = v0;
  24030. /**
  24031. * The first control point.
  24032. *
  24033. * @type {Vector3}
  24034. */
  24035. this.v1 = v1;
  24036. /**
  24037. * The second control point.
  24038. *
  24039. * @type {Vector3}
  24040. */
  24041. this.v2 = v2;
  24042. /**
  24043. * The end point.
  24044. *
  24045. * @type {Vector3}
  24046. */
  24047. this.v3 = v3;
  24048. }
  24049. /**
  24050. * Returns a point on the curve.
  24051. *
  24052. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24053. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24054. * @return {Vector3} The position on the curve.
  24055. */
  24056. getPoint( t, optionalTarget = new Vector3() ) {
  24057. const point = optionalTarget;
  24058. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24059. point.set(
  24060. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24061. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24062. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24063. );
  24064. return point;
  24065. }
  24066. copy( source ) {
  24067. super.copy( source );
  24068. this.v0.copy( source.v0 );
  24069. this.v1.copy( source.v1 );
  24070. this.v2.copy( source.v2 );
  24071. this.v3.copy( source.v3 );
  24072. return this;
  24073. }
  24074. toJSON() {
  24075. const data = super.toJSON();
  24076. data.v0 = this.v0.toArray();
  24077. data.v1 = this.v1.toArray();
  24078. data.v2 = this.v2.toArray();
  24079. data.v3 = this.v3.toArray();
  24080. return data;
  24081. }
  24082. fromJSON( json ) {
  24083. super.fromJSON( json );
  24084. this.v0.fromArray( json.v0 );
  24085. this.v1.fromArray( json.v1 );
  24086. this.v2.fromArray( json.v2 );
  24087. this.v3.fromArray( json.v3 );
  24088. return this;
  24089. }
  24090. }
  24091. /**
  24092. * A curve representing a 2D line segment.
  24093. *
  24094. * @augments Curve
  24095. */
  24096. class LineCurve extends Curve {
  24097. /**
  24098. * Constructs a new line curve.
  24099. *
  24100. * @param {Vector2} [v1] - The start point.
  24101. * @param {Vector2} [v2] - The end point.
  24102. */
  24103. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24104. super();
  24105. /**
  24106. * This flag can be used for type testing.
  24107. *
  24108. * @type {boolean}
  24109. * @readonly
  24110. * @default true
  24111. */
  24112. this.isLineCurve = true;
  24113. this.type = 'LineCurve';
  24114. /**
  24115. * The start point.
  24116. *
  24117. * @type {Vector2}
  24118. */
  24119. this.v1 = v1;
  24120. /**
  24121. * The end point.
  24122. *
  24123. * @type {Vector2}
  24124. */
  24125. this.v2 = v2;
  24126. }
  24127. /**
  24128. * Returns a point on the line.
  24129. *
  24130. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24131. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24132. * @return {Vector2} The position on the line.
  24133. */
  24134. getPoint( t, optionalTarget = new Vector2() ) {
  24135. const point = optionalTarget;
  24136. if ( t === 1 ) {
  24137. point.copy( this.v2 );
  24138. } else {
  24139. point.copy( this.v2 ).sub( this.v1 );
  24140. point.multiplyScalar( t ).add( this.v1 );
  24141. }
  24142. return point;
  24143. }
  24144. // Line curve is linear, so we can overwrite default getPointAt
  24145. getPointAt( u, optionalTarget ) {
  24146. return this.getPoint( u, optionalTarget );
  24147. }
  24148. getTangent( t, optionalTarget = new Vector2() ) {
  24149. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24150. }
  24151. getTangentAt( u, optionalTarget ) {
  24152. return this.getTangent( u, optionalTarget );
  24153. }
  24154. copy( source ) {
  24155. super.copy( source );
  24156. this.v1.copy( source.v1 );
  24157. this.v2.copy( source.v2 );
  24158. return this;
  24159. }
  24160. toJSON() {
  24161. const data = super.toJSON();
  24162. data.v1 = this.v1.toArray();
  24163. data.v2 = this.v2.toArray();
  24164. return data;
  24165. }
  24166. fromJSON( json ) {
  24167. super.fromJSON( json );
  24168. this.v1.fromArray( json.v1 );
  24169. this.v2.fromArray( json.v2 );
  24170. return this;
  24171. }
  24172. }
  24173. /**
  24174. * A curve representing a 3D line segment.
  24175. *
  24176. * @augments Curve
  24177. */
  24178. class LineCurve3 extends Curve {
  24179. /**
  24180. * Constructs a new line curve.
  24181. *
  24182. * @param {Vector3} [v1] - The start point.
  24183. * @param {Vector3} [v2] - The end point.
  24184. */
  24185. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24186. super();
  24187. /**
  24188. * This flag can be used for type testing.
  24189. *
  24190. * @type {boolean}
  24191. * @readonly
  24192. * @default true
  24193. */
  24194. this.isLineCurve3 = true;
  24195. this.type = 'LineCurve3';
  24196. /**
  24197. * The start point.
  24198. *
  24199. * @type {Vector3}
  24200. */
  24201. this.v1 = v1;
  24202. /**
  24203. * The end point.
  24204. *
  24205. * @type {Vector2}
  24206. */
  24207. this.v2 = v2;
  24208. }
  24209. /**
  24210. * Returns a point on the line.
  24211. *
  24212. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24213. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24214. * @return {Vector3} The position on the line.
  24215. */
  24216. getPoint( t, optionalTarget = new Vector3() ) {
  24217. const point = optionalTarget;
  24218. if ( t === 1 ) {
  24219. point.copy( this.v2 );
  24220. } else {
  24221. point.copy( this.v2 ).sub( this.v1 );
  24222. point.multiplyScalar( t ).add( this.v1 );
  24223. }
  24224. return point;
  24225. }
  24226. // Line curve is linear, so we can overwrite default getPointAt
  24227. getPointAt( u, optionalTarget ) {
  24228. return this.getPoint( u, optionalTarget );
  24229. }
  24230. getTangent( t, optionalTarget = new Vector3() ) {
  24231. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24232. }
  24233. getTangentAt( u, optionalTarget ) {
  24234. return this.getTangent( u, optionalTarget );
  24235. }
  24236. copy( source ) {
  24237. super.copy( source );
  24238. this.v1.copy( source.v1 );
  24239. this.v2.copy( source.v2 );
  24240. return this;
  24241. }
  24242. toJSON() {
  24243. const data = super.toJSON();
  24244. data.v1 = this.v1.toArray();
  24245. data.v2 = this.v2.toArray();
  24246. return data;
  24247. }
  24248. fromJSON( json ) {
  24249. super.fromJSON( json );
  24250. this.v1.fromArray( json.v1 );
  24251. this.v2.fromArray( json.v2 );
  24252. return this;
  24253. }
  24254. }
  24255. /**
  24256. * A curve representing a 2D Quadratic Bezier curve.
  24257. *
  24258. * ```js
  24259. * const curve = new THREE.QuadraticBezierCurve(
  24260. * new THREE.Vector2( - 10, 0 ),
  24261. * new THREE.Vector2( 20, 15 ),
  24262. * new THREE.Vector2( 10, 0 )
  24263. * )
  24264. *
  24265. * const points = curve.getPoints( 50 );
  24266. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24267. *
  24268. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24269. *
  24270. * // Create the final object to add to the scene
  24271. * const curveObject = new THREE.Line( geometry, material );
  24272. * ```
  24273. *
  24274. * @augments Curve
  24275. */
  24276. class QuadraticBezierCurve extends Curve {
  24277. /**
  24278. * Constructs a new Quadratic Bezier curve.
  24279. *
  24280. * @param {Vector2} [v0] - The start point.
  24281. * @param {Vector2} [v1] - The control point.
  24282. * @param {Vector2} [v2] - The end point.
  24283. */
  24284. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24285. super();
  24286. /**
  24287. * This flag can be used for type testing.
  24288. *
  24289. * @type {boolean}
  24290. * @readonly
  24291. * @default true
  24292. */
  24293. this.isQuadraticBezierCurve = true;
  24294. this.type = 'QuadraticBezierCurve';
  24295. /**
  24296. * The start point.
  24297. *
  24298. * @type {Vector2}
  24299. */
  24300. this.v0 = v0;
  24301. /**
  24302. * The control point.
  24303. *
  24304. * @type {Vector2}
  24305. */
  24306. this.v1 = v1;
  24307. /**
  24308. * The end point.
  24309. *
  24310. * @type {Vector2}
  24311. */
  24312. this.v2 = v2;
  24313. }
  24314. /**
  24315. * Returns a point on the curve.
  24316. *
  24317. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24318. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24319. * @return {Vector2} The position on the curve.
  24320. */
  24321. getPoint( t, optionalTarget = new Vector2() ) {
  24322. const point = optionalTarget;
  24323. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24324. point.set(
  24325. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24326. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24327. );
  24328. return point;
  24329. }
  24330. copy( source ) {
  24331. super.copy( source );
  24332. this.v0.copy( source.v0 );
  24333. this.v1.copy( source.v1 );
  24334. this.v2.copy( source.v2 );
  24335. return this;
  24336. }
  24337. toJSON() {
  24338. const data = super.toJSON();
  24339. data.v0 = this.v0.toArray();
  24340. data.v1 = this.v1.toArray();
  24341. data.v2 = this.v2.toArray();
  24342. return data;
  24343. }
  24344. fromJSON( json ) {
  24345. super.fromJSON( json );
  24346. this.v0.fromArray( json.v0 );
  24347. this.v1.fromArray( json.v1 );
  24348. this.v2.fromArray( json.v2 );
  24349. return this;
  24350. }
  24351. }
  24352. /**
  24353. * A curve representing a 3D Quadratic Bezier curve.
  24354. *
  24355. * @augments Curve
  24356. */
  24357. class QuadraticBezierCurve3 extends Curve {
  24358. /**
  24359. * Constructs a new Quadratic Bezier curve.
  24360. *
  24361. * @param {Vector3} [v0] - The start point.
  24362. * @param {Vector3} [v1] - The control point.
  24363. * @param {Vector3} [v2] - The end point.
  24364. */
  24365. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24366. super();
  24367. /**
  24368. * This flag can be used for type testing.
  24369. *
  24370. * @type {boolean}
  24371. * @readonly
  24372. * @default true
  24373. */
  24374. this.isQuadraticBezierCurve3 = true;
  24375. this.type = 'QuadraticBezierCurve3';
  24376. /**
  24377. * The start point.
  24378. *
  24379. * @type {Vector3}
  24380. */
  24381. this.v0 = v0;
  24382. /**
  24383. * The control point.
  24384. *
  24385. * @type {Vector3}
  24386. */
  24387. this.v1 = v1;
  24388. /**
  24389. * The end point.
  24390. *
  24391. * @type {Vector3}
  24392. */
  24393. this.v2 = v2;
  24394. }
  24395. /**
  24396. * Returns a point on the curve.
  24397. *
  24398. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24399. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24400. * @return {Vector3} The position on the curve.
  24401. */
  24402. getPoint( t, optionalTarget = new Vector3() ) {
  24403. const point = optionalTarget;
  24404. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24405. point.set(
  24406. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24407. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24408. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24409. );
  24410. return point;
  24411. }
  24412. copy( source ) {
  24413. super.copy( source );
  24414. this.v0.copy( source.v0 );
  24415. this.v1.copy( source.v1 );
  24416. this.v2.copy( source.v2 );
  24417. return this;
  24418. }
  24419. toJSON() {
  24420. const data = super.toJSON();
  24421. data.v0 = this.v0.toArray();
  24422. data.v1 = this.v1.toArray();
  24423. data.v2 = this.v2.toArray();
  24424. return data;
  24425. }
  24426. fromJSON( json ) {
  24427. super.fromJSON( json );
  24428. this.v0.fromArray( json.v0 );
  24429. this.v1.fromArray( json.v1 );
  24430. this.v2.fromArray( json.v2 );
  24431. return this;
  24432. }
  24433. }
  24434. /**
  24435. * A curve representing a 2D spline curve.
  24436. *
  24437. * ```js
  24438. * // Create a sine-like wave
  24439. * const curve = new THREE.SplineCurve( [
  24440. * new THREE.Vector2( -10, 0 ),
  24441. * new THREE.Vector2( -5, 5 ),
  24442. * new THREE.Vector2( 0, 0 ),
  24443. * new THREE.Vector2( 5, -5 ),
  24444. * new THREE.Vector2( 10, 0 )
  24445. * ] );
  24446. *
  24447. * const points = curve.getPoints( 50 );
  24448. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24449. *
  24450. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24451. *
  24452. * // Create the final object to add to the scene
  24453. * const splineObject = new THREE.Line( geometry, material );
  24454. * ```
  24455. *
  24456. * @augments Curve
  24457. */
  24458. class SplineCurve extends Curve {
  24459. /**
  24460. * Constructs a new 2D spline curve.
  24461. *
  24462. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24463. */
  24464. constructor( points = [] ) {
  24465. super();
  24466. /**
  24467. * This flag can be used for type testing.
  24468. *
  24469. * @type {boolean}
  24470. * @readonly
  24471. * @default true
  24472. */
  24473. this.isSplineCurve = true;
  24474. this.type = 'SplineCurve';
  24475. /**
  24476. * An array of 2D points defining the curve.
  24477. *
  24478. * @type {Array<Vector2>}
  24479. */
  24480. this.points = points;
  24481. }
  24482. /**
  24483. * Returns a point on the curve.
  24484. *
  24485. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24486. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24487. * @return {Vector2} The position on the curve.
  24488. */
  24489. getPoint( t, optionalTarget = new Vector2() ) {
  24490. const point = optionalTarget;
  24491. const points = this.points;
  24492. const p = ( points.length - 1 ) * t;
  24493. const intPoint = Math.floor( p );
  24494. const weight = p - intPoint;
  24495. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24496. const p1 = points[ intPoint ];
  24497. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24498. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24499. point.set(
  24500. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24501. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24502. );
  24503. return point;
  24504. }
  24505. copy( source ) {
  24506. super.copy( source );
  24507. this.points = [];
  24508. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24509. const point = source.points[ i ];
  24510. this.points.push( point.clone() );
  24511. }
  24512. return this;
  24513. }
  24514. toJSON() {
  24515. const data = super.toJSON();
  24516. data.points = [];
  24517. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24518. const point = this.points[ i ];
  24519. data.points.push( point.toArray() );
  24520. }
  24521. return data;
  24522. }
  24523. fromJSON( json ) {
  24524. super.fromJSON( json );
  24525. this.points = [];
  24526. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24527. const point = json.points[ i ];
  24528. this.points.push( new Vector2().fromArray( point ) );
  24529. }
  24530. return this;
  24531. }
  24532. }
  24533. var Curves = /*#__PURE__*/Object.freeze({
  24534. __proto__: null,
  24535. ArcCurve: ArcCurve,
  24536. CatmullRomCurve3: CatmullRomCurve3,
  24537. CubicBezierCurve: CubicBezierCurve,
  24538. CubicBezierCurve3: CubicBezierCurve3,
  24539. EllipseCurve: EllipseCurve,
  24540. LineCurve: LineCurve,
  24541. LineCurve3: LineCurve3,
  24542. QuadraticBezierCurve: QuadraticBezierCurve,
  24543. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24544. SplineCurve: SplineCurve
  24545. });
  24546. /**
  24547. * A base class extending {@link Curve}. `CurvePath` is simply an
  24548. * array of connected curves, but retains the API of a curve.
  24549. *
  24550. * @augments Curve
  24551. */
  24552. class CurvePath extends Curve {
  24553. /**
  24554. * Constructs a new curve path.
  24555. */
  24556. constructor() {
  24557. super();
  24558. this.type = 'CurvePath';
  24559. /**
  24560. * An array of curves defining the
  24561. * path.
  24562. *
  24563. * @type {Array<Curve>}
  24564. */
  24565. this.curves = [];
  24566. /**
  24567. * Whether the path should automatically be closed
  24568. * by a line curve.
  24569. *
  24570. * @type {boolean}
  24571. * @default false
  24572. */
  24573. this.autoClose = false;
  24574. }
  24575. /**
  24576. * Adds a curve to this curve path.
  24577. *
  24578. * @param {Curve} curve - The curve to add.
  24579. */
  24580. add( curve ) {
  24581. this.curves.push( curve );
  24582. }
  24583. /**
  24584. * Adds a line curve to close the path.
  24585. *
  24586. * @return {CurvePath} A reference to this curve path.
  24587. */
  24588. closePath() {
  24589. // Add a line curve if start and end of lines are not connected
  24590. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24591. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24592. if ( ! startPoint.equals( endPoint ) ) {
  24593. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24594. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24595. }
  24596. return this;
  24597. }
  24598. /**
  24599. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24600. * for the given interpolation factor.
  24601. *
  24602. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24603. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24604. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24605. */
  24606. getPoint( t, optionalTarget ) {
  24607. // To get accurate point with reference to
  24608. // entire path distance at time t,
  24609. // following has to be done:
  24610. // 1. Length of each sub path have to be known
  24611. // 2. Locate and identify type of curve
  24612. // 3. Get t for the curve
  24613. // 4. Return curve.getPointAt(t')
  24614. const d = t * this.getLength();
  24615. const curveLengths = this.getCurveLengths();
  24616. let i = 0;
  24617. // To think about boundaries points.
  24618. while ( i < curveLengths.length ) {
  24619. if ( curveLengths[ i ] >= d ) {
  24620. const diff = curveLengths[ i ] - d;
  24621. const curve = this.curves[ i ];
  24622. const segmentLength = curve.getLength();
  24623. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24624. return curve.getPointAt( u, optionalTarget );
  24625. }
  24626. i ++;
  24627. }
  24628. return null;
  24629. // loop where sum != 0, sum > d , sum+1 <d
  24630. }
  24631. getLength() {
  24632. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24633. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24634. // getPoint() depends on getLength
  24635. const lens = this.getCurveLengths();
  24636. return lens[ lens.length - 1 ];
  24637. }
  24638. updateArcLengths() {
  24639. // cacheLengths must be recalculated.
  24640. this.needsUpdate = true;
  24641. this.cacheLengths = null;
  24642. this.getCurveLengths();
  24643. }
  24644. /**
  24645. * Returns list of cumulative curve lengths of the defined curves.
  24646. *
  24647. * @return {Array<number>} The curve lengths.
  24648. */
  24649. getCurveLengths() {
  24650. // Compute lengths and cache them
  24651. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24652. // We use cache values if curves and cache array are same length
  24653. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24654. return this.cacheLengths;
  24655. }
  24656. // Get length of sub-curve
  24657. // Push sums into cached array
  24658. const lengths = [];
  24659. let sums = 0;
  24660. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24661. sums += this.curves[ i ].getLength();
  24662. lengths.push( sums );
  24663. }
  24664. this.cacheLengths = lengths;
  24665. return lengths;
  24666. }
  24667. getSpacedPoints( divisions = 40 ) {
  24668. const points = [];
  24669. for ( let i = 0; i <= divisions; i ++ ) {
  24670. points.push( this.getPoint( i / divisions ) );
  24671. }
  24672. if ( this.autoClose ) {
  24673. points.push( points[ 0 ] );
  24674. }
  24675. return points;
  24676. }
  24677. getPoints( divisions = 12 ) {
  24678. const points = [];
  24679. let last;
  24680. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24681. const curve = curves[ i ];
  24682. const resolution = curve.isEllipseCurve ? divisions * 2
  24683. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24684. : curve.isSplineCurve ? divisions * curve.points.length
  24685. : divisions;
  24686. const pts = curve.getPoints( resolution );
  24687. for ( let j = 0; j < pts.length; j ++ ) {
  24688. const point = pts[ j ];
  24689. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24690. points.push( point );
  24691. last = point;
  24692. }
  24693. }
  24694. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24695. points.push( points[ 0 ] );
  24696. }
  24697. return points;
  24698. }
  24699. copy( source ) {
  24700. super.copy( source );
  24701. this.curves = [];
  24702. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24703. const curve = source.curves[ i ];
  24704. this.curves.push( curve.clone() );
  24705. }
  24706. this.autoClose = source.autoClose;
  24707. return this;
  24708. }
  24709. toJSON() {
  24710. const data = super.toJSON();
  24711. data.autoClose = this.autoClose;
  24712. data.curves = [];
  24713. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24714. const curve = this.curves[ i ];
  24715. data.curves.push( curve.toJSON() );
  24716. }
  24717. return data;
  24718. }
  24719. fromJSON( json ) {
  24720. super.fromJSON( json );
  24721. this.autoClose = json.autoClose;
  24722. this.curves = [];
  24723. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24724. const curve = json.curves[ i ];
  24725. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24726. }
  24727. return this;
  24728. }
  24729. }
  24730. /**
  24731. * A 2D path representation. The class provides methods for creating paths
  24732. * and contours of 2D shapes similar to the 2D Canvas API.
  24733. *
  24734. * ```js
  24735. * const path = new THREE.Path();
  24736. *
  24737. * path.lineTo( 0, 0.8 );
  24738. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24739. * path.lineTo( 1, 1 );
  24740. *
  24741. * const points = path.getPoints();
  24742. *
  24743. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24744. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24745. *
  24746. * const line = new THREE.Line( geometry, material );
  24747. * scene.add( line );
  24748. * ```
  24749. *
  24750. * @augments CurvePath
  24751. */
  24752. class Path extends CurvePath {
  24753. /**
  24754. * Constructs a new path.
  24755. *
  24756. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24757. */
  24758. constructor( points ) {
  24759. super();
  24760. this.type = 'Path';
  24761. /**
  24762. * The current offset of the path. Any new curve added will start here.
  24763. *
  24764. * @type {Vector2}
  24765. */
  24766. this.currentPoint = new Vector2();
  24767. if ( points ) {
  24768. this.setFromPoints( points );
  24769. }
  24770. }
  24771. /**
  24772. * Creates a path from the given list of points. The points are added
  24773. * to the path as instances of {@link LineCurve}.
  24774. *
  24775. * @param {Array<Vector2>} points - An array of 2D points.
  24776. * @return {Path} A reference to this path.
  24777. */
  24778. setFromPoints( points ) {
  24779. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24780. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24781. this.lineTo( points[ i ].x, points[ i ].y );
  24782. }
  24783. return this;
  24784. }
  24785. /**
  24786. * Moves {@link Path#currentPoint} to the given point.
  24787. *
  24788. * @param {number} x - The x coordinate.
  24789. * @param {number} y - The y coordinate.
  24790. * @return {Path} A reference to this path.
  24791. */
  24792. moveTo( x, y ) {
  24793. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24794. return this;
  24795. }
  24796. /**
  24797. * Adds an instance of {@link LineCurve} to the path by connecting
  24798. * the current point with the given one.
  24799. *
  24800. * @param {number} x - The x coordinate of the end point.
  24801. * @param {number} y - The y coordinate of the end point.
  24802. * @return {Path} A reference to this path.
  24803. */
  24804. lineTo( x, y ) {
  24805. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24806. this.curves.push( curve );
  24807. this.currentPoint.set( x, y );
  24808. return this;
  24809. }
  24810. /**
  24811. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24812. * the current point with the given one.
  24813. *
  24814. * @param {number} aCPx - The x coordinate of the control point.
  24815. * @param {number} aCPy - The y coordinate of the control point.
  24816. * @param {number} aX - The x coordinate of the end point.
  24817. * @param {number} aY - The y coordinate of the end point.
  24818. * @return {Path} A reference to this path.
  24819. */
  24820. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24821. const curve = new QuadraticBezierCurve(
  24822. this.currentPoint.clone(),
  24823. new Vector2( aCPx, aCPy ),
  24824. new Vector2( aX, aY )
  24825. );
  24826. this.curves.push( curve );
  24827. this.currentPoint.set( aX, aY );
  24828. return this;
  24829. }
  24830. /**
  24831. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24832. * the current point with the given one.
  24833. *
  24834. * @param {number} aCP1x - The x coordinate of the first control point.
  24835. * @param {number} aCP1y - The y coordinate of the first control point.
  24836. * @param {number} aCP2x - The x coordinate of the second control point.
  24837. * @param {number} aCP2y - The y coordinate of the second control point.
  24838. * @param {number} aX - The x coordinate of the end point.
  24839. * @param {number} aY - The y coordinate of the end point.
  24840. * @return {Path} A reference to this path.
  24841. */
  24842. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24843. const curve = new CubicBezierCurve(
  24844. this.currentPoint.clone(),
  24845. new Vector2( aCP1x, aCP1y ),
  24846. new Vector2( aCP2x, aCP2y ),
  24847. new Vector2( aX, aY )
  24848. );
  24849. this.curves.push( curve );
  24850. this.currentPoint.set( aX, aY );
  24851. return this;
  24852. }
  24853. /**
  24854. * Adds an instance of {@link SplineCurve} to the path by connecting
  24855. * the current point with the given list of points.
  24856. *
  24857. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24858. * @return {Path} A reference to this path.
  24859. */
  24860. splineThru( pts ) {
  24861. const npts = [ this.currentPoint.clone() ].concat( pts );
  24862. const curve = new SplineCurve( npts );
  24863. this.curves.push( curve );
  24864. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24865. return this;
  24866. }
  24867. /**
  24868. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24869. * to the current point.
  24870. *
  24871. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24872. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24873. * @param {number} [aRadius=1] - The radius of the arc.
  24874. * @param {number} [aStartAngle=0] - The start angle in radians.
  24875. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24876. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24877. * @return {Path} A reference to this path.
  24878. */
  24879. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24880. const x0 = this.currentPoint.x;
  24881. const y0 = this.currentPoint.y;
  24882. this.absarc( aX + x0, aY + y0, aRadius,
  24883. aStartAngle, aEndAngle, aClockwise );
  24884. return this;
  24885. }
  24886. /**
  24887. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24888. *
  24889. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24890. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24891. * @param {number} [aRadius=1] - The radius of the arc.
  24892. * @param {number} [aStartAngle=0] - The start angle in radians.
  24893. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24894. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24895. * @return {Path} A reference to this path.
  24896. */
  24897. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24898. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24899. return this;
  24900. }
  24901. /**
  24902. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24903. * to the current point
  24904. *
  24905. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24906. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24907. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24908. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24909. * @param {number} [aStartAngle=0] - The start angle in radians.
  24910. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24911. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24912. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24913. * @return {Path} A reference to this path.
  24914. */
  24915. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24916. const x0 = this.currentPoint.x;
  24917. const y0 = this.currentPoint.y;
  24918. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24919. return this;
  24920. }
  24921. /**
  24922. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24923. *
  24924. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24925. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24926. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24927. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24928. * @param {number} [aStartAngle=0] - The start angle in radians.
  24929. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24930. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24931. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24932. * @return {Path} A reference to this path.
  24933. */
  24934. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24935. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24936. if ( this.curves.length > 0 ) {
  24937. // if a previous curve is present, attempt to join
  24938. const firstPoint = curve.getPoint( 0 );
  24939. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24940. this.lineTo( firstPoint.x, firstPoint.y );
  24941. }
  24942. }
  24943. this.curves.push( curve );
  24944. const lastPoint = curve.getPoint( 1 );
  24945. this.currentPoint.copy( lastPoint );
  24946. return this;
  24947. }
  24948. copy( source ) {
  24949. super.copy( source );
  24950. this.currentPoint.copy( source.currentPoint );
  24951. return this;
  24952. }
  24953. toJSON() {
  24954. const data = super.toJSON();
  24955. data.currentPoint = this.currentPoint.toArray();
  24956. return data;
  24957. }
  24958. fromJSON( json ) {
  24959. super.fromJSON( json );
  24960. this.currentPoint.fromArray( json.currentPoint );
  24961. return this;
  24962. }
  24963. }
  24964. /**
  24965. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24966. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24967. * points, or to get triangulated faces.
  24968. *
  24969. * ```js
  24970. * const heartShape = new THREE.Shape();
  24971. *
  24972. * heartShape.moveTo( 25, 25 );
  24973. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24974. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24975. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24976. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24977. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24978. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24979. *
  24980. * const extrudeSettings = {
  24981. * depth: 8,
  24982. * bevelEnabled: true,
  24983. * bevelSegments: 2,
  24984. * steps: 2,
  24985. * bevelSize: 1,
  24986. * bevelThickness: 1
  24987. * };
  24988. *
  24989. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24990. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24991. * ```
  24992. *
  24993. * @augments Path
  24994. */
  24995. class Shape extends Path {
  24996. /**
  24997. * Constructs a new shape.
  24998. *
  24999. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25000. */
  25001. constructor( points ) {
  25002. super( points );
  25003. /**
  25004. * The UUID of the shape.
  25005. *
  25006. * @type {string}
  25007. * @readonly
  25008. */
  25009. this.uuid = generateUUID();
  25010. this.type = 'Shape';
  25011. /**
  25012. * Defines the holes in the shape. Hole definitions must use the
  25013. * opposite winding order (CW/CCW) than the outer shape.
  25014. *
  25015. * @type {Array<Path>}
  25016. * @readonly
  25017. */
  25018. this.holes = [];
  25019. }
  25020. /**
  25021. * Returns an array representing each contour of the holes
  25022. * as a list of 2D points.
  25023. *
  25024. * @param {number} divisions - The fineness of the result.
  25025. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25026. */
  25027. getPointsHoles( divisions ) {
  25028. const holesPts = [];
  25029. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25030. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25031. }
  25032. return holesPts;
  25033. }
  25034. // get points of shape and holes (keypoints based on segments parameter)
  25035. /**
  25036. * Returns an object that holds contour data for the shape and its holes as
  25037. * arrays of 2D points.
  25038. *
  25039. * @param {number} divisions - The fineness of the result.
  25040. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25041. */
  25042. extractPoints( divisions ) {
  25043. return {
  25044. shape: this.getPoints( divisions ),
  25045. holes: this.getPointsHoles( divisions )
  25046. };
  25047. }
  25048. copy( source ) {
  25049. super.copy( source );
  25050. this.holes = [];
  25051. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25052. const hole = source.holes[ i ];
  25053. this.holes.push( hole.clone() );
  25054. }
  25055. return this;
  25056. }
  25057. toJSON() {
  25058. const data = super.toJSON();
  25059. data.uuid = this.uuid;
  25060. data.holes = [];
  25061. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25062. const hole = this.holes[ i ];
  25063. data.holes.push( hole.toJSON() );
  25064. }
  25065. return data;
  25066. }
  25067. fromJSON( json ) {
  25068. super.fromJSON( json );
  25069. this.uuid = json.uuid;
  25070. this.holes = [];
  25071. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25072. const hole = json.holes[ i ];
  25073. this.holes.push( new Path().fromJSON( hole ) );
  25074. }
  25075. return this;
  25076. }
  25077. }
  25078. /* eslint-disable */
  25079. // copy of mapbox/earcut version 3.0.1
  25080. // https://github.com/mapbox/earcut/tree/v3.0.1
  25081. function earcut(data, holeIndices, dim = 2) {
  25082. const hasHoles = holeIndices && holeIndices.length;
  25083. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25084. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25085. const triangles = [];
  25086. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25087. let minX, minY, invSize;
  25088. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25089. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25090. if (data.length > 80 * dim) {
  25091. minX = Infinity;
  25092. minY = Infinity;
  25093. let maxX = -Infinity;
  25094. let maxY = -Infinity;
  25095. for (let i = dim; i < outerLen; i += dim) {
  25096. const x = data[i];
  25097. const y = data[i + 1];
  25098. if (x < minX) minX = x;
  25099. if (y < minY) minY = y;
  25100. if (x > maxX) maxX = x;
  25101. if (y > maxY) maxY = y;
  25102. }
  25103. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25104. invSize = Math.max(maxX - minX, maxY - minY);
  25105. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25106. }
  25107. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25108. return triangles;
  25109. }
  25110. // create a circular doubly linked list from polygon points in the specified winding order
  25111. function linkedList(data, start, end, dim, clockwise) {
  25112. let last;
  25113. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25114. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25115. } else {
  25116. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25117. }
  25118. if (last && equals(last, last.next)) {
  25119. removeNode(last);
  25120. last = last.next;
  25121. }
  25122. return last;
  25123. }
  25124. // eliminate colinear or duplicate points
  25125. function filterPoints(start, end) {
  25126. if (!start) return start;
  25127. if (!end) end = start;
  25128. let p = start,
  25129. again;
  25130. do {
  25131. again = false;
  25132. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25133. removeNode(p);
  25134. p = end = p.prev;
  25135. if (p === p.next) break;
  25136. again = true;
  25137. } else {
  25138. p = p.next;
  25139. }
  25140. } while (again || p !== end);
  25141. return end;
  25142. }
  25143. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25144. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25145. if (!ear) return;
  25146. // interlink polygon nodes in z-order
  25147. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25148. let stop = ear;
  25149. // iterate through ears, slicing them one by one
  25150. while (ear.prev !== ear.next) {
  25151. const prev = ear.prev;
  25152. const next = ear.next;
  25153. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25154. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25155. removeNode(ear);
  25156. // skipping the next vertex leads to less sliver triangles
  25157. ear = next.next;
  25158. stop = next.next;
  25159. continue;
  25160. }
  25161. ear = next;
  25162. // if we looped through the whole remaining polygon and can't find any more ears
  25163. if (ear === stop) {
  25164. // try filtering points and slicing again
  25165. if (!pass) {
  25166. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25167. // if this didn't work, try curing all small self-intersections locally
  25168. } else if (pass === 1) {
  25169. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25170. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25171. // as a last resort, try splitting the remaining polygon into two
  25172. } else if (pass === 2) {
  25173. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25174. }
  25175. break;
  25176. }
  25177. }
  25178. }
  25179. // check whether a polygon node forms a valid ear with adjacent nodes
  25180. function isEar(ear) {
  25181. const a = ear.prev,
  25182. b = ear,
  25183. c = ear.next;
  25184. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25185. // now make sure we don't have other points inside the potential ear
  25186. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25187. // triangle bbox
  25188. const x0 = Math.min(ax, bx, cx),
  25189. y0 = Math.min(ay, by, cy),
  25190. x1 = Math.max(ax, bx, cx),
  25191. y1 = Math.max(ay, by, cy);
  25192. let p = c.next;
  25193. while (p !== a) {
  25194. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25195. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25196. area(p.prev, p, p.next) >= 0) return false;
  25197. p = p.next;
  25198. }
  25199. return true;
  25200. }
  25201. function isEarHashed(ear, minX, minY, invSize) {
  25202. const a = ear.prev,
  25203. b = ear,
  25204. c = ear.next;
  25205. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25206. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25207. // triangle bbox
  25208. const x0 = Math.min(ax, bx, cx),
  25209. y0 = Math.min(ay, by, cy),
  25210. x1 = Math.max(ax, bx, cx),
  25211. y1 = Math.max(ay, by, cy);
  25212. // z-order range for the current triangle bbox;
  25213. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25214. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25215. let p = ear.prevZ,
  25216. n = ear.nextZ;
  25217. // look for points inside the triangle in both directions
  25218. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25219. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25220. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25221. p = p.prevZ;
  25222. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25223. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25224. n = n.nextZ;
  25225. }
  25226. // look for remaining points in decreasing z-order
  25227. while (p && p.z >= minZ) {
  25228. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25229. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25230. p = p.prevZ;
  25231. }
  25232. // look for remaining points in increasing z-order
  25233. while (n && n.z <= maxZ) {
  25234. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25235. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25236. n = n.nextZ;
  25237. }
  25238. return true;
  25239. }
  25240. // go through all polygon nodes and cure small local self-intersections
  25241. function cureLocalIntersections(start, triangles) {
  25242. let p = start;
  25243. do {
  25244. const a = p.prev,
  25245. b = p.next.next;
  25246. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25247. triangles.push(a.i, p.i, b.i);
  25248. // remove two nodes involved
  25249. removeNode(p);
  25250. removeNode(p.next);
  25251. p = start = b;
  25252. }
  25253. p = p.next;
  25254. } while (p !== start);
  25255. return filterPoints(p);
  25256. }
  25257. // try splitting polygon into two and triangulate them independently
  25258. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25259. // look for a valid diagonal that divides the polygon into two
  25260. let a = start;
  25261. do {
  25262. let b = a.next.next;
  25263. while (b !== a.prev) {
  25264. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25265. // split the polygon in two by the diagonal
  25266. let c = splitPolygon(a, b);
  25267. // filter colinear points around the cuts
  25268. a = filterPoints(a, a.next);
  25269. c = filterPoints(c, c.next);
  25270. // run earcut on each half
  25271. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25272. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25273. return;
  25274. }
  25275. b = b.next;
  25276. }
  25277. a = a.next;
  25278. } while (a !== start);
  25279. }
  25280. // link every hole into the outer loop, producing a single-ring polygon without holes
  25281. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25282. const queue = [];
  25283. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25284. const start = holeIndices[i] * dim;
  25285. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25286. const list = linkedList(data, start, end, dim, false);
  25287. if (list === list.next) list.steiner = true;
  25288. queue.push(getLeftmost(list));
  25289. }
  25290. queue.sort(compareXYSlope);
  25291. // process holes from left to right
  25292. for (let i = 0; i < queue.length; i++) {
  25293. outerNode = eliminateHole(queue[i], outerNode);
  25294. }
  25295. return outerNode;
  25296. }
  25297. function compareXYSlope(a, b) {
  25298. let result = a.x - b.x;
  25299. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25300. // the bridge to the outer shell is always the point that they meet at.
  25301. if (result === 0) {
  25302. result = a.y - b.y;
  25303. if (result === 0) {
  25304. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25305. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25306. result = aSlope - bSlope;
  25307. }
  25308. }
  25309. return result;
  25310. }
  25311. // find a bridge between vertices that connects hole with an outer ring and and link it
  25312. function eliminateHole(hole, outerNode) {
  25313. const bridge = findHoleBridge(hole, outerNode);
  25314. if (!bridge) {
  25315. return outerNode;
  25316. }
  25317. const bridgeReverse = splitPolygon(bridge, hole);
  25318. // filter collinear points around the cuts
  25319. filterPoints(bridgeReverse, bridgeReverse.next);
  25320. return filterPoints(bridge, bridge.next);
  25321. }
  25322. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25323. function findHoleBridge(hole, outerNode) {
  25324. let p = outerNode;
  25325. const hx = hole.x;
  25326. const hy = hole.y;
  25327. let qx = -Infinity;
  25328. let m;
  25329. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25330. // segment's endpoint with lesser x will be potential connection point
  25331. // unless they intersect at a vertex, then choose the vertex
  25332. if (equals(hole, p)) return p;
  25333. do {
  25334. if (equals(hole, p.next)) return p.next;
  25335. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25336. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25337. if (x <= hx && x > qx) {
  25338. qx = x;
  25339. m = p.x < p.next.x ? p : p.next;
  25340. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25341. }
  25342. }
  25343. p = p.next;
  25344. } while (p !== outerNode);
  25345. if (!m) return null;
  25346. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25347. // if there are no points found, we have a valid connection;
  25348. // otherwise choose the point of the minimum angle with the ray as connection point
  25349. const stop = m;
  25350. const mx = m.x;
  25351. const my = m.y;
  25352. let tanMin = Infinity;
  25353. p = m;
  25354. do {
  25355. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25356. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25357. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25358. if (locallyInside(p, hole) &&
  25359. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25360. m = p;
  25361. tanMin = tan;
  25362. }
  25363. }
  25364. p = p.next;
  25365. } while (p !== stop);
  25366. return m;
  25367. }
  25368. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25369. function sectorContainsSector(m, p) {
  25370. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25371. }
  25372. // interlink polygon nodes in z-order
  25373. function indexCurve(start, minX, minY, invSize) {
  25374. let p = start;
  25375. do {
  25376. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25377. p.prevZ = p.prev;
  25378. p.nextZ = p.next;
  25379. p = p.next;
  25380. } while (p !== start);
  25381. p.prevZ.nextZ = null;
  25382. p.prevZ = null;
  25383. sortLinked(p);
  25384. }
  25385. // Simon Tatham's linked list merge sort algorithm
  25386. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25387. function sortLinked(list) {
  25388. let numMerges;
  25389. let inSize = 1;
  25390. do {
  25391. let p = list;
  25392. let e;
  25393. list = null;
  25394. let tail = null;
  25395. numMerges = 0;
  25396. while (p) {
  25397. numMerges++;
  25398. let q = p;
  25399. let pSize = 0;
  25400. for (let i = 0; i < inSize; i++) {
  25401. pSize++;
  25402. q = q.nextZ;
  25403. if (!q) break;
  25404. }
  25405. let qSize = inSize;
  25406. while (pSize > 0 || (qSize > 0 && q)) {
  25407. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25408. e = p;
  25409. p = p.nextZ;
  25410. pSize--;
  25411. } else {
  25412. e = q;
  25413. q = q.nextZ;
  25414. qSize--;
  25415. }
  25416. if (tail) tail.nextZ = e;
  25417. else list = e;
  25418. e.prevZ = tail;
  25419. tail = e;
  25420. }
  25421. p = q;
  25422. }
  25423. tail.nextZ = null;
  25424. inSize *= 2;
  25425. } while (numMerges > 1);
  25426. return list;
  25427. }
  25428. // z-order of a point given coords and inverse of the longer side of data bbox
  25429. function zOrder(x, y, minX, minY, invSize) {
  25430. // coords are transformed into non-negative 15-bit integer range
  25431. x = (x - minX) * invSize | 0;
  25432. y = (y - minY) * invSize | 0;
  25433. x = (x | (x << 8)) & 0x00FF00FF;
  25434. x = (x | (x << 4)) & 0x0F0F0F0F;
  25435. x = (x | (x << 2)) & 0x33333333;
  25436. x = (x | (x << 1)) & 0x55555555;
  25437. y = (y | (y << 8)) & 0x00FF00FF;
  25438. y = (y | (y << 4)) & 0x0F0F0F0F;
  25439. y = (y | (y << 2)) & 0x33333333;
  25440. y = (y | (y << 1)) & 0x55555555;
  25441. return x | (y << 1);
  25442. }
  25443. // find the leftmost node of a polygon ring
  25444. function getLeftmost(start) {
  25445. let p = start,
  25446. leftmost = start;
  25447. do {
  25448. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25449. p = p.next;
  25450. } while (p !== start);
  25451. return leftmost;
  25452. }
  25453. // check if a point lies within a convex triangle
  25454. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25455. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25456. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25457. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25458. }
  25459. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25460. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25461. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25462. }
  25463. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25464. function isValidDiagonal(a, b) {
  25465. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
  25466. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25467. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25468. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25469. }
  25470. // signed area of a triangle
  25471. function area(p, q, r) {
  25472. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25473. }
  25474. // check if two points are equal
  25475. function equals(p1, p2) {
  25476. return p1.x === p2.x && p1.y === p2.y;
  25477. }
  25478. // check if two segments intersect
  25479. function intersects(p1, q1, p2, q2) {
  25480. const o1 = sign(area(p1, q1, p2));
  25481. const o2 = sign(area(p1, q1, q2));
  25482. const o3 = sign(area(p2, q2, p1));
  25483. const o4 = sign(area(p2, q2, q1));
  25484. if (o1 !== o2 && o3 !== o4) return true; // general case
  25485. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25486. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25487. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25488. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25489. return false;
  25490. }
  25491. // for collinear points p, q, r, check if point q lies on segment pr
  25492. function onSegment(p, q, r) {
  25493. return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
  25494. }
  25495. function sign(num) {
  25496. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25497. }
  25498. // check if a polygon diagonal intersects any polygon segments
  25499. function intersectsPolygon(a, b) {
  25500. let p = a;
  25501. do {
  25502. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25503. intersects(p, p.next, a, b)) return true;
  25504. p = p.next;
  25505. } while (p !== a);
  25506. return false;
  25507. }
  25508. // check if a polygon diagonal is locally inside the polygon
  25509. function locallyInside(a, b) {
  25510. return area(a.prev, a, a.next) < 0 ?
  25511. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25512. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25513. }
  25514. // check if the middle point of a polygon diagonal is inside the polygon
  25515. function middleInside(a, b) {
  25516. let p = a;
  25517. let inside = false;
  25518. const px = (a.x + b.x) / 2;
  25519. const py = (a.y + b.y) / 2;
  25520. do {
  25521. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25522. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25523. inside = !inside;
  25524. p = p.next;
  25525. } while (p !== a);
  25526. return inside;
  25527. }
  25528. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25529. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25530. function splitPolygon(a, b) {
  25531. const a2 = createNode(a.i, a.x, a.y),
  25532. b2 = createNode(b.i, b.x, b.y),
  25533. an = a.next,
  25534. bp = b.prev;
  25535. a.next = b;
  25536. b.prev = a;
  25537. a2.next = an;
  25538. an.prev = a2;
  25539. b2.next = a2;
  25540. a2.prev = b2;
  25541. bp.next = b2;
  25542. b2.prev = bp;
  25543. return b2;
  25544. }
  25545. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25546. function insertNode(i, x, y, last) {
  25547. const p = createNode(i, x, y);
  25548. if (!last) {
  25549. p.prev = p;
  25550. p.next = p;
  25551. } else {
  25552. p.next = last.next;
  25553. p.prev = last;
  25554. last.next.prev = p;
  25555. last.next = p;
  25556. }
  25557. return p;
  25558. }
  25559. function removeNode(p) {
  25560. p.next.prev = p.prev;
  25561. p.prev.next = p.next;
  25562. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25563. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25564. }
  25565. function createNode(i, x, y) {
  25566. return {
  25567. i, // vertex index in coordinates array
  25568. x, y, // vertex coordinates
  25569. prev: null, // previous and next vertex nodes in a polygon ring
  25570. next: null,
  25571. z: 0, // z-order curve value
  25572. prevZ: null, // previous and next nodes in z-order
  25573. nextZ: null,
  25574. steiner: false // indicates whether this is a steiner point
  25575. };
  25576. }
  25577. function signedArea(data, start, end, dim) {
  25578. let sum = 0;
  25579. for (let i = start, j = end - dim; i < end; i += dim) {
  25580. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25581. j = i;
  25582. }
  25583. return sum;
  25584. }
  25585. class Earcut {
  25586. /**
  25587. * Triangulates the given shape definition by returning an array of triangles.
  25588. *
  25589. * @param {Array<number>} data - An array with 2D points.
  25590. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25591. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25592. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25593. * representing vertex indices.
  25594. */
  25595. static triangulate( data, holeIndices, dim = 2 ) {
  25596. return earcut( data, holeIndices, dim );
  25597. }
  25598. }
  25599. /**
  25600. * A class containing utility functions for shapes.
  25601. *
  25602. * @hideconstructor
  25603. */
  25604. class ShapeUtils {
  25605. /**
  25606. * Calculate area of a ( 2D ) contour polygon.
  25607. *
  25608. * @param {Array<Vector2>} contour - An array of 2D points.
  25609. * @return {number} The area.
  25610. */
  25611. static area( contour ) {
  25612. const n = contour.length;
  25613. let a = 0.0;
  25614. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25615. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25616. }
  25617. return a * 0.5;
  25618. }
  25619. /**
  25620. * Returns `true` if the given contour uses a clockwise winding order.
  25621. *
  25622. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25623. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25624. */
  25625. static isClockWise( pts ) {
  25626. return ShapeUtils.area( pts ) < 0;
  25627. }
  25628. /**
  25629. * Triangulates the given shape definition.
  25630. *
  25631. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25632. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25633. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25634. */
  25635. static triangulateShape( contour, holes ) {
  25636. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25637. const holeIndices = []; // array of hole indices
  25638. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25639. removeDupEndPts( contour );
  25640. addContour( vertices, contour );
  25641. //
  25642. let holeIndex = contour.length;
  25643. holes.forEach( removeDupEndPts );
  25644. for ( let i = 0; i < holes.length; i ++ ) {
  25645. holeIndices.push( holeIndex );
  25646. holeIndex += holes[ i ].length;
  25647. addContour( vertices, holes[ i ] );
  25648. }
  25649. //
  25650. const triangles = Earcut.triangulate( vertices, holeIndices );
  25651. //
  25652. for ( let i = 0; i < triangles.length; i += 3 ) {
  25653. faces.push( triangles.slice( i, i + 3 ) );
  25654. }
  25655. return faces;
  25656. }
  25657. }
  25658. function removeDupEndPts( points ) {
  25659. const l = points.length;
  25660. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25661. points.pop();
  25662. }
  25663. }
  25664. function addContour( vertices, contour ) {
  25665. for ( let i = 0; i < contour.length; i ++ ) {
  25666. vertices.push( contour[ i ].x );
  25667. vertices.push( contour[ i ].y );
  25668. }
  25669. }
  25670. /**
  25671. * Creates extruded geometry from a path shape.
  25672. *
  25673. * ```js
  25674. * const length = 12, width = 8;
  25675. *
  25676. * const shape = new THREE.Shape();
  25677. * shape.moveTo( 0,0 );
  25678. * shape.lineTo( 0, width );
  25679. * shape.lineTo( length, width );
  25680. * shape.lineTo( length, 0 );
  25681. * shape.lineTo( 0, 0 );
  25682. *
  25683. * const geometry = new THREE.ExtrudeGeometry( shape );
  25684. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25685. * const mesh = new THREE.Mesh( geometry, material ) ;
  25686. * scene.add( mesh );
  25687. * ```
  25688. *
  25689. * @augments BufferGeometry
  25690. */
  25691. class ExtrudeGeometry extends BufferGeometry {
  25692. /**
  25693. * Constructs a new extrude geometry.
  25694. *
  25695. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25696. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25697. */
  25698. constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( -0.5, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), options = {} ) {
  25699. super();
  25700. this.type = 'ExtrudeGeometry';
  25701. /**
  25702. * Holds the constructor parameters that have been
  25703. * used to generate the geometry. Any modification
  25704. * after instantiation does not change the geometry.
  25705. *
  25706. * @type {Object}
  25707. */
  25708. this.parameters = {
  25709. shapes: shapes,
  25710. options: options
  25711. };
  25712. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25713. const scope = this;
  25714. const verticesArray = [];
  25715. const uvArray = [];
  25716. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25717. const shape = shapes[ i ];
  25718. addShape( shape );
  25719. }
  25720. // build geometry
  25721. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25722. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25723. this.computeVertexNormals();
  25724. // functions
  25725. function addShape( shape ) {
  25726. const placeholder = [];
  25727. // options
  25728. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25729. const steps = options.steps !== undefined ? options.steps : 1;
  25730. const depth = options.depth !== undefined ? options.depth : 1;
  25731. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25732. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25733. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25734. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25735. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25736. const extrudePath = options.extrudePath;
  25737. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25738. //
  25739. let extrudePts, extrudeByPath = false;
  25740. let splineTube, binormal, normal, position2;
  25741. if ( extrudePath ) {
  25742. extrudePts = extrudePath.getSpacedPoints( steps );
  25743. extrudeByPath = true;
  25744. bevelEnabled = false; // bevels not supported for path extrusion
  25745. // SETUP TNB variables
  25746. // TODO1 - have a .isClosed in spline?
  25747. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25748. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25749. binormal = new Vector3();
  25750. normal = new Vector3();
  25751. position2 = new Vector3();
  25752. }
  25753. // Safeguards if bevels are not enabled
  25754. if ( ! bevelEnabled ) {
  25755. bevelSegments = 0;
  25756. bevelThickness = 0;
  25757. bevelSize = 0;
  25758. bevelOffset = 0;
  25759. }
  25760. // Variables initialization
  25761. const shapePoints = shape.extractPoints( curveSegments );
  25762. let vertices = shapePoints.shape;
  25763. const holes = shapePoints.holes;
  25764. const reverse = ! ShapeUtils.isClockWise( vertices );
  25765. if ( reverse ) {
  25766. vertices = vertices.reverse();
  25767. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25768. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25769. const ahole = holes[ h ];
  25770. if ( ShapeUtils.isClockWise( ahole ) ) {
  25771. holes[ h ] = ahole.reverse();
  25772. }
  25773. }
  25774. }
  25775. /**Merges index-adjacent points that are within a threshold distance of each other. Array is modified in-place. Threshold distance is empirical, and scaled based on the magnitude of point coordinates.
  25776. * @param {Array<Vector2>} points
  25777. */
  25778. function mergeOverlappingPoints( points ) {
  25779. const THRESHOLD = 1e-10;
  25780. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25781. let prevPos = points[ 0 ];
  25782. for ( let i = 1; i <= points.length; i ++ ) {
  25783. const currentIndex = i % points.length;
  25784. const currentPos = points[ currentIndex ];
  25785. const dx = currentPos.x - prevPos.x;
  25786. const dy = currentPos.y - prevPos.y;
  25787. const distSq = dx * dx + dy * dy;
  25788. const scalingFactorSqrt = Math.max(
  25789. Math.abs( currentPos.x ),
  25790. Math.abs( currentPos.y ),
  25791. Math.abs( prevPos.x ),
  25792. Math.abs( prevPos.y )
  25793. );
  25794. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25795. if ( distSq <= thresholdSqScaled ) {
  25796. points.splice( currentIndex, 1 );
  25797. i --;
  25798. continue;
  25799. }
  25800. prevPos = currentPos;
  25801. }
  25802. }
  25803. mergeOverlappingPoints( vertices );
  25804. holes.forEach( mergeOverlappingPoints );
  25805. const numHoles = holes.length;
  25806. /* Vertices */
  25807. const contour = vertices; // vertices has all points but contour has only points of circumference
  25808. for ( let h = 0; h < numHoles; h ++ ) {
  25809. const ahole = holes[ h ];
  25810. vertices = vertices.concat( ahole );
  25811. }
  25812. function scalePt2( pt, vec, size ) {
  25813. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  25814. return pt.clone().addScaledVector( vec, size );
  25815. }
  25816. const vlen = vertices.length;
  25817. // Find directions for point movement
  25818. function getBevelVec( inPt, inPrev, inNext ) {
  25819. // computes for inPt the corresponding point inPt' on a new contour
  25820. // shifted by 1 unit (length of normalized vector) to the left
  25821. // if we walk along contour clockwise, this new contour is outside the old one
  25822. //
  25823. // inPt' is the intersection of the two lines parallel to the two
  25824. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25825. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25826. // good reading for geometry algorithms (here: line-line intersection)
  25827. // http://geomalgorithms.com/a05-_intersect-1.html
  25828. const v_prev_x = inPt.x - inPrev.x,
  25829. v_prev_y = inPt.y - inPrev.y;
  25830. const v_next_x = inNext.x - inPt.x,
  25831. v_next_y = inNext.y - inPt.y;
  25832. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25833. // check for collinear edges
  25834. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25835. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25836. // not collinear
  25837. // length of vectors for normalizing
  25838. const v_prev_len = Math.sqrt( v_prev_lensq );
  25839. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25840. // shift adjacent points by unit vectors to the left
  25841. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25842. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25843. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25844. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25845. // scaling factor for v_prev to intersection point
  25846. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25847. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25848. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25849. // vector from inPt to intersection point
  25850. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25851. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25852. // Don't normalize!, otherwise sharp corners become ugly
  25853. // but prevent crazy spikes
  25854. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25855. if ( v_trans_lensq <= 2 ) {
  25856. return new Vector2( v_trans_x, v_trans_y );
  25857. } else {
  25858. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25859. }
  25860. } else {
  25861. // handle special case of collinear edges
  25862. let direction_eq = false; // assumes: opposite
  25863. if ( v_prev_x > Number.EPSILON ) {
  25864. if ( v_next_x > Number.EPSILON ) {
  25865. direction_eq = true;
  25866. }
  25867. } else {
  25868. if ( v_prev_x < - Number.EPSILON ) {
  25869. if ( v_next_x < - Number.EPSILON ) {
  25870. direction_eq = true;
  25871. }
  25872. } else {
  25873. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25874. direction_eq = true;
  25875. }
  25876. }
  25877. }
  25878. if ( direction_eq ) {
  25879. // console.log("Warning: lines are a straight sequence");
  25880. v_trans_x = - v_prev_y;
  25881. v_trans_y = v_prev_x;
  25882. shrink_by = Math.sqrt( v_prev_lensq );
  25883. } else {
  25884. // console.log("Warning: lines are a straight spike");
  25885. v_trans_x = v_prev_x;
  25886. v_trans_y = v_prev_y;
  25887. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25888. }
  25889. }
  25890. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25891. }
  25892. const contourMovements = [];
  25893. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25894. if ( j === il ) j = 0;
  25895. if ( k === il ) k = 0;
  25896. // (j)---(i)---(k)
  25897. // console.log('i,j,k', i, j , k)
  25898. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25899. }
  25900. const holesMovements = [];
  25901. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25902. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25903. const ahole = holes[ h ];
  25904. oneHoleMovements = [];
  25905. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25906. if ( j === il ) j = 0;
  25907. if ( k === il ) k = 0;
  25908. // (j)---(i)---(k)
  25909. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25910. }
  25911. holesMovements.push( oneHoleMovements );
  25912. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25913. }
  25914. let faces;
  25915. if ( bevelSegments === 0 ) {
  25916. faces = ShapeUtils.triangulateShape( contour, holes );
  25917. } else {
  25918. const contractedContourVertices = [];
  25919. const expandedHoleVertices = [];
  25920. // Loop bevelSegments, 1 for the front, 1 for the back
  25921. for ( let b = 0; b < bevelSegments; b ++ ) {
  25922. //for ( b = bevelSegments; b > 0; b -- ) {
  25923. const t = b / bevelSegments;
  25924. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25925. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25926. // contract shape
  25927. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25928. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25929. v( vert.x, vert.y, - z );
  25930. if ( t === 0 ) contractedContourVertices.push( vert );
  25931. }
  25932. // expand holes
  25933. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25934. const ahole = holes[ h ];
  25935. oneHoleMovements = holesMovements[ h ];
  25936. const oneHoleVertices = [];
  25937. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25938. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25939. v( vert.x, vert.y, - z );
  25940. if ( t === 0 ) oneHoleVertices.push( vert );
  25941. }
  25942. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25943. }
  25944. }
  25945. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25946. }
  25947. const flen = faces.length;
  25948. const bs = bevelSize + bevelOffset;
  25949. // Back facing vertices
  25950. for ( let i = 0; i < vlen; i ++ ) {
  25951. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25952. if ( ! extrudeByPath ) {
  25953. v( vert.x, vert.y, 0 );
  25954. } else {
  25955. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25956. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25957. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25958. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25959. v( position2.x, position2.y, position2.z );
  25960. }
  25961. }
  25962. // Add stepped vertices...
  25963. // Including front facing vertices
  25964. for ( let s = 1; s <= steps; s ++ ) {
  25965. for ( let i = 0; i < vlen; i ++ ) {
  25966. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25967. if ( ! extrudeByPath ) {
  25968. v( vert.x, vert.y, depth / steps * s );
  25969. } else {
  25970. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25971. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25972. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25973. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25974. v( position2.x, position2.y, position2.z );
  25975. }
  25976. }
  25977. }
  25978. // Add bevel segments planes
  25979. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25980. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25981. const t = b / bevelSegments;
  25982. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25983. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25984. // contract shape
  25985. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25986. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25987. v( vert.x, vert.y, depth + z );
  25988. }
  25989. // expand holes
  25990. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25991. const ahole = holes[ h ];
  25992. oneHoleMovements = holesMovements[ h ];
  25993. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25994. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25995. if ( ! extrudeByPath ) {
  25996. v( vert.x, vert.y, depth + z );
  25997. } else {
  25998. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25999. }
  26000. }
  26001. }
  26002. }
  26003. /* Faces */
  26004. // Top and bottom faces
  26005. buildLidFaces();
  26006. // Sides faces
  26007. buildSideFaces();
  26008. ///// Internal functions
  26009. function buildLidFaces() {
  26010. const start = verticesArray.length / 3;
  26011. if ( bevelEnabled ) {
  26012. let layer = 0; // steps + 1
  26013. let offset = vlen * layer;
  26014. // Bottom faces
  26015. for ( let i = 0; i < flen; i ++ ) {
  26016. const face = faces[ i ];
  26017. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26018. }
  26019. layer = steps + bevelSegments * 2;
  26020. offset = vlen * layer;
  26021. // Top faces
  26022. for ( let i = 0; i < flen; i ++ ) {
  26023. const face = faces[ i ];
  26024. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26025. }
  26026. } else {
  26027. // Bottom faces
  26028. for ( let i = 0; i < flen; i ++ ) {
  26029. const face = faces[ i ];
  26030. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26031. }
  26032. // Top faces
  26033. for ( let i = 0; i < flen; i ++ ) {
  26034. const face = faces[ i ];
  26035. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26036. }
  26037. }
  26038. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26039. }
  26040. // Create faces for the z-sides of the shape
  26041. function buildSideFaces() {
  26042. const start = verticesArray.length / 3;
  26043. let layeroffset = 0;
  26044. sidewalls( contour, layeroffset );
  26045. layeroffset += contour.length;
  26046. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26047. const ahole = holes[ h ];
  26048. sidewalls( ahole, layeroffset );
  26049. //, true
  26050. layeroffset += ahole.length;
  26051. }
  26052. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26053. }
  26054. function sidewalls( contour, layeroffset ) {
  26055. let i = contour.length;
  26056. while ( -- i >= 0 ) {
  26057. const j = i;
  26058. let k = i - 1;
  26059. if ( k < 0 ) k = contour.length - 1;
  26060. //console.log('b', i,j, i-1, k,vertices.length);
  26061. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26062. const slen1 = vlen * s;
  26063. const slen2 = vlen * ( s + 1 );
  26064. const a = layeroffset + j + slen1,
  26065. b = layeroffset + k + slen1,
  26066. c = layeroffset + k + slen2,
  26067. d = layeroffset + j + slen2;
  26068. f4( a, b, c, d );
  26069. }
  26070. }
  26071. }
  26072. function v( x, y, z ) {
  26073. placeholder.push( x );
  26074. placeholder.push( y );
  26075. placeholder.push( z );
  26076. }
  26077. function f3( a, b, c ) {
  26078. addVertex( a );
  26079. addVertex( b );
  26080. addVertex( c );
  26081. const nextIndex = verticesArray.length / 3;
  26082. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26083. addUV( uvs[ 0 ] );
  26084. addUV( uvs[ 1 ] );
  26085. addUV( uvs[ 2 ] );
  26086. }
  26087. function f4( a, b, c, d ) {
  26088. addVertex( a );
  26089. addVertex( b );
  26090. addVertex( d );
  26091. addVertex( b );
  26092. addVertex( c );
  26093. addVertex( d );
  26094. const nextIndex = verticesArray.length / 3;
  26095. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26096. addUV( uvs[ 0 ] );
  26097. addUV( uvs[ 1 ] );
  26098. addUV( uvs[ 3 ] );
  26099. addUV( uvs[ 1 ] );
  26100. addUV( uvs[ 2 ] );
  26101. addUV( uvs[ 3 ] );
  26102. }
  26103. function addVertex( index ) {
  26104. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26105. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26106. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26107. }
  26108. function addUV( vector2 ) {
  26109. uvArray.push( vector2.x );
  26110. uvArray.push( vector2.y );
  26111. }
  26112. }
  26113. }
  26114. copy( source ) {
  26115. super.copy( source );
  26116. this.parameters = Object.assign( {}, source.parameters );
  26117. return this;
  26118. }
  26119. toJSON() {
  26120. const data = super.toJSON();
  26121. const shapes = this.parameters.shapes;
  26122. const options = this.parameters.options;
  26123. return toJSON$1( shapes, options, data );
  26124. }
  26125. /**
  26126. * Factory method for creating an instance of this class from the given
  26127. * JSON object.
  26128. *
  26129. * @param {Object} data - A JSON object representing the serialized geometry.
  26130. * @param {Array<Shape>} shapes - An array of shapes.
  26131. * @return {ExtrudeGeometry} A new instance.
  26132. */
  26133. static fromJSON( data, shapes ) {
  26134. const geometryShapes = [];
  26135. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26136. const shape = shapes[ data.shapes[ j ] ];
  26137. geometryShapes.push( shape );
  26138. }
  26139. const extrudePath = data.options.extrudePath;
  26140. if ( extrudePath !== undefined ) {
  26141. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26142. }
  26143. return new ExtrudeGeometry( geometryShapes, data.options );
  26144. }
  26145. }
  26146. const WorldUVGenerator = {
  26147. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26148. const a_x = vertices[ indexA * 3 ];
  26149. const a_y = vertices[ indexA * 3 + 1 ];
  26150. const b_x = vertices[ indexB * 3 ];
  26151. const b_y = vertices[ indexB * 3 + 1 ];
  26152. const c_x = vertices[ indexC * 3 ];
  26153. const c_y = vertices[ indexC * 3 + 1 ];
  26154. return [
  26155. new Vector2( a_x, a_y ),
  26156. new Vector2( b_x, b_y ),
  26157. new Vector2( c_x, c_y )
  26158. ];
  26159. },
  26160. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26161. const a_x = vertices[ indexA * 3 ];
  26162. const a_y = vertices[ indexA * 3 + 1 ];
  26163. const a_z = vertices[ indexA * 3 + 2 ];
  26164. const b_x = vertices[ indexB * 3 ];
  26165. const b_y = vertices[ indexB * 3 + 1 ];
  26166. const b_z = vertices[ indexB * 3 + 2 ];
  26167. const c_x = vertices[ indexC * 3 ];
  26168. const c_y = vertices[ indexC * 3 + 1 ];
  26169. const c_z = vertices[ indexC * 3 + 2 ];
  26170. const d_x = vertices[ indexD * 3 ];
  26171. const d_y = vertices[ indexD * 3 + 1 ];
  26172. const d_z = vertices[ indexD * 3 + 2 ];
  26173. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26174. return [
  26175. new Vector2( a_x, 1 - a_z ),
  26176. new Vector2( b_x, 1 - b_z ),
  26177. new Vector2( c_x, 1 - c_z ),
  26178. new Vector2( d_x, 1 - d_z )
  26179. ];
  26180. } else {
  26181. return [
  26182. new Vector2( a_y, 1 - a_z ),
  26183. new Vector2( b_y, 1 - b_z ),
  26184. new Vector2( c_y, 1 - c_z ),
  26185. new Vector2( d_y, 1 - d_z )
  26186. ];
  26187. }
  26188. }
  26189. };
  26190. function toJSON$1( shapes, options, data ) {
  26191. data.shapes = [];
  26192. if ( Array.isArray( shapes ) ) {
  26193. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26194. const shape = shapes[ i ];
  26195. data.shapes.push( shape.uuid );
  26196. }
  26197. } else {
  26198. data.shapes.push( shapes.uuid );
  26199. }
  26200. data.options = Object.assign( {}, options );
  26201. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26202. return data;
  26203. }
  26204. /**
  26205. * A geometry class for representing an icosahedron.
  26206. *
  26207. * ```js
  26208. * const geometry = new THREE.IcosahedronGeometry();
  26209. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26210. * const icosahedron = new THREE.Mesh( geometry, material );
  26211. * scene.add( icosahedron );
  26212. * ```
  26213. *
  26214. * @augments PolyhedronGeometry
  26215. */
  26216. class IcosahedronGeometry extends PolyhedronGeometry {
  26217. /**
  26218. * Constructs a new icosahedron geometry.
  26219. *
  26220. * @param {number} [radius=1] - Radius of the icosahedron.
  26221. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26222. */
  26223. constructor( radius = 1, detail = 0 ) {
  26224. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26225. const vertices = [
  26226. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26227. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26228. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26229. ];
  26230. const indices = [
  26231. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26232. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26233. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26234. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26235. ];
  26236. super( vertices, indices, radius, detail );
  26237. this.type = 'IcosahedronGeometry';
  26238. /**
  26239. * Holds the constructor parameters that have been
  26240. * used to generate the geometry. Any modification
  26241. * after instantiation does not change the geometry.
  26242. *
  26243. * @type {Object}
  26244. */
  26245. this.parameters = {
  26246. radius: radius,
  26247. detail: detail
  26248. };
  26249. }
  26250. /**
  26251. * Factory method for creating an instance of this class from the given
  26252. * JSON object.
  26253. *
  26254. * @param {Object} data - A JSON object representing the serialized geometry.
  26255. * @return {IcosahedronGeometry} A new instance.
  26256. */
  26257. static fromJSON( data ) {
  26258. return new IcosahedronGeometry( data.radius, data.detail );
  26259. }
  26260. }
  26261. /**
  26262. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26263. *
  26264. * ```js
  26265. * const points = [];
  26266. * for ( let i = 0; i < 10; i ++ ) {
  26267. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26268. * }
  26269. * const geometry = new THREE.LatheGeometry( points );
  26270. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26271. * const lathe = new THREE.Mesh( geometry, material );
  26272. * scene.add( lathe );
  26273. * ```
  26274. *
  26275. * @augments BufferGeometry
  26276. */
  26277. class LatheGeometry extends BufferGeometry {
  26278. /**
  26279. * Constructs a new lathe geometry.
  26280. *
  26281. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26282. * must be greater than zero.
  26283. * @param {number} [segments=12] - The number of circumference segments to generate.
  26284. * @param {number} [phiStart=0] - The starting angle in radians.
  26285. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26286. * closed lathe, less than 2PI is a portion.
  26287. */
  26288. constructor( points = [ new Vector2( 0, -0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  26289. super();
  26290. this.type = 'LatheGeometry';
  26291. /**
  26292. * Holds the constructor parameters that have been
  26293. * used to generate the geometry. Any modification
  26294. * after instantiation does not change the geometry.
  26295. *
  26296. * @type {Object}
  26297. */
  26298. this.parameters = {
  26299. points: points,
  26300. segments: segments,
  26301. phiStart: phiStart,
  26302. phiLength: phiLength
  26303. };
  26304. segments = Math.floor( segments );
  26305. // clamp phiLength so it's in range of [ 0, 2PI ]
  26306. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26307. // buffers
  26308. const indices = [];
  26309. const vertices = [];
  26310. const uvs = [];
  26311. const initNormals = [];
  26312. const normals = [];
  26313. // helper variables
  26314. const inverseSegments = 1.0 / segments;
  26315. const vertex = new Vector3();
  26316. const uv = new Vector2();
  26317. const normal = new Vector3();
  26318. const curNormal = new Vector3();
  26319. const prevNormal = new Vector3();
  26320. let dx = 0;
  26321. let dy = 0;
  26322. // pre-compute normals for initial "meridian"
  26323. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26324. switch ( j ) {
  26325. case 0: // special handling for 1st vertex on path
  26326. dx = points[ j + 1 ].x - points[ j ].x;
  26327. dy = points[ j + 1 ].y - points[ j ].y;
  26328. normal.x = dy * 1.0;
  26329. normal.y = - dx;
  26330. normal.z = dy * 0.0;
  26331. prevNormal.copy( normal );
  26332. normal.normalize();
  26333. initNormals.push( normal.x, normal.y, normal.z );
  26334. break;
  26335. case ( points.length - 1 ): // special handling for last Vertex on path
  26336. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26337. break;
  26338. default: // default handling for all vertices in between
  26339. dx = points[ j + 1 ].x - points[ j ].x;
  26340. dy = points[ j + 1 ].y - points[ j ].y;
  26341. normal.x = dy * 1.0;
  26342. normal.y = - dx;
  26343. normal.z = dy * 0.0;
  26344. curNormal.copy( normal );
  26345. normal.x += prevNormal.x;
  26346. normal.y += prevNormal.y;
  26347. normal.z += prevNormal.z;
  26348. normal.normalize();
  26349. initNormals.push( normal.x, normal.y, normal.z );
  26350. prevNormal.copy( curNormal );
  26351. }
  26352. }
  26353. // generate vertices, uvs and normals
  26354. for ( let i = 0; i <= segments; i ++ ) {
  26355. const phi = phiStart + i * inverseSegments * phiLength;
  26356. const sin = Math.sin( phi );
  26357. const cos = Math.cos( phi );
  26358. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26359. // vertex
  26360. vertex.x = points[ j ].x * sin;
  26361. vertex.y = points[ j ].y;
  26362. vertex.z = points[ j ].x * cos;
  26363. vertices.push( vertex.x, vertex.y, vertex.z );
  26364. // uv
  26365. uv.x = i / segments;
  26366. uv.y = j / ( points.length - 1 );
  26367. uvs.push( uv.x, uv.y );
  26368. // normal
  26369. const x = initNormals[ 3 * j + 0 ] * sin;
  26370. const y = initNormals[ 3 * j + 1 ];
  26371. const z = initNormals[ 3 * j + 0 ] * cos;
  26372. normals.push( x, y, z );
  26373. }
  26374. }
  26375. // indices
  26376. for ( let i = 0; i < segments; i ++ ) {
  26377. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26378. const base = j + i * points.length;
  26379. const a = base;
  26380. const b = base + points.length;
  26381. const c = base + points.length + 1;
  26382. const d = base + 1;
  26383. // faces
  26384. indices.push( a, b, d );
  26385. indices.push( c, d, b );
  26386. }
  26387. }
  26388. // build geometry
  26389. this.setIndex( indices );
  26390. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26391. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26392. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26393. }
  26394. copy( source ) {
  26395. super.copy( source );
  26396. this.parameters = Object.assign( {}, source.parameters );
  26397. return this;
  26398. }
  26399. /**
  26400. * Factory method for creating an instance of this class from the given
  26401. * JSON object.
  26402. *
  26403. * @param {Object} data - A JSON object representing the serialized geometry.
  26404. * @return {LatheGeometry} A new instance.
  26405. */
  26406. static fromJSON( data ) {
  26407. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26408. }
  26409. }
  26410. /**
  26411. * A geometry class for representing an octahedron.
  26412. *
  26413. * ```js
  26414. * const geometry = new THREE.OctahedronGeometry();
  26415. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26416. * const octahedron = new THREE.Mesh( geometry, material );
  26417. * scene.add( octahedron );
  26418. * ```
  26419. *
  26420. * @augments PolyhedronGeometry
  26421. */
  26422. class OctahedronGeometry extends PolyhedronGeometry {
  26423. /**
  26424. * Constructs a new octahedron geometry.
  26425. *
  26426. * @param {number} [radius=1] - Radius of the octahedron.
  26427. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26428. */
  26429. constructor( radius = 1, detail = 0 ) {
  26430. const vertices = [
  26431. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26432. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26433. ];
  26434. const indices = [
  26435. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26436. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26437. 1, 3, 4, 1, 4, 2
  26438. ];
  26439. super( vertices, indices, radius, detail );
  26440. this.type = 'OctahedronGeometry';
  26441. /**
  26442. * Holds the constructor parameters that have been
  26443. * used to generate the geometry. Any modification
  26444. * after instantiation does not change the geometry.
  26445. *
  26446. * @type {Object}
  26447. */
  26448. this.parameters = {
  26449. radius: radius,
  26450. detail: detail
  26451. };
  26452. }
  26453. /**
  26454. * Factory method for creating an instance of this class from the given
  26455. * JSON object.
  26456. *
  26457. * @param {Object} data - A JSON object representing the serialized geometry.
  26458. * @return {OctahedronGeometry} A new instance.
  26459. */
  26460. static fromJSON( data ) {
  26461. return new OctahedronGeometry( data.radius, data.detail );
  26462. }
  26463. }
  26464. /**
  26465. * A geometry class for representing a plane.
  26466. *
  26467. * ```js
  26468. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26469. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26470. * const plane = new THREE.Mesh( geometry, material );
  26471. * scene.add( plane );
  26472. * ```
  26473. *
  26474. * @augments BufferGeometry
  26475. */
  26476. class PlaneGeometry extends BufferGeometry {
  26477. /**
  26478. * Constructs a new plane geometry.
  26479. *
  26480. * @param {number} [width=1] - The width along the X axis.
  26481. * @param {number} [height=1] - The height along the Y axis
  26482. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26483. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26484. */
  26485. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26486. super();
  26487. this.type = 'PlaneGeometry';
  26488. /**
  26489. * Holds the constructor parameters that have been
  26490. * used to generate the geometry. Any modification
  26491. * after instantiation does not change the geometry.
  26492. *
  26493. * @type {Object}
  26494. */
  26495. this.parameters = {
  26496. width: width,
  26497. height: height,
  26498. widthSegments: widthSegments,
  26499. heightSegments: heightSegments
  26500. };
  26501. const width_half = width / 2;
  26502. const height_half = height / 2;
  26503. const gridX = Math.floor( widthSegments );
  26504. const gridY = Math.floor( heightSegments );
  26505. const gridX1 = gridX + 1;
  26506. const gridY1 = gridY + 1;
  26507. const segment_width = width / gridX;
  26508. const segment_height = height / gridY;
  26509. //
  26510. const indices = [];
  26511. const vertices = [];
  26512. const normals = [];
  26513. const uvs = [];
  26514. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26515. const y = iy * segment_height - height_half;
  26516. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26517. const x = ix * segment_width - width_half;
  26518. vertices.push( x, - y, 0 );
  26519. normals.push( 0, 0, 1 );
  26520. uvs.push( ix / gridX );
  26521. uvs.push( 1 - ( iy / gridY ) );
  26522. }
  26523. }
  26524. for ( let iy = 0; iy < gridY; iy ++ ) {
  26525. for ( let ix = 0; ix < gridX; ix ++ ) {
  26526. const a = ix + gridX1 * iy;
  26527. const b = ix + gridX1 * ( iy + 1 );
  26528. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26529. const d = ( ix + 1 ) + gridX1 * iy;
  26530. indices.push( a, b, d );
  26531. indices.push( b, c, d );
  26532. }
  26533. }
  26534. this.setIndex( indices );
  26535. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26536. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26537. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26538. }
  26539. copy( source ) {
  26540. super.copy( source );
  26541. this.parameters = Object.assign( {}, source.parameters );
  26542. return this;
  26543. }
  26544. /**
  26545. * Factory method for creating an instance of this class from the given
  26546. * JSON object.
  26547. *
  26548. * @param {Object} data - A JSON object representing the serialized geometry.
  26549. * @return {PlaneGeometry} A new instance.
  26550. */
  26551. static fromJSON( data ) {
  26552. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26553. }
  26554. }
  26555. /**
  26556. * A class for generating a two-dimensional ring geometry.
  26557. *
  26558. * ```js
  26559. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26560. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26561. * const mesh = new THREE.Mesh( geometry, material );
  26562. * scene.add( mesh );
  26563. * ```
  26564. *
  26565. * @augments BufferGeometry
  26566. */
  26567. class RingGeometry extends BufferGeometry {
  26568. /**
  26569. * Constructs a new ring geometry.
  26570. *
  26571. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26572. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26573. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26574. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26575. * @param {number} [thetaStart=0] - Starting angle in radians.
  26576. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26577. */
  26578. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26579. super();
  26580. this.type = 'RingGeometry';
  26581. /**
  26582. * Holds the constructor parameters that have been
  26583. * used to generate the geometry. Any modification
  26584. * after instantiation does not change the geometry.
  26585. *
  26586. * @type {Object}
  26587. */
  26588. this.parameters = {
  26589. innerRadius: innerRadius,
  26590. outerRadius: outerRadius,
  26591. thetaSegments: thetaSegments,
  26592. phiSegments: phiSegments,
  26593. thetaStart: thetaStart,
  26594. thetaLength: thetaLength
  26595. };
  26596. thetaSegments = Math.max( 3, thetaSegments );
  26597. phiSegments = Math.max( 1, phiSegments );
  26598. // buffers
  26599. const indices = [];
  26600. const vertices = [];
  26601. const normals = [];
  26602. const uvs = [];
  26603. // some helper variables
  26604. let radius = innerRadius;
  26605. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26606. const vertex = new Vector3();
  26607. const uv = new Vector2();
  26608. // generate vertices, normals and uvs
  26609. for ( let j = 0; j <= phiSegments; j ++ ) {
  26610. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26611. // values are generate from the inside of the ring to the outside
  26612. const segment = thetaStart + i / thetaSegments * thetaLength;
  26613. // vertex
  26614. vertex.x = radius * Math.cos( segment );
  26615. vertex.y = radius * Math.sin( segment );
  26616. vertices.push( vertex.x, vertex.y, vertex.z );
  26617. // normal
  26618. normals.push( 0, 0, 1 );
  26619. // uv
  26620. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26621. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26622. uvs.push( uv.x, uv.y );
  26623. }
  26624. // increase the radius for next row of vertices
  26625. radius += radiusStep;
  26626. }
  26627. // indices
  26628. for ( let j = 0; j < phiSegments; j ++ ) {
  26629. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26630. for ( let i = 0; i < thetaSegments; i ++ ) {
  26631. const segment = i + thetaSegmentLevel;
  26632. const a = segment;
  26633. const b = segment + thetaSegments + 1;
  26634. const c = segment + thetaSegments + 2;
  26635. const d = segment + 1;
  26636. // faces
  26637. indices.push( a, b, d );
  26638. indices.push( b, c, d );
  26639. }
  26640. }
  26641. // build geometry
  26642. this.setIndex( indices );
  26643. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26644. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26645. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26646. }
  26647. copy( source ) {
  26648. super.copy( source );
  26649. this.parameters = Object.assign( {}, source.parameters );
  26650. return this;
  26651. }
  26652. /**
  26653. * Factory method for creating an instance of this class from the given
  26654. * JSON object.
  26655. *
  26656. * @param {Object} data - A JSON object representing the serialized geometry.
  26657. * @return {RingGeometry} A new instance.
  26658. */
  26659. static fromJSON( data ) {
  26660. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26661. }
  26662. }
  26663. /**
  26664. * Creates an one-sided polygonal geometry from one or more path shapes.
  26665. *
  26666. * ```js
  26667. * const arcShape = new THREE.Shape()
  26668. * .moveTo( 5, 1 )
  26669. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26670. *
  26671. * const geometry = new THREE.ShapeGeometry( arcShape );
  26672. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26673. * const mesh = new THREE.Mesh( geometry, material ) ;
  26674. * scene.add( mesh );
  26675. * ```
  26676. *
  26677. * @augments BufferGeometry
  26678. */
  26679. class ShapeGeometry extends BufferGeometry {
  26680. /**
  26681. * Constructs a new shape geometry.
  26682. *
  26683. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26684. * @param {number} [curveSegments=12] - Number of segments per shape.
  26685. */
  26686. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26687. super();
  26688. this.type = 'ShapeGeometry';
  26689. /**
  26690. * Holds the constructor parameters that have been
  26691. * used to generate the geometry. Any modification
  26692. * after instantiation does not change the geometry.
  26693. *
  26694. * @type {Object}
  26695. */
  26696. this.parameters = {
  26697. shapes: shapes,
  26698. curveSegments: curveSegments
  26699. };
  26700. // buffers
  26701. const indices = [];
  26702. const vertices = [];
  26703. const normals = [];
  26704. const uvs = [];
  26705. // helper variables
  26706. let groupStart = 0;
  26707. let groupCount = 0;
  26708. // allow single and array values for "shapes" parameter
  26709. if ( Array.isArray( shapes ) === false ) {
  26710. addShape( shapes );
  26711. } else {
  26712. for ( let i = 0; i < shapes.length; i ++ ) {
  26713. addShape( shapes[ i ] );
  26714. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26715. groupStart += groupCount;
  26716. groupCount = 0;
  26717. }
  26718. }
  26719. // build geometry
  26720. this.setIndex( indices );
  26721. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26722. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26723. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26724. // helper functions
  26725. function addShape( shape ) {
  26726. const indexOffset = vertices.length / 3;
  26727. const points = shape.extractPoints( curveSegments );
  26728. let shapeVertices = points.shape;
  26729. const shapeHoles = points.holes;
  26730. // check direction of vertices
  26731. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26732. shapeVertices = shapeVertices.reverse();
  26733. }
  26734. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26735. const shapeHole = shapeHoles[ i ];
  26736. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26737. shapeHoles[ i ] = shapeHole.reverse();
  26738. }
  26739. }
  26740. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26741. // join vertices of inner and outer paths to a single array
  26742. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26743. const shapeHole = shapeHoles[ i ];
  26744. shapeVertices = shapeVertices.concat( shapeHole );
  26745. }
  26746. // vertices, normals, uvs
  26747. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26748. const vertex = shapeVertices[ i ];
  26749. vertices.push( vertex.x, vertex.y, 0 );
  26750. normals.push( 0, 0, 1 );
  26751. uvs.push( vertex.x, vertex.y ); // world uvs
  26752. }
  26753. // indices
  26754. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26755. const face = faces[ i ];
  26756. const a = face[ 0 ] + indexOffset;
  26757. const b = face[ 1 ] + indexOffset;
  26758. const c = face[ 2 ] + indexOffset;
  26759. indices.push( a, b, c );
  26760. groupCount += 3;
  26761. }
  26762. }
  26763. }
  26764. copy( source ) {
  26765. super.copy( source );
  26766. this.parameters = Object.assign( {}, source.parameters );
  26767. return this;
  26768. }
  26769. toJSON() {
  26770. const data = super.toJSON();
  26771. const shapes = this.parameters.shapes;
  26772. return toJSON( shapes, data );
  26773. }
  26774. /**
  26775. * Factory method for creating an instance of this class from the given
  26776. * JSON object.
  26777. *
  26778. * @param {Object} data - A JSON object representing the serialized geometry.
  26779. * @param {Array<Shape>} shapes - An array of shapes.
  26780. * @return {ShapeGeometry} A new instance.
  26781. */
  26782. static fromJSON( data, shapes ) {
  26783. const geometryShapes = [];
  26784. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26785. const shape = shapes[ data.shapes[ j ] ];
  26786. geometryShapes.push( shape );
  26787. }
  26788. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26789. }
  26790. }
  26791. function toJSON( shapes, data ) {
  26792. data.shapes = [];
  26793. if ( Array.isArray( shapes ) ) {
  26794. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26795. const shape = shapes[ i ];
  26796. data.shapes.push( shape.uuid );
  26797. }
  26798. } else {
  26799. data.shapes.push( shapes.uuid );
  26800. }
  26801. return data;
  26802. }
  26803. /**
  26804. * A class for generating a sphere geometry.
  26805. *
  26806. * ```js
  26807. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26808. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26809. * const sphere = new THREE.Mesh( geometry, material );
  26810. * scene.add( sphere );
  26811. * ```
  26812. *
  26813. * @augments BufferGeometry
  26814. */
  26815. class SphereGeometry extends BufferGeometry {
  26816. /**
  26817. * Constructs a new sphere geometry.
  26818. *
  26819. * @param {number} [radius=1] - The sphere radius.
  26820. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26821. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26822. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26823. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26824. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26825. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26826. */
  26827. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26828. super();
  26829. this.type = 'SphereGeometry';
  26830. /**
  26831. * Holds the constructor parameters that have been
  26832. * used to generate the geometry. Any modification
  26833. * after instantiation does not change the geometry.
  26834. *
  26835. * @type {Object}
  26836. */
  26837. this.parameters = {
  26838. radius: radius,
  26839. widthSegments: widthSegments,
  26840. heightSegments: heightSegments,
  26841. phiStart: phiStart,
  26842. phiLength: phiLength,
  26843. thetaStart: thetaStart,
  26844. thetaLength: thetaLength
  26845. };
  26846. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26847. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26848. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26849. let index = 0;
  26850. const grid = [];
  26851. const vertex = new Vector3();
  26852. const normal = new Vector3();
  26853. // buffers
  26854. const indices = [];
  26855. const vertices = [];
  26856. const normals = [];
  26857. const uvs = [];
  26858. // generate vertices, normals and uvs
  26859. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26860. const verticesRow = [];
  26861. const v = iy / heightSegments;
  26862. // special case for the poles
  26863. let uOffset = 0;
  26864. if ( iy === 0 && thetaStart === 0 ) {
  26865. uOffset = 0.5 / widthSegments;
  26866. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26867. uOffset = -0.5 / widthSegments;
  26868. }
  26869. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26870. const u = ix / widthSegments;
  26871. // vertex
  26872. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26873. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26874. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26875. vertices.push( vertex.x, vertex.y, vertex.z );
  26876. // normal
  26877. normal.copy( vertex ).normalize();
  26878. normals.push( normal.x, normal.y, normal.z );
  26879. // uv
  26880. uvs.push( u + uOffset, 1 - v );
  26881. verticesRow.push( index ++ );
  26882. }
  26883. grid.push( verticesRow );
  26884. }
  26885. // indices
  26886. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26887. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26888. const a = grid[ iy ][ ix + 1 ];
  26889. const b = grid[ iy ][ ix ];
  26890. const c = grid[ iy + 1 ][ ix ];
  26891. const d = grid[ iy + 1 ][ ix + 1 ];
  26892. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26893. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26894. }
  26895. }
  26896. // build geometry
  26897. this.setIndex( indices );
  26898. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26899. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26900. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26901. }
  26902. copy( source ) {
  26903. super.copy( source );
  26904. this.parameters = Object.assign( {}, source.parameters );
  26905. return this;
  26906. }
  26907. /**
  26908. * Factory method for creating an instance of this class from the given
  26909. * JSON object.
  26910. *
  26911. * @param {Object} data - A JSON object representing the serialized geometry.
  26912. * @return {SphereGeometry} A new instance.
  26913. */
  26914. static fromJSON( data ) {
  26915. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26916. }
  26917. }
  26918. /**
  26919. * A geometry class for representing an tetrahedron.
  26920. *
  26921. * ```js
  26922. * const geometry = new THREE.TetrahedronGeometry();
  26923. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26924. * const tetrahedron = new THREE.Mesh( geometry, material );
  26925. * scene.add( tetrahedron );
  26926. * ```
  26927. *
  26928. * @augments PolyhedronGeometry
  26929. */
  26930. class TetrahedronGeometry extends PolyhedronGeometry {
  26931. /**
  26932. * Constructs a new tetrahedron geometry.
  26933. *
  26934. * @param {number} [radius=1] - Radius of the tetrahedron.
  26935. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26936. */
  26937. constructor( radius = 1, detail = 0 ) {
  26938. const vertices = [
  26939. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26940. ];
  26941. const indices = [
  26942. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26943. ];
  26944. super( vertices, indices, radius, detail );
  26945. this.type = 'TetrahedronGeometry';
  26946. /**
  26947. * Holds the constructor parameters that have been
  26948. * used to generate the geometry. Any modification
  26949. * after instantiation does not change the geometry.
  26950. *
  26951. * @type {Object}
  26952. */
  26953. this.parameters = {
  26954. radius: radius,
  26955. detail: detail
  26956. };
  26957. }
  26958. /**
  26959. * Factory method for creating an instance of this class from the given
  26960. * JSON object.
  26961. *
  26962. * @param {Object} data - A JSON object representing the serialized geometry.
  26963. * @return {TetrahedronGeometry} A new instance.
  26964. */
  26965. static fromJSON( data ) {
  26966. return new TetrahedronGeometry( data.radius, data.detail );
  26967. }
  26968. }
  26969. /**
  26970. * A geometry class for representing an torus.
  26971. *
  26972. * ```js
  26973. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26974. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26975. * const torus = new THREE.Mesh( geometry, material );
  26976. * scene.add( torus );
  26977. * ```
  26978. *
  26979. * @augments BufferGeometry
  26980. */
  26981. class TorusGeometry extends BufferGeometry {
  26982. /**
  26983. * Constructs a new torus geometry.
  26984. *
  26985. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26986. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26987. * @param {number} [radialSegments=12] - The number of radial segments.
  26988. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26989. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26990. */
  26991. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  26992. super();
  26993. this.type = 'TorusGeometry';
  26994. /**
  26995. * Holds the constructor parameters that have been
  26996. * used to generate the geometry. Any modification
  26997. * after instantiation does not change the geometry.
  26998. *
  26999. * @type {Object}
  27000. */
  27001. this.parameters = {
  27002. radius: radius,
  27003. tube: tube,
  27004. radialSegments: radialSegments,
  27005. tubularSegments: tubularSegments,
  27006. arc: arc
  27007. };
  27008. radialSegments = Math.floor( radialSegments );
  27009. tubularSegments = Math.floor( tubularSegments );
  27010. // buffers
  27011. const indices = [];
  27012. const vertices = [];
  27013. const normals = [];
  27014. const uvs = [];
  27015. // helper variables
  27016. const center = new Vector3();
  27017. const vertex = new Vector3();
  27018. const normal = new Vector3();
  27019. // generate vertices, normals and uvs
  27020. for ( let j = 0; j <= radialSegments; j ++ ) {
  27021. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27022. const u = i / tubularSegments * arc;
  27023. const v = j / radialSegments * Math.PI * 2;
  27024. // vertex
  27025. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27026. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27027. vertex.z = tube * Math.sin( v );
  27028. vertices.push( vertex.x, vertex.y, vertex.z );
  27029. // normal
  27030. center.x = radius * Math.cos( u );
  27031. center.y = radius * Math.sin( u );
  27032. normal.subVectors( vertex, center ).normalize();
  27033. normals.push( normal.x, normal.y, normal.z );
  27034. // uv
  27035. uvs.push( i / tubularSegments );
  27036. uvs.push( j / radialSegments );
  27037. }
  27038. }
  27039. // generate indices
  27040. for ( let j = 1; j <= radialSegments; j ++ ) {
  27041. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27042. // indices
  27043. const a = ( tubularSegments + 1 ) * j + i - 1;
  27044. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27045. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27046. const d = ( tubularSegments + 1 ) * j + i;
  27047. // faces
  27048. indices.push( a, b, d );
  27049. indices.push( b, c, d );
  27050. }
  27051. }
  27052. // build geometry
  27053. this.setIndex( indices );
  27054. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27055. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27056. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27057. }
  27058. copy( source ) {
  27059. super.copy( source );
  27060. this.parameters = Object.assign( {}, source.parameters );
  27061. return this;
  27062. }
  27063. /**
  27064. * Factory method for creating an instance of this class from the given
  27065. * JSON object.
  27066. *
  27067. * @param {Object} data - A JSON object representing the serialized geometry.
  27068. * @return {TorusGeometry} A new instance.
  27069. */
  27070. static fromJSON( data ) {
  27071. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27072. }
  27073. }
  27074. /**
  27075. * Creates a torus knot, the particular shape of which is defined by a pair
  27076. * of coprime integers, p and q. If p and q are not coprime, the result will
  27077. * be a torus link.
  27078. *
  27079. * ```js
  27080. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27081. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27082. * const torusKnot = new THREE.Mesh( geometry, material );
  27083. * scene.add( torusKnot );
  27084. * ```
  27085. *
  27086. * @augments BufferGeometry
  27087. */
  27088. class TorusKnotGeometry extends BufferGeometry {
  27089. /**
  27090. * Constructs a new torus knot geometry.
  27091. *
  27092. * @param {number} [radius=1] - Radius of the torus knot.
  27093. * @param {number} [tube=0.4] - Radius of the tube.
  27094. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27095. * @param {number} [radialSegments=8] - The number of radial segments.
  27096. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27097. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27098. */
  27099. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27100. super();
  27101. this.type = 'TorusKnotGeometry';
  27102. /**
  27103. * Holds the constructor parameters that have been
  27104. * used to generate the geometry. Any modification
  27105. * after instantiation does not change the geometry.
  27106. *
  27107. * @type {Object}
  27108. */
  27109. this.parameters = {
  27110. radius: radius,
  27111. tube: tube,
  27112. tubularSegments: tubularSegments,
  27113. radialSegments: radialSegments,
  27114. p: p,
  27115. q: q
  27116. };
  27117. tubularSegments = Math.floor( tubularSegments );
  27118. radialSegments = Math.floor( radialSegments );
  27119. // buffers
  27120. const indices = [];
  27121. const vertices = [];
  27122. const normals = [];
  27123. const uvs = [];
  27124. // helper variables
  27125. const vertex = new Vector3();
  27126. const normal = new Vector3();
  27127. const P1 = new Vector3();
  27128. const P2 = new Vector3();
  27129. const B = new Vector3();
  27130. const T = new Vector3();
  27131. const N = new Vector3();
  27132. // generate vertices, normals and uvs
  27133. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27134. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27135. const u = i / tubularSegments * p * Math.PI * 2;
  27136. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27137. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27138. calculatePositionOnCurve( u, p, q, radius, P1 );
  27139. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27140. // calculate orthonormal basis
  27141. T.subVectors( P2, P1 );
  27142. N.addVectors( P2, P1 );
  27143. B.crossVectors( T, N );
  27144. N.crossVectors( B, T );
  27145. // normalize B, N. T can be ignored, we don't use it
  27146. B.normalize();
  27147. N.normalize();
  27148. for ( let j = 0; j <= radialSegments; ++ j ) {
  27149. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27150. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27151. const v = j / radialSegments * Math.PI * 2;
  27152. const cx = - tube * Math.cos( v );
  27153. const cy = tube * Math.sin( v );
  27154. // now calculate the final vertex position.
  27155. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27156. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27157. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27158. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27159. vertices.push( vertex.x, vertex.y, vertex.z );
  27160. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27161. normal.subVectors( vertex, P1 ).normalize();
  27162. normals.push( normal.x, normal.y, normal.z );
  27163. // uv
  27164. uvs.push( i / tubularSegments );
  27165. uvs.push( j / radialSegments );
  27166. }
  27167. }
  27168. // generate indices
  27169. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27170. for ( let i = 1; i <= radialSegments; i ++ ) {
  27171. // indices
  27172. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27173. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27174. const c = ( radialSegments + 1 ) * j + i;
  27175. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27176. // faces
  27177. indices.push( a, b, d );
  27178. indices.push( b, c, d );
  27179. }
  27180. }
  27181. // build geometry
  27182. this.setIndex( indices );
  27183. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27184. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27185. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27186. // this function calculates the current position on the torus curve
  27187. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27188. const cu = Math.cos( u );
  27189. const su = Math.sin( u );
  27190. const quOverP = q / p * u;
  27191. const cs = Math.cos( quOverP );
  27192. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27193. position.y = radius * ( 2 + cs ) * su * 0.5;
  27194. position.z = radius * Math.sin( quOverP ) * 0.5;
  27195. }
  27196. }
  27197. copy( source ) {
  27198. super.copy( source );
  27199. this.parameters = Object.assign( {}, source.parameters );
  27200. return this;
  27201. }
  27202. /**
  27203. * Factory method for creating an instance of this class from the given
  27204. * JSON object.
  27205. *
  27206. * @param {Object} data - A JSON object representing the serialized geometry.
  27207. * @return {TorusKnotGeometry} A new instance.
  27208. */
  27209. static fromJSON( data ) {
  27210. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27211. }
  27212. }
  27213. /**
  27214. * Creates a tube that extrudes along a 3D curve.
  27215. *
  27216. * ```js
  27217. * class CustomSinCurve extends THREE.Curve {
  27218. *
  27219. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27220. *
  27221. * const tx = t * 3 - 1.5;
  27222. * const ty = Math.sin( 2 * Math.PI * t );
  27223. * const tz = 0;
  27224. *
  27225. * return optionalTarget.set( tx, ty, tz );
  27226. * }
  27227. *
  27228. * }
  27229. *
  27230. * const path = new CustomSinCurve( 10 );
  27231. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27232. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27233. * const mesh = new THREE.Mesh( geometry, material );
  27234. * scene.add( mesh );
  27235. * ```
  27236. *
  27237. * @augments BufferGeometry
  27238. */
  27239. class TubeGeometry extends BufferGeometry {
  27240. /**
  27241. * Constructs a new tube geometry.
  27242. *
  27243. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27244. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27245. * @param {number} [radius=1] -The radius of the tube.
  27246. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27247. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27248. */
  27249. constructor( path = new QuadraticBezierCurve3( new Vector3( -1, -1, 0 ), new Vector3( -1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  27250. super();
  27251. this.type = 'TubeGeometry';
  27252. /**
  27253. * Holds the constructor parameters that have been
  27254. * used to generate the geometry. Any modification
  27255. * after instantiation does not change the geometry.
  27256. *
  27257. * @type {Object}
  27258. */
  27259. this.parameters = {
  27260. path: path,
  27261. tubularSegments: tubularSegments,
  27262. radius: radius,
  27263. radialSegments: radialSegments,
  27264. closed: closed
  27265. };
  27266. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27267. // expose internals
  27268. this.tangents = frames.tangents;
  27269. this.normals = frames.normals;
  27270. this.binormals = frames.binormals;
  27271. // helper variables
  27272. const vertex = new Vector3();
  27273. const normal = new Vector3();
  27274. const uv = new Vector2();
  27275. let P = new Vector3();
  27276. // buffer
  27277. const vertices = [];
  27278. const normals = [];
  27279. const uvs = [];
  27280. const indices = [];
  27281. // create buffer data
  27282. generateBufferData();
  27283. // build geometry
  27284. this.setIndex( indices );
  27285. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27286. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27287. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27288. // functions
  27289. function generateBufferData() {
  27290. for ( let i = 0; i < tubularSegments; i ++ ) {
  27291. generateSegment( i );
  27292. }
  27293. // if the geometry is not closed, generate the last row of vertices and normals
  27294. // at the regular position on the given path
  27295. //
  27296. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27297. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27298. // uvs are generated in a separate function.
  27299. // this makes it easy compute correct values for closed geometries
  27300. generateUVs();
  27301. // finally create faces
  27302. generateIndices();
  27303. }
  27304. function generateSegment( i ) {
  27305. // we use getPointAt to sample evenly distributed points from the given path
  27306. P = path.getPointAt( i / tubularSegments, P );
  27307. // retrieve corresponding normal and binormal
  27308. const N = frames.normals[ i ];
  27309. const B = frames.binormals[ i ];
  27310. // generate normals and vertices for the current segment
  27311. for ( let j = 0; j <= radialSegments; j ++ ) {
  27312. const v = j / radialSegments * Math.PI * 2;
  27313. const sin = Math.sin( v );
  27314. const cos = - Math.cos( v );
  27315. // normal
  27316. normal.x = ( cos * N.x + sin * B.x );
  27317. normal.y = ( cos * N.y + sin * B.y );
  27318. normal.z = ( cos * N.z + sin * B.z );
  27319. normal.normalize();
  27320. normals.push( normal.x, normal.y, normal.z );
  27321. // vertex
  27322. vertex.x = P.x + radius * normal.x;
  27323. vertex.y = P.y + radius * normal.y;
  27324. vertex.z = P.z + radius * normal.z;
  27325. vertices.push( vertex.x, vertex.y, vertex.z );
  27326. }
  27327. }
  27328. function generateIndices() {
  27329. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27330. for ( let i = 1; i <= radialSegments; i ++ ) {
  27331. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27332. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27333. const c = ( radialSegments + 1 ) * j + i;
  27334. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27335. // faces
  27336. indices.push( a, b, d );
  27337. indices.push( b, c, d );
  27338. }
  27339. }
  27340. }
  27341. function generateUVs() {
  27342. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27343. for ( let j = 0; j <= radialSegments; j ++ ) {
  27344. uv.x = i / tubularSegments;
  27345. uv.y = j / radialSegments;
  27346. uvs.push( uv.x, uv.y );
  27347. }
  27348. }
  27349. }
  27350. }
  27351. copy( source ) {
  27352. super.copy( source );
  27353. this.parameters = Object.assign( {}, source.parameters );
  27354. return this;
  27355. }
  27356. toJSON() {
  27357. const data = super.toJSON();
  27358. data.path = this.parameters.path.toJSON();
  27359. return data;
  27360. }
  27361. /**
  27362. * Factory method for creating an instance of this class from the given
  27363. * JSON object.
  27364. *
  27365. * @param {Object} data - A JSON object representing the serialized geometry.
  27366. * @return {TubeGeometry} A new instance.
  27367. */
  27368. static fromJSON( data ) {
  27369. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27370. // User defined curves or instances of CurvePath will not be deserialized.
  27371. return new TubeGeometry(
  27372. new Curves[ data.path.type ]().fromJSON( data.path ),
  27373. data.tubularSegments,
  27374. data.radius,
  27375. data.radialSegments,
  27376. data.closed
  27377. );
  27378. }
  27379. }
  27380. /**
  27381. * Can be used as a helper object to visualize a geometry as a wireframe.
  27382. *
  27383. * ```js
  27384. * const geometry = new THREE.SphereGeometry();
  27385. *
  27386. * const wireframe = new THREE.WireframeGeometry( geometry );
  27387. *
  27388. * const line = new THREE.LineSegments( wireframe );
  27389. * line.material.depthWrite = false;
  27390. * line.material.opacity = 0.25;
  27391. * line.material.transparent = true;
  27392. *
  27393. * scene.add( line );
  27394. * ```
  27395. *
  27396. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27397. *
  27398. * @augments BufferGeometry
  27399. */
  27400. class WireframeGeometry extends BufferGeometry {
  27401. /**
  27402. * Constructs a new wireframe geometry.
  27403. *
  27404. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27405. */
  27406. constructor( geometry = null ) {
  27407. super();
  27408. this.type = 'WireframeGeometry';
  27409. /**
  27410. * Holds the constructor parameters that have been
  27411. * used to generate the geometry. Any modification
  27412. * after instantiation does not change the geometry.
  27413. *
  27414. * @type {Object}
  27415. */
  27416. this.parameters = {
  27417. geometry: geometry
  27418. };
  27419. if ( geometry !== null ) {
  27420. // buffer
  27421. const vertices = [];
  27422. const edges = new Set();
  27423. // helper variables
  27424. const start = new Vector3();
  27425. const end = new Vector3();
  27426. if ( geometry.index !== null ) {
  27427. // indexed BufferGeometry
  27428. const position = geometry.attributes.position;
  27429. const indices = geometry.index;
  27430. let groups = geometry.groups;
  27431. if ( groups.length === 0 ) {
  27432. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27433. }
  27434. // create a data structure that contains all edges without duplicates
  27435. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27436. const group = groups[ o ];
  27437. const groupStart = group.start;
  27438. const groupCount = group.count;
  27439. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27440. for ( let j = 0; j < 3; j ++ ) {
  27441. const index1 = indices.getX( i + j );
  27442. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27443. start.fromBufferAttribute( position, index1 );
  27444. end.fromBufferAttribute( position, index2 );
  27445. if ( isUniqueEdge( start, end, edges ) === true ) {
  27446. vertices.push( start.x, start.y, start.z );
  27447. vertices.push( end.x, end.y, end.z );
  27448. }
  27449. }
  27450. }
  27451. }
  27452. } else {
  27453. // non-indexed BufferGeometry
  27454. const position = geometry.attributes.position;
  27455. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27456. for ( let j = 0; j < 3; j ++ ) {
  27457. // three edges per triangle, an edge is represented as (index1, index2)
  27458. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27459. const index1 = 3 * i + j;
  27460. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27461. start.fromBufferAttribute( position, index1 );
  27462. end.fromBufferAttribute( position, index2 );
  27463. if ( isUniqueEdge( start, end, edges ) === true ) {
  27464. vertices.push( start.x, start.y, start.z );
  27465. vertices.push( end.x, end.y, end.z );
  27466. }
  27467. }
  27468. }
  27469. }
  27470. // build geometry
  27471. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27472. }
  27473. }
  27474. copy( source ) {
  27475. super.copy( source );
  27476. this.parameters = Object.assign( {}, source.parameters );
  27477. return this;
  27478. }
  27479. }
  27480. function isUniqueEdge( start, end, edges ) {
  27481. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27482. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27483. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27484. return false;
  27485. } else {
  27486. edges.add( hash1 );
  27487. edges.add( hash2 );
  27488. return true;
  27489. }
  27490. }
  27491. var Geometries = /*#__PURE__*/Object.freeze({
  27492. __proto__: null,
  27493. BoxGeometry: BoxGeometry,
  27494. CapsuleGeometry: CapsuleGeometry,
  27495. CircleGeometry: CircleGeometry,
  27496. ConeGeometry: ConeGeometry,
  27497. CylinderGeometry: CylinderGeometry,
  27498. DodecahedronGeometry: DodecahedronGeometry,
  27499. EdgesGeometry: EdgesGeometry,
  27500. ExtrudeGeometry: ExtrudeGeometry,
  27501. IcosahedronGeometry: IcosahedronGeometry,
  27502. LatheGeometry: LatheGeometry,
  27503. OctahedronGeometry: OctahedronGeometry,
  27504. PlaneGeometry: PlaneGeometry,
  27505. PolyhedronGeometry: PolyhedronGeometry,
  27506. RingGeometry: RingGeometry,
  27507. ShapeGeometry: ShapeGeometry,
  27508. SphereGeometry: SphereGeometry,
  27509. TetrahedronGeometry: TetrahedronGeometry,
  27510. TorusGeometry: TorusGeometry,
  27511. TorusKnotGeometry: TorusKnotGeometry,
  27512. TubeGeometry: TubeGeometry,
  27513. WireframeGeometry: WireframeGeometry
  27514. });
  27515. /**
  27516. * This material can receive shadows, but otherwise is completely transparent.
  27517. *
  27518. * ```js
  27519. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27520. * geometry.rotateX( - Math.PI / 2 );
  27521. *
  27522. * const material = new THREE.ShadowMaterial();
  27523. * material.opacity = 0.2;
  27524. *
  27525. * const plane = new THREE.Mesh( geometry, material );
  27526. * plane.position.y = -200;
  27527. * plane.receiveShadow = true;
  27528. * scene.add( plane );
  27529. * ```
  27530. *
  27531. * @augments Material
  27532. */
  27533. class ShadowMaterial extends Material {
  27534. /**
  27535. * Constructs a new shadow material.
  27536. *
  27537. * @param {Object} [parameters] - An object with one or more properties
  27538. * defining the material's appearance. Any property of the material
  27539. * (including any property from inherited materials) can be passed
  27540. * in here. Color values can be passed any type of value accepted
  27541. * by {@link Color#set}.
  27542. */
  27543. constructor( parameters ) {
  27544. super();
  27545. /**
  27546. * This flag can be used for type testing.
  27547. *
  27548. * @type {boolean}
  27549. * @readonly
  27550. * @default true
  27551. */
  27552. this.isShadowMaterial = true;
  27553. this.type = 'ShadowMaterial';
  27554. /**
  27555. * Color of the material.
  27556. *
  27557. * @type {Color}
  27558. * @default (0,0,0)
  27559. */
  27560. this.color = new Color( 0x000000 );
  27561. /**
  27562. * Overwritten since shadow materials are transparent
  27563. * by default.
  27564. *
  27565. * @type {boolean}
  27566. * @default true
  27567. */
  27568. this.transparent = true;
  27569. /**
  27570. * Whether the material is affected by fog or not.
  27571. *
  27572. * @type {boolean}
  27573. * @default true
  27574. */
  27575. this.fog = true;
  27576. this.setValues( parameters );
  27577. }
  27578. copy( source ) {
  27579. super.copy( source );
  27580. this.color.copy( source.color );
  27581. this.fog = source.fog;
  27582. return this;
  27583. }
  27584. }
  27585. /**
  27586. * This class works just like {@link ShaderMaterial}, except that definitions
  27587. * of built-in uniforms and attributes are not automatically prepended to the
  27588. * GLSL shader code.
  27589. *
  27590. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27591. *
  27592. * @augments ShaderMaterial
  27593. */
  27594. class RawShaderMaterial extends ShaderMaterial {
  27595. /**
  27596. * Constructs a new raw shader material.
  27597. *
  27598. * @param {Object} [parameters] - An object with one or more properties
  27599. * defining the material's appearance. Any property of the material
  27600. * (including any property from inherited materials) can be passed
  27601. * in here. Color values can be passed any type of value accepted
  27602. * by {@link Color#set}.
  27603. */
  27604. constructor( parameters ) {
  27605. super( parameters );
  27606. /**
  27607. * This flag can be used for type testing.
  27608. *
  27609. * @type {boolean}
  27610. * @readonly
  27611. * @default true
  27612. */
  27613. this.isRawShaderMaterial = true;
  27614. this.type = 'RawShaderMaterial';
  27615. }
  27616. }
  27617. /**
  27618. * A standard physically based material, using Metallic-Roughness workflow.
  27619. *
  27620. * Physically based rendering (PBR) has recently become the standard in many
  27621. * 3D applications, such as [Unity]{@link https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/},
  27622. * [Unreal]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/} and
  27623. * [3D Studio Max]{@link http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017}.
  27624. *
  27625. * This approach differs from older approaches in that instead of using
  27626. * approximations for the way in which light interacts with a surface, a
  27627. * physically correct model is used. The idea is that, instead of tweaking
  27628. * materials to look good under specific lighting, a material can be created
  27629. * that will react 'correctly' under all lighting scenarios.
  27630. *
  27631. * In practice this gives a more accurate and realistic looking result than
  27632. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27633. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27634. * shading.
  27635. *
  27636. * Note that for best results you should always specify an environment map when using this material.
  27637. *
  27638. * For a non-technical introduction to the concept of PBR and how to set up a
  27639. * PBR material, check out these articles by the people at [marmoset]{@link https://www.marmoset.co}:
  27640. *
  27641. * - [Basic Theory of Physically Based Rendering]{@link https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/}
  27642. * - [Physically Based Rendering and You Can Too]{@link https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/}
  27643. *
  27644. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27645. * [paper from Disney]{@link https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf}
  27646. * (pdf), by Brent Burley.
  27647. *
  27648. * @augments Material
  27649. */
  27650. class MeshStandardMaterial extends Material {
  27651. /**
  27652. * Constructs a new mesh standard material.
  27653. *
  27654. * @param {Object} [parameters] - An object with one or more properties
  27655. * defining the material's appearance. Any property of the material
  27656. * (including any property from inherited materials) can be passed
  27657. * in here. Color values can be passed any type of value accepted
  27658. * by {@link Color#set}.
  27659. */
  27660. constructor( parameters ) {
  27661. super();
  27662. /**
  27663. * This flag can be used for type testing.
  27664. *
  27665. * @type {boolean}
  27666. * @readonly
  27667. * @default true
  27668. */
  27669. this.isMeshStandardMaterial = true;
  27670. this.type = 'MeshStandardMaterial';
  27671. this.defines = { 'STANDARD': '' };
  27672. /**
  27673. * Color of the material.
  27674. *
  27675. * @type {Color}
  27676. * @default (1,1,1)
  27677. */
  27678. this.color = new Color( 0xffffff ); // diffuse
  27679. /**
  27680. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27681. * means fully diffuse. If `roughnessMap` is also provided,
  27682. * both values are multiplied.
  27683. *
  27684. * @type {number}
  27685. * @default 1
  27686. */
  27687. this.roughness = 1.0;
  27688. /**
  27689. * How much the material is like a metal. Non-metallic materials such as wood
  27690. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27691. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27692. * If `metalnessMap` is also provided, both values are multiplied.
  27693. *
  27694. * @type {number}
  27695. * @default 0
  27696. */
  27697. this.metalness = 0.0;
  27698. /**
  27699. * The color map. May optionally include an alpha channel, typically combined
  27700. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27701. * color is modulated by the diffuse `color`.
  27702. *
  27703. * @type {?Texture}
  27704. * @default null
  27705. */
  27706. this.map = null;
  27707. /**
  27708. * The light map. Requires a second set of UVs.
  27709. *
  27710. * @type {?Texture}
  27711. * @default null
  27712. */
  27713. this.lightMap = null;
  27714. /**
  27715. * Intensity of the baked light.
  27716. *
  27717. * @type {number}
  27718. * @default 1
  27719. */
  27720. this.lightMapIntensity = 1.0;
  27721. /**
  27722. * The red channel of this texture is used as the ambient occlusion map.
  27723. * Requires a second set of UVs.
  27724. *
  27725. * @type {?Texture}
  27726. * @default null
  27727. */
  27728. this.aoMap = null;
  27729. /**
  27730. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27731. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27732. * red channel is also `1`, ambient light is fully occluded on a surface.
  27733. *
  27734. * @type {number}
  27735. * @default 1
  27736. */
  27737. this.aoMapIntensity = 1.0;
  27738. /**
  27739. * Emissive (light) color of the material, essentially a solid color
  27740. * unaffected by other lighting.
  27741. *
  27742. * @type {Color}
  27743. * @default (0,0,0)
  27744. */
  27745. this.emissive = new Color( 0x000000 );
  27746. /**
  27747. * Intensity of the emissive light. Modulates the emissive color.
  27748. *
  27749. * @type {number}
  27750. * @default 1
  27751. */
  27752. this.emissiveIntensity = 1.0;
  27753. /**
  27754. * Set emissive (glow) map. The emissive map color is modulated by the
  27755. * emissive color and the emissive intensity. If you have an emissive map,
  27756. * be sure to set the emissive color to something other than black.
  27757. *
  27758. * @type {?Texture}
  27759. * @default null
  27760. */
  27761. this.emissiveMap = null;
  27762. /**
  27763. * The texture to create a bump map. The black and white values map to the
  27764. * perceived depth in relation to the lights. Bump doesn't actually affect
  27765. * the geometry of the object, only the lighting. If a normal map is defined
  27766. * this will be ignored.
  27767. *
  27768. * @type {?Texture}
  27769. * @default null
  27770. */
  27771. this.bumpMap = null;
  27772. /**
  27773. * How much the bump map affects the material. Typical range is `[0,1]`.
  27774. *
  27775. * @type {number}
  27776. * @default 1
  27777. */
  27778. this.bumpScale = 1;
  27779. /**
  27780. * The texture to create a normal map. The RGB values affect the surface
  27781. * normal for each pixel fragment and change the way the color is lit. Normal
  27782. * maps do not change the actual shape of the surface, only the lighting. In
  27783. * case the material has a normal map authored using the left handed
  27784. * convention, the `y` component of `normalScale` should be negated to compensate
  27785. * for the different handedness.
  27786. *
  27787. * @type {?Texture}
  27788. * @default null
  27789. */
  27790. this.normalMap = null;
  27791. /**
  27792. * The type of normal map.
  27793. *
  27794. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27795. * @default TangentSpaceNormalMap
  27796. */
  27797. this.normalMapType = TangentSpaceNormalMap;
  27798. /**
  27799. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27800. *
  27801. * @type {Vector2}
  27802. * @default (1,1)
  27803. */
  27804. this.normalScale = new Vector2( 1, 1 );
  27805. /**
  27806. * The displacement map affects the position of the mesh's vertices. Unlike
  27807. * other maps which only affect the light and shade of the material the
  27808. * displaced vertices can cast shadows, block other objects, and otherwise
  27809. * act as real geometry. The displacement texture is an image where the value
  27810. * of each pixel (white being the highest) is mapped against, and
  27811. * repositions, the vertices of the mesh.
  27812. *
  27813. * @type {?Texture}
  27814. * @default null
  27815. */
  27816. this.displacementMap = null;
  27817. /**
  27818. * How much the displacement map affects the mesh (where black is no
  27819. * displacement, and white is maximum displacement). Without a displacement
  27820. * map set, this value is not applied.
  27821. *
  27822. * @type {number}
  27823. * @default 0
  27824. */
  27825. this.displacementScale = 1;
  27826. /**
  27827. * The offset of the displacement map's values on the mesh's vertices.
  27828. * The bias is added to the scaled sample of the displacement map.
  27829. * Without a displacement map set, this value is not applied.
  27830. *
  27831. * @type {number}
  27832. * @default 0
  27833. */
  27834. this.displacementBias = 0;
  27835. /**
  27836. * The green channel of this texture is used to alter the roughness of the
  27837. * material.
  27838. *
  27839. * @type {?Texture}
  27840. * @default null
  27841. */
  27842. this.roughnessMap = null;
  27843. /**
  27844. * The blue channel of this texture is used to alter the metalness of the
  27845. * material.
  27846. *
  27847. * @type {?Texture}
  27848. * @default null
  27849. */
  27850. this.metalnessMap = null;
  27851. /**
  27852. * The alpha map is a grayscale texture that controls the opacity across the
  27853. * surface (black: fully transparent; white: fully opaque).
  27854. *
  27855. * Only the color of the texture is used, ignoring the alpha channel if one
  27856. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27857. * when sampling this texture due to the extra bit of precision provided for
  27858. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27859. * luminance/alpha textures will also still work as expected.
  27860. *
  27861. * @type {?Texture}
  27862. * @default null
  27863. */
  27864. this.alphaMap = null;
  27865. /**
  27866. * The environment map. To ensure a physically correct rendering, environment maps
  27867. * are internally pre-processed with {@link PMREMGenerator}.
  27868. *
  27869. * @type {?Texture}
  27870. * @default null
  27871. */
  27872. this.envMap = null;
  27873. /**
  27874. * The rotation of the environment map in radians.
  27875. *
  27876. * @type {Euler}
  27877. * @default (0,0,0)
  27878. */
  27879. this.envMapRotation = new Euler();
  27880. /**
  27881. * Scales the effect of the environment map by multiplying its color.
  27882. *
  27883. * @type {number}
  27884. * @default 1
  27885. */
  27886. this.envMapIntensity = 1.0;
  27887. /**
  27888. * Renders the geometry as a wireframe.
  27889. *
  27890. * @type {boolean}
  27891. * @default false
  27892. */
  27893. this.wireframe = false;
  27894. /**
  27895. * Controls the thickness of the wireframe.
  27896. *
  27897. * Can only be used with {@link SVGRenderer}.
  27898. *
  27899. * @type {number}
  27900. * @default 1
  27901. */
  27902. this.wireframeLinewidth = 1;
  27903. /**
  27904. * Defines appearance of wireframe ends.
  27905. *
  27906. * Can only be used with {@link SVGRenderer}.
  27907. *
  27908. * @type {('round'|'bevel'|'miter')}
  27909. * @default 'round'
  27910. */
  27911. this.wireframeLinecap = 'round';
  27912. /**
  27913. * Defines appearance of wireframe joints.
  27914. *
  27915. * Can only be used with {@link SVGRenderer}.
  27916. *
  27917. * @type {('round'|'bevel'|'miter')}
  27918. * @default 'round'
  27919. */
  27920. this.wireframeLinejoin = 'round';
  27921. /**
  27922. * Whether the material is rendered with flat shading or not.
  27923. *
  27924. * @type {boolean}
  27925. * @default false
  27926. */
  27927. this.flatShading = false;
  27928. /**
  27929. * Whether the material is affected by fog or not.
  27930. *
  27931. * @type {boolean}
  27932. * @default true
  27933. */
  27934. this.fog = true;
  27935. this.setValues( parameters );
  27936. }
  27937. copy( source ) {
  27938. super.copy( source );
  27939. this.defines = { 'STANDARD': '' };
  27940. this.color.copy( source.color );
  27941. this.roughness = source.roughness;
  27942. this.metalness = source.metalness;
  27943. this.map = source.map;
  27944. this.lightMap = source.lightMap;
  27945. this.lightMapIntensity = source.lightMapIntensity;
  27946. this.aoMap = source.aoMap;
  27947. this.aoMapIntensity = source.aoMapIntensity;
  27948. this.emissive.copy( source.emissive );
  27949. this.emissiveMap = source.emissiveMap;
  27950. this.emissiveIntensity = source.emissiveIntensity;
  27951. this.bumpMap = source.bumpMap;
  27952. this.bumpScale = source.bumpScale;
  27953. this.normalMap = source.normalMap;
  27954. this.normalMapType = source.normalMapType;
  27955. this.normalScale.copy( source.normalScale );
  27956. this.displacementMap = source.displacementMap;
  27957. this.displacementScale = source.displacementScale;
  27958. this.displacementBias = source.displacementBias;
  27959. this.roughnessMap = source.roughnessMap;
  27960. this.metalnessMap = source.metalnessMap;
  27961. this.alphaMap = source.alphaMap;
  27962. this.envMap = source.envMap;
  27963. this.envMapRotation.copy( source.envMapRotation );
  27964. this.envMapIntensity = source.envMapIntensity;
  27965. this.wireframe = source.wireframe;
  27966. this.wireframeLinewidth = source.wireframeLinewidth;
  27967. this.wireframeLinecap = source.wireframeLinecap;
  27968. this.wireframeLinejoin = source.wireframeLinejoin;
  27969. this.flatShading = source.flatShading;
  27970. this.fog = source.fog;
  27971. return this;
  27972. }
  27973. }
  27974. /**
  27975. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27976. * physically-based rendering properties:
  27977. *
  27978. * - Anisotropy: Ability to represent the anisotropic property of materials
  27979. * as observable with brushed metals.
  27980. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27981. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27982. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27983. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27984. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27985. * wings of many insects.
  27986. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27987. * transparent materials are less reflective. Physically-based transmission provides a more
  27988. * realistic option for thin, transparent surfaces like glass.
  27989. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27990. * - Sheen: Can be used for representing cloth and fabric materials.
  27991. *
  27992. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27993. * higher performance cost, per pixel, than other three.js materials. Most
  27994. * effects are disabled by default, and add cost as they are enabled. For
  27995. * best results, always specify an environment map when using this material.
  27996. *
  27997. * @augments MeshStandardMaterial
  27998. */
  27999. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28000. /**
  28001. * Constructs a new mesh physical material.
  28002. *
  28003. * @param {Object} [parameters] - An object with one or more properties
  28004. * defining the material's appearance. Any property of the material
  28005. * (including any property from inherited materials) can be passed
  28006. * in here. Color values can be passed any type of value accepted
  28007. * by {@link Color#set}.
  28008. */
  28009. constructor( parameters ) {
  28010. super();
  28011. /**
  28012. * This flag can be used for type testing.
  28013. *
  28014. * @type {boolean}
  28015. * @readonly
  28016. * @default true
  28017. */
  28018. this.isMeshPhysicalMaterial = true;
  28019. this.defines = {
  28020. 'STANDARD': '',
  28021. 'PHYSICAL': ''
  28022. };
  28023. this.type = 'MeshPhysicalMaterial';
  28024. /**
  28025. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28026. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28027. * property provides additional rotation to the vectors in the texture.
  28028. *
  28029. * @type {number}
  28030. * @default 1
  28031. */
  28032. this.anisotropyRotation = 0;
  28033. /**
  28034. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28035. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28036. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28037. *
  28038. * @type {?Texture}
  28039. * @default null
  28040. */
  28041. this.anisotropyMap = null;
  28042. /**
  28043. * The red channel of this texture is multiplied against `clearcoat`,
  28044. * for per-pixel control over a coating's intensity.
  28045. *
  28046. * @type {?Texture}
  28047. * @default null
  28048. */
  28049. this.clearcoatMap = null;
  28050. /**
  28051. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28052. *
  28053. * @type {number}
  28054. * @default 0
  28055. */
  28056. this.clearcoatRoughness = 0.0;
  28057. /**
  28058. * The green channel of this texture is multiplied against
  28059. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28060. *
  28061. * @type {?Texture}
  28062. * @default null
  28063. */
  28064. this.clearcoatRoughnessMap = null;
  28065. /**
  28066. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28067. * `(0,0)` to `(1,1)`.
  28068. *
  28069. * @type {Vector2}
  28070. * @default (1,1)
  28071. */
  28072. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28073. /**
  28074. * Can be used to enable independent normals for the clear coat layer.
  28075. *
  28076. * @type {?Texture}
  28077. * @default null
  28078. */
  28079. this.clearcoatNormalMap = null;
  28080. /**
  28081. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28082. *
  28083. * @type {number}
  28084. * @default 1.5
  28085. */
  28086. this.ior = 1.5;
  28087. /**
  28088. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28089. * corresponds to an index-of-refraction of `1.5`.
  28090. *
  28091. * This models the reflectivity of non-metallic materials. It has no effect
  28092. * when `metalness` is `1.0`
  28093. *
  28094. * @name MeshPhysicalMaterial#reflectivity
  28095. * @type {number}
  28096. * @default 0.5
  28097. */
  28098. Object.defineProperty( this, 'reflectivity', {
  28099. get: function () {
  28100. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28101. },
  28102. set: function ( reflectivity ) {
  28103. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28104. }
  28105. } );
  28106. /**
  28107. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28108. * control over iridescence.
  28109. *
  28110. * @type {?Texture}
  28111. * @default null
  28112. */
  28113. this.iridescenceMap = null;
  28114. /**
  28115. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28116. * Between `1.0` to `2.333`.
  28117. *
  28118. * @type {number}
  28119. * @default 1.3
  28120. */
  28121. this.iridescenceIOR = 1.3;
  28122. /**
  28123. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28124. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28125. *
  28126. * @type {Array<number,number>}
  28127. * @default [100,400]
  28128. */
  28129. this.iridescenceThicknessRange = [ 100, 400 ];
  28130. /**
  28131. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28132. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28133. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28134. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28135. * - Values in-between will linearly interpolate between the elements of the array.
  28136. *
  28137. * @type {?Texture}
  28138. * @default null
  28139. */
  28140. this.iridescenceThicknessMap = null;
  28141. /**
  28142. * The sheen tint.
  28143. *
  28144. * @type {Color}
  28145. * @default (0,0,0)
  28146. */
  28147. this.sheenColor = new Color( 0x000000 );
  28148. /**
  28149. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28150. * over sheen tint.
  28151. *
  28152. * @type {?Texture}
  28153. * @default null
  28154. */
  28155. this.sheenColorMap = null;
  28156. /**
  28157. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28158. *
  28159. * @type {number}
  28160. * @default 1
  28161. */
  28162. this.sheenRoughness = 1.0;
  28163. /**
  28164. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28165. * over sheen roughness.
  28166. *
  28167. * @type {?Texture}
  28168. * @default null
  28169. */
  28170. this.sheenRoughnessMap = null;
  28171. /**
  28172. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28173. * optical transparency.
  28174. *
  28175. * @type {?Texture}
  28176. * @default null
  28177. */
  28178. this.transmissionMap = null;
  28179. /**
  28180. * The thickness of the volume beneath the surface. The value is given in the
  28181. * coordinate space of the mesh. If the value is `0` the material is
  28182. * thin-walled. Otherwise the material is a volume boundary.
  28183. *
  28184. * @type {number}
  28185. * @default 0
  28186. */
  28187. this.thickness = 0;
  28188. /**
  28189. * A texture that defines the thickness, stored in the green channel. This will
  28190. * be multiplied by `thickness`.
  28191. *
  28192. * @type {?Texture}
  28193. * @default null
  28194. */
  28195. this.thicknessMap = null;
  28196. /**
  28197. * Density of the medium given as the average distance that light travels in
  28198. * the medium before interacting with a particle. The value is given in world
  28199. * space units, and must be greater than zero.
  28200. *
  28201. * @type {number}
  28202. * @default Infinity
  28203. */
  28204. this.attenuationDistance = Infinity;
  28205. /**
  28206. * The color that white light turns into due to absorption when reaching the
  28207. * attenuation distance.
  28208. *
  28209. * @type {Color}
  28210. * @default (1,1,1)
  28211. */
  28212. this.attenuationColor = new Color( 1, 1, 1 );
  28213. /**
  28214. * A float that scales the amount of specular reflection for non-metals only.
  28215. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28216. *
  28217. * @type {number}
  28218. * @default 1
  28219. */
  28220. this.specularIntensity = 1.0;
  28221. /**
  28222. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28223. * for per-pixel control over specular intensity.
  28224. *
  28225. * @type {?Texture}
  28226. * @default null
  28227. */
  28228. this.specularIntensityMap = null;
  28229. /**
  28230. * Tints the specular reflection at normal incidence for non-metals only.
  28231. *
  28232. * @type {Color}
  28233. * @default (1,1,1)
  28234. */
  28235. this.specularColor = new Color( 1, 1, 1 );
  28236. /**
  28237. * The RGB channels of this texture are multiplied against `specularColor`,
  28238. * for per-pixel control over specular color.
  28239. *
  28240. * @type {?Texture}
  28241. * @default null
  28242. */
  28243. this.specularColorMap = null;
  28244. this._anisotropy = 0;
  28245. this._clearcoat = 0;
  28246. this._dispersion = 0;
  28247. this._iridescence = 0;
  28248. this._sheen = 0.0;
  28249. this._transmission = 0;
  28250. this.setValues( parameters );
  28251. }
  28252. /**
  28253. * The anisotropy strength.
  28254. *
  28255. * @type {number}
  28256. * @default 0
  28257. */
  28258. get anisotropy() {
  28259. return this._anisotropy;
  28260. }
  28261. set anisotropy( value ) {
  28262. if ( this._anisotropy > 0 !== value > 0 ) {
  28263. this.version ++;
  28264. }
  28265. this._anisotropy = value;
  28266. }
  28267. /**
  28268. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28269. * clear coat related properties to enable multilayer materials that have a
  28270. * thin translucent layer over the base layer.
  28271. *
  28272. * @type {number}
  28273. * @default 0
  28274. */
  28275. get clearcoat() {
  28276. return this._clearcoat;
  28277. }
  28278. set clearcoat( value ) {
  28279. if ( this._clearcoat > 0 !== value > 0 ) {
  28280. this.version ++;
  28281. }
  28282. this._clearcoat = value;
  28283. }
  28284. /**
  28285. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28286. * the surface and the viewer, from `0.0` to `1.0`.
  28287. *
  28288. * @type {number}
  28289. * @default 0
  28290. */
  28291. get iridescence() {
  28292. return this._iridescence;
  28293. }
  28294. set iridescence( value ) {
  28295. if ( this._iridescence > 0 !== value > 0 ) {
  28296. this.version ++;
  28297. }
  28298. this._iridescence = value;
  28299. }
  28300. /**
  28301. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28302. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28303. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28304. *
  28305. * @type {number}
  28306. * @default 0
  28307. */
  28308. get dispersion() {
  28309. return this._dispersion;
  28310. }
  28311. set dispersion( value ) {
  28312. if ( this._dispersion > 0 !== value > 0 ) {
  28313. this.version ++;
  28314. }
  28315. this._dispersion = value;
  28316. }
  28317. /**
  28318. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28319. *
  28320. * @type {number}
  28321. * @default 0
  28322. */
  28323. get sheen() {
  28324. return this._sheen;
  28325. }
  28326. set sheen( value ) {
  28327. if ( this._sheen > 0 !== value > 0 ) {
  28328. this.version ++;
  28329. }
  28330. this._sheen = value;
  28331. }
  28332. /**
  28333. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28334. *
  28335. * Thin, transparent or semitransparent, plastic or glass materials remain
  28336. * largely reflective even if they are fully transmissive. The transmission
  28337. * property can be used to model these materials.
  28338. *
  28339. * When transmission is non-zero, `opacity` should be set to `1`.
  28340. *
  28341. * @type {number}
  28342. * @default 0
  28343. */
  28344. get transmission() {
  28345. return this._transmission;
  28346. }
  28347. set transmission( value ) {
  28348. if ( this._transmission > 0 !== value > 0 ) {
  28349. this.version ++;
  28350. }
  28351. this._transmission = value;
  28352. }
  28353. copy( source ) {
  28354. super.copy( source );
  28355. this.defines = {
  28356. 'STANDARD': '',
  28357. 'PHYSICAL': ''
  28358. };
  28359. this.anisotropy = source.anisotropy;
  28360. this.anisotropyRotation = source.anisotropyRotation;
  28361. this.anisotropyMap = source.anisotropyMap;
  28362. this.clearcoat = source.clearcoat;
  28363. this.clearcoatMap = source.clearcoatMap;
  28364. this.clearcoatRoughness = source.clearcoatRoughness;
  28365. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28366. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28367. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28368. this.dispersion = source.dispersion;
  28369. this.ior = source.ior;
  28370. this.iridescence = source.iridescence;
  28371. this.iridescenceMap = source.iridescenceMap;
  28372. this.iridescenceIOR = source.iridescenceIOR;
  28373. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28374. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28375. this.sheen = source.sheen;
  28376. this.sheenColor.copy( source.sheenColor );
  28377. this.sheenColorMap = source.sheenColorMap;
  28378. this.sheenRoughness = source.sheenRoughness;
  28379. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28380. this.transmission = source.transmission;
  28381. this.transmissionMap = source.transmissionMap;
  28382. this.thickness = source.thickness;
  28383. this.thicknessMap = source.thicknessMap;
  28384. this.attenuationDistance = source.attenuationDistance;
  28385. this.attenuationColor.copy( source.attenuationColor );
  28386. this.specularIntensity = source.specularIntensity;
  28387. this.specularIntensityMap = source.specularIntensityMap;
  28388. this.specularColor.copy( source.specularColor );
  28389. this.specularColorMap = source.specularColorMap;
  28390. return this;
  28391. }
  28392. }
  28393. /**
  28394. * A material for shiny surfaces with specular highlights.
  28395. *
  28396. * The material uses a non-physically based [Blinn-Phong]{@link https://en.wikipedia.org/wiki/Blinn-Phong_shading_model}
  28397. * model for calculating reflectance. Unlike the Lambertian model used in the
  28398. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28399. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28400. *
  28401. * Performance will generally be greater when using this material over the
  28402. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28403. * some graphical accuracy.
  28404. *
  28405. * @augments Material
  28406. */
  28407. class MeshPhongMaterial extends Material {
  28408. /**
  28409. * Constructs a new mesh phong material.
  28410. *
  28411. * @param {Object} [parameters] - An object with one or more properties
  28412. * defining the material's appearance. Any property of the material
  28413. * (including any property from inherited materials) can be passed
  28414. * in here. Color values can be passed any type of value accepted
  28415. * by {@link Color#set}.
  28416. */
  28417. constructor( parameters ) {
  28418. super();
  28419. /**
  28420. * This flag can be used for type testing.
  28421. *
  28422. * @type {boolean}
  28423. * @readonly
  28424. * @default true
  28425. */
  28426. this.isMeshPhongMaterial = true;
  28427. this.type = 'MeshPhongMaterial';
  28428. /**
  28429. * Color of the material.
  28430. *
  28431. * @type {Color}
  28432. * @default (1,1,1)
  28433. */
  28434. this.color = new Color( 0xffffff ); // diffuse
  28435. /**
  28436. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28437. *
  28438. * This defines how shiny the material is and the color of its shine.
  28439. *
  28440. * @type {Color}
  28441. */
  28442. this.specular = new Color( 0x111111 );
  28443. /**
  28444. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28445. *
  28446. * @type {number}
  28447. * @default 30
  28448. */
  28449. this.shininess = 30;
  28450. /**
  28451. * The color map. May optionally include an alpha channel, typically combined
  28452. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28453. * color is modulated by the diffuse `color`.
  28454. *
  28455. * @type {?Texture}
  28456. * @default null
  28457. */
  28458. this.map = null;
  28459. /**
  28460. * The light map. Requires a second set of UVs.
  28461. *
  28462. * @type {?Texture}
  28463. * @default null
  28464. */
  28465. this.lightMap = null;
  28466. /**
  28467. * Intensity of the baked light.
  28468. *
  28469. * @type {number}
  28470. * @default 1
  28471. */
  28472. this.lightMapIntensity = 1.0;
  28473. /**
  28474. * The red channel of this texture is used as the ambient occlusion map.
  28475. * Requires a second set of UVs.
  28476. *
  28477. * @type {?Texture}
  28478. * @default null
  28479. */
  28480. this.aoMap = null;
  28481. /**
  28482. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28483. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28484. * red channel is also `1`, ambient light is fully occluded on a surface.
  28485. *
  28486. * @type {number}
  28487. * @default 1
  28488. */
  28489. this.aoMapIntensity = 1.0;
  28490. /**
  28491. * Emissive (light) color of the material, essentially a solid color
  28492. * unaffected by other lighting.
  28493. *
  28494. * @type {Color}
  28495. * @default (0,0,0)
  28496. */
  28497. this.emissive = new Color( 0x000000 );
  28498. /**
  28499. * Intensity of the emissive light. Modulates the emissive color.
  28500. *
  28501. * @type {number}
  28502. * @default 1
  28503. */
  28504. this.emissiveIntensity = 1.0;
  28505. /**
  28506. * Set emissive (glow) map. The emissive map color is modulated by the
  28507. * emissive color and the emissive intensity. If you have an emissive map,
  28508. * be sure to set the emissive color to something other than black.
  28509. *
  28510. * @type {?Texture}
  28511. * @default null
  28512. */
  28513. this.emissiveMap = null;
  28514. /**
  28515. * The texture to create a bump map. The black and white values map to the
  28516. * perceived depth in relation to the lights. Bump doesn't actually affect
  28517. * the geometry of the object, only the lighting. If a normal map is defined
  28518. * this will be ignored.
  28519. *
  28520. * @type {?Texture}
  28521. * @default null
  28522. */
  28523. this.bumpMap = null;
  28524. /**
  28525. * How much the bump map affects the material. Typical range is `[0,1]`.
  28526. *
  28527. * @type {number}
  28528. * @default 1
  28529. */
  28530. this.bumpScale = 1;
  28531. /**
  28532. * The texture to create a normal map. The RGB values affect the surface
  28533. * normal for each pixel fragment and change the way the color is lit. Normal
  28534. * maps do not change the actual shape of the surface, only the lighting. In
  28535. * case the material has a normal map authored using the left handed
  28536. * convention, the `y` component of `normalScale` should be negated to compensate
  28537. * for the different handedness.
  28538. *
  28539. * @type {?Texture}
  28540. * @default null
  28541. */
  28542. this.normalMap = null;
  28543. /**
  28544. * The type of normal map.
  28545. *
  28546. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28547. * @default TangentSpaceNormalMap
  28548. */
  28549. this.normalMapType = TangentSpaceNormalMap;
  28550. /**
  28551. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28552. *
  28553. * @type {Vector2}
  28554. * @default (1,1)
  28555. */
  28556. this.normalScale = new Vector2( 1, 1 );
  28557. /**
  28558. * The displacement map affects the position of the mesh's vertices. Unlike
  28559. * other maps which only affect the light and shade of the material the
  28560. * displaced vertices can cast shadows, block other objects, and otherwise
  28561. * act as real geometry. The displacement texture is an image where the value
  28562. * of each pixel (white being the highest) is mapped against, and
  28563. * repositions, the vertices of the mesh.
  28564. *
  28565. * @type {?Texture}
  28566. * @default null
  28567. */
  28568. this.displacementMap = null;
  28569. /**
  28570. * How much the displacement map affects the mesh (where black is no
  28571. * displacement, and white is maximum displacement). Without a displacement
  28572. * map set, this value is not applied.
  28573. *
  28574. * @type {number}
  28575. * @default 0
  28576. */
  28577. this.displacementScale = 1;
  28578. /**
  28579. * The offset of the displacement map's values on the mesh's vertices.
  28580. * The bias is added to the scaled sample of the displacement map.
  28581. * Without a displacement map set, this value is not applied.
  28582. *
  28583. * @type {number}
  28584. * @default 0
  28585. */
  28586. this.displacementBias = 0;
  28587. /**
  28588. * The specular map value affects both how much the specular surface
  28589. * highlight contributes and how much of the environment map affects the
  28590. * surface.
  28591. *
  28592. * @type {?Texture}
  28593. * @default null
  28594. */
  28595. this.specularMap = null;
  28596. /**
  28597. * The alpha map is a grayscale texture that controls the opacity across the
  28598. * surface (black: fully transparent; white: fully opaque).
  28599. *
  28600. * Only the color of the texture is used, ignoring the alpha channel if one
  28601. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28602. * when sampling this texture due to the extra bit of precision provided for
  28603. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28604. * luminance/alpha textures will also still work as expected.
  28605. *
  28606. * @type {?Texture}
  28607. * @default null
  28608. */
  28609. this.alphaMap = null;
  28610. /**
  28611. * The environment map.
  28612. *
  28613. * @type {?Texture}
  28614. * @default null
  28615. */
  28616. this.envMap = null;
  28617. /**
  28618. * The rotation of the environment map in radians.
  28619. *
  28620. * @type {Euler}
  28621. * @default (0,0,0)
  28622. */
  28623. this.envMapRotation = new Euler();
  28624. /**
  28625. * How to combine the result of the surface's color with the environment map, if any.
  28626. *
  28627. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28628. * blend between the two colors.
  28629. *
  28630. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28631. * @default MultiplyOperation
  28632. */
  28633. this.combine = MultiplyOperation;
  28634. /**
  28635. * How much the environment map affects the surface.
  28636. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28637. *
  28638. * @type {number}
  28639. * @default 1
  28640. */
  28641. this.reflectivity = 1;
  28642. /**
  28643. * The index of refraction (IOR) of air (approximately 1) divided by the
  28644. * index of refraction of the material. It is used with environment mapping
  28645. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28646. * The refraction ratio should not exceed `1`.
  28647. *
  28648. * @type {number}
  28649. * @default 0.98
  28650. */
  28651. this.refractionRatio = 0.98;
  28652. /**
  28653. * Renders the geometry as a wireframe.
  28654. *
  28655. * @type {boolean}
  28656. * @default false
  28657. */
  28658. this.wireframe = false;
  28659. /**
  28660. * Controls the thickness of the wireframe.
  28661. *
  28662. * Can only be used with {@link SVGRenderer}.
  28663. *
  28664. * @type {number}
  28665. * @default 1
  28666. */
  28667. this.wireframeLinewidth = 1;
  28668. /**
  28669. * Defines appearance of wireframe ends.
  28670. *
  28671. * Can only be used with {@link SVGRenderer}.
  28672. *
  28673. * @type {('round'|'bevel'|'miter')}
  28674. * @default 'round'
  28675. */
  28676. this.wireframeLinecap = 'round';
  28677. /**
  28678. * Defines appearance of wireframe joints.
  28679. *
  28680. * Can only be used with {@link SVGRenderer}.
  28681. *
  28682. * @type {('round'|'bevel'|'miter')}
  28683. * @default 'round'
  28684. */
  28685. this.wireframeLinejoin = 'round';
  28686. /**
  28687. * Whether the material is rendered with flat shading or not.
  28688. *
  28689. * @type {boolean}
  28690. * @default false
  28691. */
  28692. this.flatShading = false;
  28693. /**
  28694. * Whether the material is affected by fog or not.
  28695. *
  28696. * @type {boolean}
  28697. * @default true
  28698. */
  28699. this.fog = true;
  28700. this.setValues( parameters );
  28701. }
  28702. copy( source ) {
  28703. super.copy( source );
  28704. this.color.copy( source.color );
  28705. this.specular.copy( source.specular );
  28706. this.shininess = source.shininess;
  28707. this.map = source.map;
  28708. this.lightMap = source.lightMap;
  28709. this.lightMapIntensity = source.lightMapIntensity;
  28710. this.aoMap = source.aoMap;
  28711. this.aoMapIntensity = source.aoMapIntensity;
  28712. this.emissive.copy( source.emissive );
  28713. this.emissiveMap = source.emissiveMap;
  28714. this.emissiveIntensity = source.emissiveIntensity;
  28715. this.bumpMap = source.bumpMap;
  28716. this.bumpScale = source.bumpScale;
  28717. this.normalMap = source.normalMap;
  28718. this.normalMapType = source.normalMapType;
  28719. this.normalScale.copy( source.normalScale );
  28720. this.displacementMap = source.displacementMap;
  28721. this.displacementScale = source.displacementScale;
  28722. this.displacementBias = source.displacementBias;
  28723. this.specularMap = source.specularMap;
  28724. this.alphaMap = source.alphaMap;
  28725. this.envMap = source.envMap;
  28726. this.envMapRotation.copy( source.envMapRotation );
  28727. this.combine = source.combine;
  28728. this.reflectivity = source.reflectivity;
  28729. this.refractionRatio = source.refractionRatio;
  28730. this.wireframe = source.wireframe;
  28731. this.wireframeLinewidth = source.wireframeLinewidth;
  28732. this.wireframeLinecap = source.wireframeLinecap;
  28733. this.wireframeLinejoin = source.wireframeLinejoin;
  28734. this.flatShading = source.flatShading;
  28735. this.fog = source.fog;
  28736. return this;
  28737. }
  28738. }
  28739. /**
  28740. * A material implementing toon shading.
  28741. *
  28742. * @augments Material
  28743. */
  28744. class MeshToonMaterial extends Material {
  28745. /**
  28746. * Constructs a new mesh toon material.
  28747. *
  28748. * @param {Object} [parameters] - An object with one or more properties
  28749. * defining the material's appearance. Any property of the material
  28750. * (including any property from inherited materials) can be passed
  28751. * in here. Color values can be passed any type of value accepted
  28752. * by {@link Color#set}.
  28753. */
  28754. constructor( parameters ) {
  28755. super();
  28756. /**
  28757. * This flag can be used for type testing.
  28758. *
  28759. * @type {boolean}
  28760. * @readonly
  28761. * @default true
  28762. */
  28763. this.isMeshToonMaterial = true;
  28764. this.defines = { 'TOON': '' };
  28765. this.type = 'MeshToonMaterial';
  28766. /**
  28767. * Color of the material.
  28768. *
  28769. * @type {Color}
  28770. * @default (1,1,1)
  28771. */
  28772. this.color = new Color( 0xffffff );
  28773. /**
  28774. * The color map. May optionally include an alpha channel, typically combined
  28775. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28776. * color is modulated by the diffuse `color`.
  28777. *
  28778. * @type {?Texture}
  28779. * @default null
  28780. */
  28781. this.map = null;
  28782. /**
  28783. * Gradient map for toon shading. It's required to set
  28784. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28785. * when using this type of texture.
  28786. *
  28787. * @type {?Texture}
  28788. * @default null
  28789. */
  28790. this.gradientMap = null;
  28791. /**
  28792. * The light map. Requires a second set of UVs.
  28793. *
  28794. * @type {?Texture}
  28795. * @default null
  28796. */
  28797. this.lightMap = null;
  28798. /**
  28799. * Intensity of the baked light.
  28800. *
  28801. * @type {number}
  28802. * @default 1
  28803. */
  28804. this.lightMapIntensity = 1.0;
  28805. /**
  28806. * The red channel of this texture is used as the ambient occlusion map.
  28807. * Requires a second set of UVs.
  28808. *
  28809. * @type {?Texture}
  28810. * @default null
  28811. */
  28812. this.aoMap = null;
  28813. /**
  28814. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28815. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28816. * red channel is also `1`, ambient light is fully occluded on a surface.
  28817. *
  28818. * @type {number}
  28819. * @default 1
  28820. */
  28821. this.aoMapIntensity = 1.0;
  28822. /**
  28823. * Emissive (light) color of the material, essentially a solid color
  28824. * unaffected by other lighting.
  28825. *
  28826. * @type {Color}
  28827. * @default (0,0,0)
  28828. */
  28829. this.emissive = new Color( 0x000000 );
  28830. /**
  28831. * Intensity of the emissive light. Modulates the emissive color.
  28832. *
  28833. * @type {number}
  28834. * @default 1
  28835. */
  28836. this.emissiveIntensity = 1.0;
  28837. /**
  28838. * Set emissive (glow) map. The emissive map color is modulated by the
  28839. * emissive color and the emissive intensity. If you have an emissive map,
  28840. * be sure to set the emissive color to something other than black.
  28841. *
  28842. * @type {?Texture}
  28843. * @default null
  28844. */
  28845. this.emissiveMap = null;
  28846. /**
  28847. * The texture to create a bump map. The black and white values map to the
  28848. * perceived depth in relation to the lights. Bump doesn't actually affect
  28849. * the geometry of the object, only the lighting. If a normal map is defined
  28850. * this will be ignored.
  28851. *
  28852. * @type {?Texture}
  28853. * @default null
  28854. */
  28855. this.bumpMap = null;
  28856. /**
  28857. * How much the bump map affects the material. Typical range is `[0,1]`.
  28858. *
  28859. * @type {number}
  28860. * @default 1
  28861. */
  28862. this.bumpScale = 1;
  28863. /**
  28864. * The texture to create a normal map. The RGB values affect the surface
  28865. * normal for each pixel fragment and change the way the color is lit. Normal
  28866. * maps do not change the actual shape of the surface, only the lighting. In
  28867. * case the material has a normal map authored using the left handed
  28868. * convention, the `y` component of `normalScale` should be negated to compensate
  28869. * for the different handedness.
  28870. *
  28871. * @type {?Texture}
  28872. * @default null
  28873. */
  28874. this.normalMap = null;
  28875. /**
  28876. * The type of normal map.
  28877. *
  28878. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28879. * @default TangentSpaceNormalMap
  28880. */
  28881. this.normalMapType = TangentSpaceNormalMap;
  28882. /**
  28883. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28884. *
  28885. * @type {Vector2}
  28886. * @default (1,1)
  28887. */
  28888. this.normalScale = new Vector2( 1, 1 );
  28889. /**
  28890. * The displacement map affects the position of the mesh's vertices. Unlike
  28891. * other maps which only affect the light and shade of the material the
  28892. * displaced vertices can cast shadows, block other objects, and otherwise
  28893. * act as real geometry. The displacement texture is an image where the value
  28894. * of each pixel (white being the highest) is mapped against, and
  28895. * repositions, the vertices of the mesh.
  28896. *
  28897. * @type {?Texture}
  28898. * @default null
  28899. */
  28900. this.displacementMap = null;
  28901. /**
  28902. * How much the displacement map affects the mesh (where black is no
  28903. * displacement, and white is maximum displacement). Without a displacement
  28904. * map set, this value is not applied.
  28905. *
  28906. * @type {number}
  28907. * @default 0
  28908. */
  28909. this.displacementScale = 1;
  28910. /**
  28911. * The offset of the displacement map's values on the mesh's vertices.
  28912. * The bias is added to the scaled sample of the displacement map.
  28913. * Without a displacement map set, this value is not applied.
  28914. *
  28915. * @type {number}
  28916. * @default 0
  28917. */
  28918. this.displacementBias = 0;
  28919. /**
  28920. * The alpha map is a grayscale texture that controls the opacity across the
  28921. * surface (black: fully transparent; white: fully opaque).
  28922. *
  28923. * Only the color of the texture is used, ignoring the alpha channel if one
  28924. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28925. * when sampling this texture due to the extra bit of precision provided for
  28926. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28927. * luminance/alpha textures will also still work as expected.
  28928. *
  28929. * @type {?Texture}
  28930. * @default null
  28931. */
  28932. this.alphaMap = null;
  28933. /**
  28934. * Renders the geometry as a wireframe.
  28935. *
  28936. * @type {boolean}
  28937. * @default false
  28938. */
  28939. this.wireframe = false;
  28940. /**
  28941. * Controls the thickness of the wireframe.
  28942. *
  28943. * Can only be used with {@link SVGRenderer}.
  28944. *
  28945. * @type {number}
  28946. * @default 1
  28947. */
  28948. this.wireframeLinewidth = 1;
  28949. /**
  28950. * Defines appearance of wireframe ends.
  28951. *
  28952. * Can only be used with {@link SVGRenderer}.
  28953. *
  28954. * @type {('round'|'bevel'|'miter')}
  28955. * @default 'round'
  28956. */
  28957. this.wireframeLinecap = 'round';
  28958. /**
  28959. * Defines appearance of wireframe joints.
  28960. *
  28961. * Can only be used with {@link SVGRenderer}.
  28962. *
  28963. * @type {('round'|'bevel'|'miter')}
  28964. * @default 'round'
  28965. */
  28966. this.wireframeLinejoin = 'round';
  28967. /**
  28968. * Whether the material is affected by fog or not.
  28969. *
  28970. * @type {boolean}
  28971. * @default true
  28972. */
  28973. this.fog = true;
  28974. this.setValues( parameters );
  28975. }
  28976. copy( source ) {
  28977. super.copy( source );
  28978. this.color.copy( source.color );
  28979. this.map = source.map;
  28980. this.gradientMap = source.gradientMap;
  28981. this.lightMap = source.lightMap;
  28982. this.lightMapIntensity = source.lightMapIntensity;
  28983. this.aoMap = source.aoMap;
  28984. this.aoMapIntensity = source.aoMapIntensity;
  28985. this.emissive.copy( source.emissive );
  28986. this.emissiveMap = source.emissiveMap;
  28987. this.emissiveIntensity = source.emissiveIntensity;
  28988. this.bumpMap = source.bumpMap;
  28989. this.bumpScale = source.bumpScale;
  28990. this.normalMap = source.normalMap;
  28991. this.normalMapType = source.normalMapType;
  28992. this.normalScale.copy( source.normalScale );
  28993. this.displacementMap = source.displacementMap;
  28994. this.displacementScale = source.displacementScale;
  28995. this.displacementBias = source.displacementBias;
  28996. this.alphaMap = source.alphaMap;
  28997. this.wireframe = source.wireframe;
  28998. this.wireframeLinewidth = source.wireframeLinewidth;
  28999. this.wireframeLinecap = source.wireframeLinecap;
  29000. this.wireframeLinejoin = source.wireframeLinejoin;
  29001. this.fog = source.fog;
  29002. return this;
  29003. }
  29004. }
  29005. /**
  29006. * A material that maps the normal vectors to RGB colors.
  29007. *
  29008. * @augments Material
  29009. */
  29010. class MeshNormalMaterial extends Material {
  29011. /**
  29012. * Constructs a new mesh normal material.
  29013. *
  29014. * @param {Object} [parameters] - An object with one or more properties
  29015. * defining the material's appearance. Any property of the material
  29016. * (including any property from inherited materials) can be passed
  29017. * in here. Color values can be passed any type of value accepted
  29018. * by {@link Color#set}.
  29019. */
  29020. constructor( parameters ) {
  29021. super();
  29022. /**
  29023. * This flag can be used for type testing.
  29024. *
  29025. * @type {boolean}
  29026. * @readonly
  29027. * @default true
  29028. */
  29029. this.isMeshNormalMaterial = true;
  29030. this.type = 'MeshNormalMaterial';
  29031. /**
  29032. * The texture to create a bump map. The black and white values map to the
  29033. * perceived depth in relation to the lights. Bump doesn't actually affect
  29034. * the geometry of the object, only the lighting. If a normal map is defined
  29035. * this will be ignored.
  29036. *
  29037. * @type {?Texture}
  29038. * @default null
  29039. */
  29040. this.bumpMap = null;
  29041. /**
  29042. * How much the bump map affects the material. Typical range is `[0,1]`.
  29043. *
  29044. * @type {number}
  29045. * @default 1
  29046. */
  29047. this.bumpScale = 1;
  29048. /**
  29049. * The texture to create a normal map. The RGB values affect the surface
  29050. * normal for each pixel fragment and change the way the color is lit. Normal
  29051. * maps do not change the actual shape of the surface, only the lighting. In
  29052. * case the material has a normal map authored using the left handed
  29053. * convention, the `y` component of `normalScale` should be negated to compensate
  29054. * for the different handedness.
  29055. *
  29056. * @type {?Texture}
  29057. * @default null
  29058. */
  29059. this.normalMap = null;
  29060. /**
  29061. * The type of normal map.
  29062. *
  29063. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29064. * @default TangentSpaceNormalMap
  29065. */
  29066. this.normalMapType = TangentSpaceNormalMap;
  29067. /**
  29068. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29069. *
  29070. * @type {Vector2}
  29071. * @default (1,1)
  29072. */
  29073. this.normalScale = new Vector2( 1, 1 );
  29074. /**
  29075. * The displacement map affects the position of the mesh's vertices. Unlike
  29076. * other maps which only affect the light and shade of the material the
  29077. * displaced vertices can cast shadows, block other objects, and otherwise
  29078. * act as real geometry. The displacement texture is an image where the value
  29079. * of each pixel (white being the highest) is mapped against, and
  29080. * repositions, the vertices of the mesh.
  29081. *
  29082. * @type {?Texture}
  29083. * @default null
  29084. */
  29085. this.displacementMap = null;
  29086. /**
  29087. * How much the displacement map affects the mesh (where black is no
  29088. * displacement, and white is maximum displacement). Without a displacement
  29089. * map set, this value is not applied.
  29090. *
  29091. * @type {number}
  29092. * @default 0
  29093. */
  29094. this.displacementScale = 1;
  29095. /**
  29096. * The offset of the displacement map's values on the mesh's vertices.
  29097. * The bias is added to the scaled sample of the displacement map.
  29098. * Without a displacement map set, this value is not applied.
  29099. *
  29100. * @type {number}
  29101. * @default 0
  29102. */
  29103. this.displacementBias = 0;
  29104. /**
  29105. * Renders the geometry as a wireframe.
  29106. *
  29107. * @type {boolean}
  29108. * @default false
  29109. */
  29110. this.wireframe = false;
  29111. /**
  29112. * Controls the thickness of the wireframe.
  29113. *
  29114. * WebGL and WebGPU ignore this property and always render
  29115. * 1 pixel wide lines.
  29116. *
  29117. * @type {number}
  29118. * @default 1
  29119. */
  29120. this.wireframeLinewidth = 1;
  29121. /**
  29122. * Whether the material is rendered with flat shading or not.
  29123. *
  29124. * @type {boolean}
  29125. * @default false
  29126. */
  29127. this.flatShading = false;
  29128. this.setValues( parameters );
  29129. }
  29130. copy( source ) {
  29131. super.copy( source );
  29132. this.bumpMap = source.bumpMap;
  29133. this.bumpScale = source.bumpScale;
  29134. this.normalMap = source.normalMap;
  29135. this.normalMapType = source.normalMapType;
  29136. this.normalScale.copy( source.normalScale );
  29137. this.displacementMap = source.displacementMap;
  29138. this.displacementScale = source.displacementScale;
  29139. this.displacementBias = source.displacementBias;
  29140. this.wireframe = source.wireframe;
  29141. this.wireframeLinewidth = source.wireframeLinewidth;
  29142. this.flatShading = source.flatShading;
  29143. return this;
  29144. }
  29145. }
  29146. /**
  29147. * A material for non-shiny surfaces, without specular highlights.
  29148. *
  29149. * The material uses a non-physically based [Lambertian]{@link https://en.wikipedia.org/wiki/Lambertian_reflectance}
  29150. * model for calculating reflectance. This can simulate some surfaces (such
  29151. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29152. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29153. * shading.
  29154. *
  29155. * Due to the simplicity of the reflectance and illumination models,
  29156. * performance will be greater when using this material over the
  29157. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29158. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29159. *
  29160. * @augments Material
  29161. */
  29162. class MeshLambertMaterial extends Material {
  29163. /**
  29164. * Constructs a new mesh lambert material.
  29165. *
  29166. * @param {Object} [parameters] - An object with one or more properties
  29167. * defining the material's appearance. Any property of the material
  29168. * (including any property from inherited materials) can be passed
  29169. * in here. Color values can be passed any type of value accepted
  29170. * by {@link Color#set}.
  29171. */
  29172. constructor( parameters ) {
  29173. super();
  29174. /**
  29175. * This flag can be used for type testing.
  29176. *
  29177. * @type {boolean}
  29178. * @readonly
  29179. * @default true
  29180. */
  29181. this.isMeshLambertMaterial = true;
  29182. this.type = 'MeshLambertMaterial';
  29183. /**
  29184. * Color of the material.
  29185. *
  29186. * @type {Color}
  29187. * @default (1,1,1)
  29188. */
  29189. this.color = new Color( 0xffffff ); // diffuse
  29190. /**
  29191. * The color map. May optionally include an alpha channel, typically combined
  29192. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29193. * color is modulated by the diffuse `color`.
  29194. *
  29195. * @type {?Texture}
  29196. * @default null
  29197. */
  29198. this.map = null;
  29199. /**
  29200. * The light map. Requires a second set of UVs.
  29201. *
  29202. * @type {?Texture}
  29203. * @default null
  29204. */
  29205. this.lightMap = null;
  29206. /**
  29207. * Intensity of the baked light.
  29208. *
  29209. * @type {number}
  29210. * @default 1
  29211. */
  29212. this.lightMapIntensity = 1.0;
  29213. /**
  29214. * The red channel of this texture is used as the ambient occlusion map.
  29215. * Requires a second set of UVs.
  29216. *
  29217. * @type {?Texture}
  29218. * @default null
  29219. */
  29220. this.aoMap = null;
  29221. /**
  29222. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29223. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29224. * red channel is also `1`, ambient light is fully occluded on a surface.
  29225. *
  29226. * @type {number}
  29227. * @default 1
  29228. */
  29229. this.aoMapIntensity = 1.0;
  29230. /**
  29231. * Emissive (light) color of the material, essentially a solid color
  29232. * unaffected by other lighting.
  29233. *
  29234. * @type {Color}
  29235. * @default (0,0,0)
  29236. */
  29237. this.emissive = new Color( 0x000000 );
  29238. /**
  29239. * Intensity of the emissive light. Modulates the emissive color.
  29240. *
  29241. * @type {number}
  29242. * @default 1
  29243. */
  29244. this.emissiveIntensity = 1.0;
  29245. /**
  29246. * Set emissive (glow) map. The emissive map color is modulated by the
  29247. * emissive color and the emissive intensity. If you have an emissive map,
  29248. * be sure to set the emissive color to something other than black.
  29249. *
  29250. * @type {?Texture}
  29251. * @default null
  29252. */
  29253. this.emissiveMap = null;
  29254. /**
  29255. * The texture to create a bump map. The black and white values map to the
  29256. * perceived depth in relation to the lights. Bump doesn't actually affect
  29257. * the geometry of the object, only the lighting. If a normal map is defined
  29258. * this will be ignored.
  29259. *
  29260. * @type {?Texture}
  29261. * @default null
  29262. */
  29263. this.bumpMap = null;
  29264. /**
  29265. * How much the bump map affects the material. Typical range is `[0,1]`.
  29266. *
  29267. * @type {number}
  29268. * @default 1
  29269. */
  29270. this.bumpScale = 1;
  29271. /**
  29272. * The texture to create a normal map. The RGB values affect the surface
  29273. * normal for each pixel fragment and change the way the color is lit. Normal
  29274. * maps do not change the actual shape of the surface, only the lighting. In
  29275. * case the material has a normal map authored using the left handed
  29276. * convention, the `y` component of `normalScale` should be negated to compensate
  29277. * for the different handedness.
  29278. *
  29279. * @type {?Texture}
  29280. * @default null
  29281. */
  29282. this.normalMap = null;
  29283. /**
  29284. * The type of normal map.
  29285. *
  29286. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29287. * @default TangentSpaceNormalMap
  29288. */
  29289. this.normalMapType = TangentSpaceNormalMap;
  29290. /**
  29291. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29292. *
  29293. * @type {Vector2}
  29294. * @default (1,1)
  29295. */
  29296. this.normalScale = new Vector2( 1, 1 );
  29297. /**
  29298. * The displacement map affects the position of the mesh's vertices. Unlike
  29299. * other maps which only affect the light and shade of the material the
  29300. * displaced vertices can cast shadows, block other objects, and otherwise
  29301. * act as real geometry. The displacement texture is an image where the value
  29302. * of each pixel (white being the highest) is mapped against, and
  29303. * repositions, the vertices of the mesh.
  29304. *
  29305. * @type {?Texture}
  29306. * @default null
  29307. */
  29308. this.displacementMap = null;
  29309. /**
  29310. * How much the displacement map affects the mesh (where black is no
  29311. * displacement, and white is maximum displacement). Without a displacement
  29312. * map set, this value is not applied.
  29313. *
  29314. * @type {number}
  29315. * @default 0
  29316. */
  29317. this.displacementScale = 1;
  29318. /**
  29319. * The offset of the displacement map's values on the mesh's vertices.
  29320. * The bias is added to the scaled sample of the displacement map.
  29321. * Without a displacement map set, this value is not applied.
  29322. *
  29323. * @type {number}
  29324. * @default 0
  29325. */
  29326. this.displacementBias = 0;
  29327. /**
  29328. * Specular map used by the material.
  29329. *
  29330. * @type {?Texture}
  29331. * @default null
  29332. */
  29333. this.specularMap = null;
  29334. /**
  29335. * The alpha map is a grayscale texture that controls the opacity across the
  29336. * surface (black: fully transparent; white: fully opaque).
  29337. *
  29338. * Only the color of the texture is used, ignoring the alpha channel if one
  29339. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29340. * when sampling this texture due to the extra bit of precision provided for
  29341. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29342. * luminance/alpha textures will also still work as expected.
  29343. *
  29344. * @type {?Texture}
  29345. * @default null
  29346. */
  29347. this.alphaMap = null;
  29348. /**
  29349. * The environment map.
  29350. *
  29351. * @type {?Texture}
  29352. * @default null
  29353. */
  29354. this.envMap = null;
  29355. /**
  29356. * The rotation of the environment map in radians.
  29357. *
  29358. * @type {Euler}
  29359. * @default (0,0,0)
  29360. */
  29361. this.envMapRotation = new Euler();
  29362. /**
  29363. * How to combine the result of the surface's color with the environment map, if any.
  29364. *
  29365. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29366. * blend between the two colors.
  29367. *
  29368. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29369. * @default MultiplyOperation
  29370. */
  29371. this.combine = MultiplyOperation;
  29372. /**
  29373. * How much the environment map affects the surface.
  29374. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29375. *
  29376. * @type {number}
  29377. * @default 1
  29378. */
  29379. this.reflectivity = 1;
  29380. /**
  29381. * The index of refraction (IOR) of air (approximately 1) divided by the
  29382. * index of refraction of the material. It is used with environment mapping
  29383. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29384. * The refraction ratio should not exceed `1`.
  29385. *
  29386. * @type {number}
  29387. * @default 0.98
  29388. */
  29389. this.refractionRatio = 0.98;
  29390. /**
  29391. * Renders the geometry as a wireframe.
  29392. *
  29393. * @type {boolean}
  29394. * @default false
  29395. */
  29396. this.wireframe = false;
  29397. /**
  29398. * Controls the thickness of the wireframe.
  29399. *
  29400. * Can only be used with {@link SVGRenderer}.
  29401. *
  29402. * @type {number}
  29403. * @default 1
  29404. */
  29405. this.wireframeLinewidth = 1;
  29406. /**
  29407. * Defines appearance of wireframe ends.
  29408. *
  29409. * Can only be used with {@link SVGRenderer}.
  29410. *
  29411. * @type {('round'|'bevel'|'miter')}
  29412. * @default 'round'
  29413. */
  29414. this.wireframeLinecap = 'round';
  29415. /**
  29416. * Defines appearance of wireframe joints.
  29417. *
  29418. * Can only be used with {@link SVGRenderer}.
  29419. *
  29420. * @type {('round'|'bevel'|'miter')}
  29421. * @default 'round'
  29422. */
  29423. this.wireframeLinejoin = 'round';
  29424. /**
  29425. * Whether the material is rendered with flat shading or not.
  29426. *
  29427. * @type {boolean}
  29428. * @default false
  29429. */
  29430. this.flatShading = false;
  29431. /**
  29432. * Whether the material is affected by fog or not.
  29433. *
  29434. * @type {boolean}
  29435. * @default true
  29436. */
  29437. this.fog = true;
  29438. this.setValues( parameters );
  29439. }
  29440. copy( source ) {
  29441. super.copy( source );
  29442. this.color.copy( source.color );
  29443. this.map = source.map;
  29444. this.lightMap = source.lightMap;
  29445. this.lightMapIntensity = source.lightMapIntensity;
  29446. this.aoMap = source.aoMap;
  29447. this.aoMapIntensity = source.aoMapIntensity;
  29448. this.emissive.copy( source.emissive );
  29449. this.emissiveMap = source.emissiveMap;
  29450. this.emissiveIntensity = source.emissiveIntensity;
  29451. this.bumpMap = source.bumpMap;
  29452. this.bumpScale = source.bumpScale;
  29453. this.normalMap = source.normalMap;
  29454. this.normalMapType = source.normalMapType;
  29455. this.normalScale.copy( source.normalScale );
  29456. this.displacementMap = source.displacementMap;
  29457. this.displacementScale = source.displacementScale;
  29458. this.displacementBias = source.displacementBias;
  29459. this.specularMap = source.specularMap;
  29460. this.alphaMap = source.alphaMap;
  29461. this.envMap = source.envMap;
  29462. this.envMapRotation.copy( source.envMapRotation );
  29463. this.combine = source.combine;
  29464. this.reflectivity = source.reflectivity;
  29465. this.refractionRatio = source.refractionRatio;
  29466. this.wireframe = source.wireframe;
  29467. this.wireframeLinewidth = source.wireframeLinewidth;
  29468. this.wireframeLinecap = source.wireframeLinecap;
  29469. this.wireframeLinejoin = source.wireframeLinejoin;
  29470. this.flatShading = source.flatShading;
  29471. this.fog = source.fog;
  29472. return this;
  29473. }
  29474. }
  29475. /**
  29476. * A material for drawing geometry by depth. Depth is based off of the camera
  29477. * near and far plane. White is nearest, black is farthest.
  29478. *
  29479. * @augments Material
  29480. */
  29481. class MeshDepthMaterial extends Material {
  29482. /**
  29483. * Constructs a new mesh depth material.
  29484. *
  29485. * @param {Object} [parameters] - An object with one or more properties
  29486. * defining the material's appearance. Any property of the material
  29487. * (including any property from inherited materials) can be passed
  29488. * in here. Color values can be passed any type of value accepted
  29489. * by {@link Color#set}.
  29490. */
  29491. constructor( parameters ) {
  29492. super();
  29493. /**
  29494. * This flag can be used for type testing.
  29495. *
  29496. * @type {boolean}
  29497. * @readonly
  29498. * @default true
  29499. */
  29500. this.isMeshDepthMaterial = true;
  29501. this.type = 'MeshDepthMaterial';
  29502. /**
  29503. * Type for depth packing.
  29504. *
  29505. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29506. * @default BasicDepthPacking
  29507. */
  29508. this.depthPacking = BasicDepthPacking;
  29509. /**
  29510. * The color map. May optionally include an alpha channel, typically combined
  29511. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29512. *
  29513. * @type {?Texture}
  29514. * @default null
  29515. */
  29516. this.map = null;
  29517. /**
  29518. * The alpha map is a grayscale texture that controls the opacity across the
  29519. * surface (black: fully transparent; white: fully opaque).
  29520. *
  29521. * Only the color of the texture is used, ignoring the alpha channel if one
  29522. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29523. * when sampling this texture due to the extra bit of precision provided for
  29524. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29525. * luminance/alpha textures will also still work as expected.
  29526. *
  29527. * @type {?Texture}
  29528. * @default null
  29529. */
  29530. this.alphaMap = null;
  29531. /**
  29532. * The displacement map affects the position of the mesh's vertices. Unlike
  29533. * other maps which only affect the light and shade of the material the
  29534. * displaced vertices can cast shadows, block other objects, and otherwise
  29535. * act as real geometry. The displacement texture is an image where the value
  29536. * of each pixel (white being the highest) is mapped against, and
  29537. * repositions, the vertices of the mesh.
  29538. *
  29539. * @type {?Texture}
  29540. * @default null
  29541. */
  29542. this.displacementMap = null;
  29543. /**
  29544. * How much the displacement map affects the mesh (where black is no
  29545. * displacement, and white is maximum displacement). Without a displacement
  29546. * map set, this value is not applied.
  29547. *
  29548. * @type {number}
  29549. * @default 0
  29550. */
  29551. this.displacementScale = 1;
  29552. /**
  29553. * The offset of the displacement map's values on the mesh's vertices.
  29554. * The bias is added to the scaled sample of the displacement map.
  29555. * Without a displacement map set, this value is not applied.
  29556. *
  29557. * @type {number}
  29558. * @default 0
  29559. */
  29560. this.displacementBias = 0;
  29561. /**
  29562. * Renders the geometry as a wireframe.
  29563. *
  29564. * @type {boolean}
  29565. * @default false
  29566. */
  29567. this.wireframe = false;
  29568. /**
  29569. * Controls the thickness of the wireframe.
  29570. *
  29571. * WebGL and WebGPU ignore this property and always render
  29572. * 1 pixel wide lines.
  29573. *
  29574. * @type {number}
  29575. * @default 1
  29576. */
  29577. this.wireframeLinewidth = 1;
  29578. this.setValues( parameters );
  29579. }
  29580. copy( source ) {
  29581. super.copy( source );
  29582. this.depthPacking = source.depthPacking;
  29583. this.map = source.map;
  29584. this.alphaMap = source.alphaMap;
  29585. this.displacementMap = source.displacementMap;
  29586. this.displacementScale = source.displacementScale;
  29587. this.displacementBias = source.displacementBias;
  29588. this.wireframe = source.wireframe;
  29589. this.wireframeLinewidth = source.wireframeLinewidth;
  29590. return this;
  29591. }
  29592. }
  29593. /**
  29594. * A material used internally for implementing shadow mapping with
  29595. * point lights.
  29596. *
  29597. * Can also be used to customize the shadow casting of an object by assigning
  29598. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29599. * The following examples demonstrates this approach in order to ensure
  29600. * transparent parts of objects do no cast shadows.
  29601. *
  29602. * @augments Material
  29603. */
  29604. class MeshDistanceMaterial extends Material {
  29605. /**
  29606. * Constructs a new mesh distance material.
  29607. *
  29608. * @param {Object} [parameters] - An object with one or more properties
  29609. * defining the material's appearance. Any property of the material
  29610. * (including any property from inherited materials) can be passed
  29611. * in here. Color values can be passed any type of value accepted
  29612. * by {@link Color#set}.
  29613. */
  29614. constructor( parameters ) {
  29615. super();
  29616. /**
  29617. * This flag can be used for type testing.
  29618. *
  29619. * @type {boolean}
  29620. * @readonly
  29621. * @default true
  29622. */
  29623. this.isMeshDistanceMaterial = true;
  29624. this.type = 'MeshDistanceMaterial';
  29625. /**
  29626. * The color map. May optionally include an alpha channel, typically combined
  29627. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29628. *
  29629. * @type {?Texture}
  29630. * @default null
  29631. */
  29632. this.map = null;
  29633. /**
  29634. * The alpha map is a grayscale texture that controls the opacity across the
  29635. * surface (black: fully transparent; white: fully opaque).
  29636. *
  29637. * Only the color of the texture is used, ignoring the alpha channel if one
  29638. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29639. * when sampling this texture due to the extra bit of precision provided for
  29640. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29641. * luminance/alpha textures will also still work as expected.
  29642. *
  29643. * @type {?Texture}
  29644. * @default null
  29645. */
  29646. this.alphaMap = null;
  29647. /**
  29648. * The displacement map affects the position of the mesh's vertices. Unlike
  29649. * other maps which only affect the light and shade of the material the
  29650. * displaced vertices can cast shadows, block other objects, and otherwise
  29651. * act as real geometry. The displacement texture is an image where the value
  29652. * of each pixel (white being the highest) is mapped against, and
  29653. * repositions, the vertices of the mesh.
  29654. *
  29655. * @type {?Texture}
  29656. * @default null
  29657. */
  29658. this.displacementMap = null;
  29659. /**
  29660. * How much the displacement map affects the mesh (where black is no
  29661. * displacement, and white is maximum displacement). Without a displacement
  29662. * map set, this value is not applied.
  29663. *
  29664. * @type {number}
  29665. * @default 0
  29666. */
  29667. this.displacementScale = 1;
  29668. /**
  29669. * The offset of the displacement map's values on the mesh's vertices.
  29670. * The bias is added to the scaled sample of the displacement map.
  29671. * Without a displacement map set, this value is not applied.
  29672. *
  29673. * @type {number}
  29674. * @default 0
  29675. */
  29676. this.displacementBias = 0;
  29677. this.setValues( parameters );
  29678. }
  29679. copy( source ) {
  29680. super.copy( source );
  29681. this.map = source.map;
  29682. this.alphaMap = source.alphaMap;
  29683. this.displacementMap = source.displacementMap;
  29684. this.displacementScale = source.displacementScale;
  29685. this.displacementBias = source.displacementBias;
  29686. return this;
  29687. }
  29688. }
  29689. /**
  29690. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29691. * material color and shading.
  29692. *
  29693. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29694. * baked lighting. It will cast a shadow onto an object that receives shadows
  29695. * (and shadow clipping works), but it will not self-shadow or receive
  29696. * shadows.
  29697. *
  29698. * @augments Material
  29699. */
  29700. class MeshMatcapMaterial extends Material {
  29701. /**
  29702. * Constructs a new mesh matcap material.
  29703. *
  29704. * @param {Object} [parameters] - An object with one or more properties
  29705. * defining the material's appearance. Any property of the material
  29706. * (including any property from inherited materials) can be passed
  29707. * in here. Color values can be passed any type of value accepted
  29708. * by {@link Color#set}.
  29709. */
  29710. constructor( parameters ) {
  29711. super();
  29712. /**
  29713. * This flag can be used for type testing.
  29714. *
  29715. * @type {boolean}
  29716. * @readonly
  29717. * @default true
  29718. */
  29719. this.isMeshMatcapMaterial = true;
  29720. this.defines = { 'MATCAP': '' };
  29721. this.type = 'MeshMatcapMaterial';
  29722. /**
  29723. * Color of the material.
  29724. *
  29725. * @type {Color}
  29726. * @default (1,1,1)
  29727. */
  29728. this.color = new Color( 0xffffff ); // diffuse
  29729. /**
  29730. * The matcap map.
  29731. *
  29732. * @type {?Texture}
  29733. * @default null
  29734. */
  29735. this.matcap = null;
  29736. /**
  29737. * The color map. May optionally include an alpha channel, typically combined
  29738. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29739. * color is modulated by the diffuse `color`.
  29740. *
  29741. * @type {?Texture}
  29742. * @default null
  29743. */
  29744. this.map = null;
  29745. /**
  29746. * The texture to create a bump map. The black and white values map to the
  29747. * perceived depth in relation to the lights. Bump doesn't actually affect
  29748. * the geometry of the object, only the lighting. If a normal map is defined
  29749. * this will be ignored.
  29750. *
  29751. * @type {?Texture}
  29752. * @default null
  29753. */
  29754. this.bumpMap = null;
  29755. /**
  29756. * How much the bump map affects the material. Typical range is `[0,1]`.
  29757. *
  29758. * @type {number}
  29759. * @default 1
  29760. */
  29761. this.bumpScale = 1;
  29762. /**
  29763. * The texture to create a normal map. The RGB values affect the surface
  29764. * normal for each pixel fragment and change the way the color is lit. Normal
  29765. * maps do not change the actual shape of the surface, only the lighting. In
  29766. * case the material has a normal map authored using the left handed
  29767. * convention, the `y` component of `normalScale` should be negated to compensate
  29768. * for the different handedness.
  29769. *
  29770. * @type {?Texture}
  29771. * @default null
  29772. */
  29773. this.normalMap = null;
  29774. /**
  29775. * The type of normal map.
  29776. *
  29777. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29778. * @default TangentSpaceNormalMap
  29779. */
  29780. this.normalMapType = TangentSpaceNormalMap;
  29781. /**
  29782. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29783. *
  29784. * @type {Vector2}
  29785. * @default (1,1)
  29786. */
  29787. this.normalScale = new Vector2( 1, 1 );
  29788. /**
  29789. * The displacement map affects the position of the mesh's vertices. Unlike
  29790. * other maps which only affect the light and shade of the material the
  29791. * displaced vertices can cast shadows, block other objects, and otherwise
  29792. * act as real geometry. The displacement texture is an image where the value
  29793. * of each pixel (white being the highest) is mapped against, and
  29794. * repositions, the vertices of the mesh.
  29795. *
  29796. * @type {?Texture}
  29797. * @default null
  29798. */
  29799. this.displacementMap = null;
  29800. /**
  29801. * How much the displacement map affects the mesh (where black is no
  29802. * displacement, and white is maximum displacement). Without a displacement
  29803. * map set, this value is not applied.
  29804. *
  29805. * @type {number}
  29806. * @default 0
  29807. */
  29808. this.displacementScale = 1;
  29809. /**
  29810. * The offset of the displacement map's values on the mesh's vertices.
  29811. * The bias is added to the scaled sample of the displacement map.
  29812. * Without a displacement map set, this value is not applied.
  29813. *
  29814. * @type {number}
  29815. * @default 0
  29816. */
  29817. this.displacementBias = 0;
  29818. /**
  29819. * The alpha map is a grayscale texture that controls the opacity across the
  29820. * surface (black: fully transparent; white: fully opaque).
  29821. *
  29822. * Only the color of the texture is used, ignoring the alpha channel if one
  29823. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29824. * when sampling this texture due to the extra bit of precision provided for
  29825. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29826. * luminance/alpha textures will also still work as expected.
  29827. *
  29828. * @type {?Texture}
  29829. * @default null
  29830. */
  29831. this.alphaMap = null;
  29832. /**
  29833. * Whether the material is rendered with flat shading or not.
  29834. *
  29835. * @type {boolean}
  29836. * @default false
  29837. */
  29838. this.flatShading = false;
  29839. /**
  29840. * Whether the material is affected by fog or not.
  29841. *
  29842. * @type {boolean}
  29843. * @default true
  29844. */
  29845. this.fog = true;
  29846. this.setValues( parameters );
  29847. }
  29848. copy( source ) {
  29849. super.copy( source );
  29850. this.defines = { 'MATCAP': '' };
  29851. this.color.copy( source.color );
  29852. this.matcap = source.matcap;
  29853. this.map = source.map;
  29854. this.bumpMap = source.bumpMap;
  29855. this.bumpScale = source.bumpScale;
  29856. this.normalMap = source.normalMap;
  29857. this.normalMapType = source.normalMapType;
  29858. this.normalScale.copy( source.normalScale );
  29859. this.displacementMap = source.displacementMap;
  29860. this.displacementScale = source.displacementScale;
  29861. this.displacementBias = source.displacementBias;
  29862. this.alphaMap = source.alphaMap;
  29863. this.flatShading = source.flatShading;
  29864. this.fog = source.fog;
  29865. return this;
  29866. }
  29867. }
  29868. /**
  29869. * A material for rendering line primitives.
  29870. *
  29871. * Materials define the appearance of renderable 3D objects.
  29872. *
  29873. * ```js
  29874. * const material = new THREE.LineDashedMaterial( {
  29875. * color: 0xffffff,
  29876. * scale: 1,
  29877. * dashSize: 3,
  29878. * gapSize: 1,
  29879. * } );
  29880. * ```
  29881. *
  29882. * @augments LineBasicMaterial
  29883. */
  29884. class LineDashedMaterial extends LineBasicMaterial {
  29885. /**
  29886. * Constructs a new line dashed material.
  29887. *
  29888. * @param {Object} [parameters] - An object with one or more properties
  29889. * defining the material's appearance. Any property of the material
  29890. * (including any property from inherited materials) can be passed
  29891. * in here. Color values can be passed any type of value accepted
  29892. * by {@link Color#set}.
  29893. */
  29894. constructor( parameters ) {
  29895. super();
  29896. /**
  29897. * This flag can be used for type testing.
  29898. *
  29899. * @type {boolean}
  29900. * @readonly
  29901. * @default true
  29902. */
  29903. this.isLineDashedMaterial = true;
  29904. this.type = 'LineDashedMaterial';
  29905. /**
  29906. * The scale of the dashed part of a line.
  29907. *
  29908. * @type {number}
  29909. * @default 1
  29910. */
  29911. this.scale = 1;
  29912. /**
  29913. * The size of the dash. This is both the gap with the stroke.
  29914. *
  29915. * @type {number}
  29916. * @default 3
  29917. */
  29918. this.dashSize = 3;
  29919. /**
  29920. * The size of the gap.
  29921. *
  29922. * @type {number}
  29923. * @default 1
  29924. */
  29925. this.gapSize = 1;
  29926. this.setValues( parameters );
  29927. }
  29928. copy( source ) {
  29929. super.copy( source );
  29930. this.scale = source.scale;
  29931. this.dashSize = source.dashSize;
  29932. this.gapSize = source.gapSize;
  29933. return this;
  29934. }
  29935. }
  29936. /**
  29937. * Converts an array to a specific type.
  29938. *
  29939. * @param {TypedArray|Array} array - The array to convert.
  29940. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29941. * @return {TypedArray} The converted array.
  29942. */
  29943. function convertArray( array, type ) {
  29944. if ( ! array || array.constructor === type ) return array;
  29945. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29946. return new type( array ); // create typed array
  29947. }
  29948. return Array.prototype.slice.call( array ); // create Array
  29949. }
  29950. /**
  29951. * Returns `true` if the given object is a typed array.
  29952. *
  29953. * @param {any} object - The object to check.
  29954. * @return {boolean} Whether the given object is a typed array.
  29955. */
  29956. function isTypedArray( object ) {
  29957. return ArrayBuffer.isView( object ) && ! ( object instanceof DataView );
  29958. }
  29959. /**
  29960. * Returns an array by which times and values can be sorted.
  29961. *
  29962. * @param {Array<number>} times - The keyframe time values.
  29963. * @return {Array<number>} The array.
  29964. */
  29965. function getKeyframeOrder( times ) {
  29966. function compareTime( i, j ) {
  29967. return times[ i ] - times[ j ];
  29968. }
  29969. const n = times.length;
  29970. const result = new Array( n );
  29971. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29972. result.sort( compareTime );
  29973. return result;
  29974. }
  29975. /**
  29976. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29977. *
  29978. * @param {Array<number>} values - The values to sort.
  29979. * @param {number} stride - The stride.
  29980. * @param {Array<number>} order - The sort order.
  29981. * @return {Array<number>} The sorted values.
  29982. */
  29983. function sortedArray( values, stride, order ) {
  29984. const nValues = values.length;
  29985. const result = new values.constructor( nValues );
  29986. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29987. const srcOffset = order[ i ] * stride;
  29988. for ( let j = 0; j !== stride; ++ j ) {
  29989. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29990. }
  29991. }
  29992. return result;
  29993. }
  29994. /**
  29995. * Used for parsing AOS keyframe formats.
  29996. *
  29997. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29998. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  29999. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30000. * @param {string} valuePropertyName - The name of the property to use.
  30001. */
  30002. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30003. let i = 1, key = jsonKeys[ 0 ];
  30004. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30005. key = jsonKeys[ i ++ ];
  30006. }
  30007. if ( key === undefined ) return; // no data
  30008. let value = key[ valuePropertyName ];
  30009. if ( value === undefined ) return; // no data
  30010. if ( Array.isArray( value ) ) {
  30011. do {
  30012. value = key[ valuePropertyName ];
  30013. if ( value !== undefined ) {
  30014. times.push( key.time );
  30015. values.push( ...value ); // push all elements
  30016. }
  30017. key = jsonKeys[ i ++ ];
  30018. } while ( key !== undefined );
  30019. } else if ( value.toArray !== undefined ) {
  30020. // ...assume THREE.Math-ish
  30021. do {
  30022. value = key[ valuePropertyName ];
  30023. if ( value !== undefined ) {
  30024. times.push( key.time );
  30025. value.toArray( values, values.length );
  30026. }
  30027. key = jsonKeys[ i ++ ];
  30028. } while ( key !== undefined );
  30029. } else {
  30030. // otherwise push as-is
  30031. do {
  30032. value = key[ valuePropertyName ];
  30033. if ( value !== undefined ) {
  30034. times.push( key.time );
  30035. values.push( value );
  30036. }
  30037. key = jsonKeys[ i ++ ];
  30038. } while ( key !== undefined );
  30039. }
  30040. }
  30041. /**
  30042. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30043. *
  30044. * @param {AnimationClip} sourceClip - The values to sort.
  30045. * @param {string} name - The name of the clip.
  30046. * @param {number} startFrame - The start frame.
  30047. * @param {number} endFrame - The end frame.
  30048. * @param {number} [fps=30] - The FPS.
  30049. * @return {AnimationClip} The new sub clip.
  30050. */
  30051. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30052. const clip = sourceClip.clone();
  30053. clip.name = name;
  30054. const tracks = [];
  30055. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30056. const track = clip.tracks[ i ];
  30057. const valueSize = track.getValueSize();
  30058. const times = [];
  30059. const values = [];
  30060. for ( let j = 0; j < track.times.length; ++ j ) {
  30061. const frame = track.times[ j ] * fps;
  30062. if ( frame < startFrame || frame >= endFrame ) continue;
  30063. times.push( track.times[ j ] );
  30064. for ( let k = 0; k < valueSize; ++ k ) {
  30065. values.push( track.values[ j * valueSize + k ] );
  30066. }
  30067. }
  30068. if ( times.length === 0 ) continue;
  30069. track.times = convertArray( times, track.times.constructor );
  30070. track.values = convertArray( values, track.values.constructor );
  30071. tracks.push( track );
  30072. }
  30073. clip.tracks = tracks;
  30074. // find minimum .times value across all tracks in the trimmed clip
  30075. let minStartTime = Infinity;
  30076. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30077. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30078. minStartTime = clip.tracks[ i ].times[ 0 ];
  30079. }
  30080. }
  30081. // shift all tracks such that clip begins at t=0
  30082. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30083. clip.tracks[ i ].shift( -1 * minStartTime );
  30084. }
  30085. clip.resetDuration();
  30086. return clip;
  30087. }
  30088. /**
  30089. * Converts the keyframes of the given animation clip to an additive format.
  30090. *
  30091. * @param {AnimationClip} targetClip - The clip to make additive.
  30092. * @param {number} [referenceFrame=0] - The reference frame.
  30093. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30094. * @param {number} [fps=30] - The FPS.
  30095. * @return {AnimationClip} The updated clip which is now additive.
  30096. */
  30097. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30098. if ( fps <= 0 ) fps = 30;
  30099. const numTracks = referenceClip.tracks.length;
  30100. const referenceTime = referenceFrame / fps;
  30101. // Make each track's values relative to the values at the reference frame
  30102. for ( let i = 0; i < numTracks; ++ i ) {
  30103. const referenceTrack = referenceClip.tracks[ i ];
  30104. const referenceTrackType = referenceTrack.ValueTypeName;
  30105. // Skip this track if it's non-numeric
  30106. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30107. // Find the track in the target clip whose name and type matches the reference track
  30108. const targetTrack = targetClip.tracks.find( function ( track ) {
  30109. return track.name === referenceTrack.name
  30110. && track.ValueTypeName === referenceTrackType;
  30111. } );
  30112. if ( targetTrack === undefined ) continue;
  30113. let referenceOffset = 0;
  30114. const referenceValueSize = referenceTrack.getValueSize();
  30115. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30116. referenceOffset = referenceValueSize / 3;
  30117. }
  30118. let targetOffset = 0;
  30119. const targetValueSize = targetTrack.getValueSize();
  30120. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30121. targetOffset = targetValueSize / 3;
  30122. }
  30123. const lastIndex = referenceTrack.times.length - 1;
  30124. let referenceValue;
  30125. // Find the value to subtract out of the track
  30126. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30127. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30128. const startIndex = referenceOffset;
  30129. const endIndex = referenceValueSize - referenceOffset;
  30130. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30131. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30132. // Reference frame is after the last keyframe, so just use the last keyframe
  30133. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30134. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30135. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30136. } else {
  30137. // Interpolate to the reference value
  30138. const interpolant = referenceTrack.createInterpolant();
  30139. const startIndex = referenceOffset;
  30140. const endIndex = referenceValueSize - referenceOffset;
  30141. interpolant.evaluate( referenceTime );
  30142. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30143. }
  30144. // Conjugate the quaternion
  30145. if ( referenceTrackType === 'quaternion' ) {
  30146. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30147. referenceQuat.toArray( referenceValue );
  30148. }
  30149. // Subtract the reference value from all of the track values
  30150. const numTimes = targetTrack.times.length;
  30151. for ( let j = 0; j < numTimes; ++ j ) {
  30152. const valueStart = j * targetValueSize + targetOffset;
  30153. if ( referenceTrackType === 'quaternion' ) {
  30154. // Multiply the conjugate for quaternion track types
  30155. Quaternion.multiplyQuaternionsFlat(
  30156. targetTrack.values,
  30157. valueStart,
  30158. referenceValue,
  30159. 0,
  30160. targetTrack.values,
  30161. valueStart
  30162. );
  30163. } else {
  30164. const valueEnd = targetValueSize - targetOffset * 2;
  30165. // Subtract each value for all other numeric track types
  30166. for ( let k = 0; k < valueEnd; ++ k ) {
  30167. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30168. }
  30169. }
  30170. }
  30171. }
  30172. targetClip.blendMode = AdditiveAnimationBlendMode;
  30173. return targetClip;
  30174. }
  30175. /**
  30176. * A class with various methods to assist with animations.
  30177. *
  30178. * @hideconstructor
  30179. */
  30180. class AnimationUtils {
  30181. /**
  30182. * Converts an array to a specific type
  30183. *
  30184. * @static
  30185. * @param {TypedArray|Array} array - The array to convert.
  30186. * @param {TypedArray.constructor} type - The constructor of a type array.
  30187. * @return {TypedArray} The converted array
  30188. */
  30189. static convertArray( array, type ) {
  30190. return convertArray( array, type );
  30191. }
  30192. /**
  30193. * Returns `true` if the given object is a typed array.
  30194. *
  30195. * @static
  30196. * @param {any} object - The object to check.
  30197. * @return {boolean} Whether the given object is a typed array.
  30198. */
  30199. static isTypedArray( object ) {
  30200. return isTypedArray( object );
  30201. }
  30202. /**
  30203. * Returns an array by which times and values can be sorted.
  30204. *
  30205. * @static
  30206. * @param {Array<number>} times - The keyframe time values.
  30207. * @return {Array<number>} The array.
  30208. */
  30209. static getKeyframeOrder( times ) {
  30210. return getKeyframeOrder( times );
  30211. }
  30212. /**
  30213. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30214. *
  30215. * @static
  30216. * @param {Array<number>} values - The values to sort.
  30217. * @param {number} stride - The stride.
  30218. * @param {Array<number>} order - The sort order.
  30219. * @return {Array<number>} The sorted values.
  30220. */
  30221. static sortedArray( values, stride, order ) {
  30222. return sortedArray( values, stride, order );
  30223. }
  30224. /**
  30225. * Used for parsing AOS keyframe formats.
  30226. *
  30227. * @static
  30228. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30229. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30230. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30231. * @param {string} valuePropertyName - The name of the property to use.
  30232. */
  30233. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30234. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30235. }
  30236. /**
  30237. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30238. *
  30239. * @static
  30240. * @param {AnimationClip} sourceClip - The values to sort.
  30241. * @param {string} name - The name of the clip.
  30242. * @param {number} startFrame - The start frame.
  30243. * @param {number} endFrame - The end frame.
  30244. * @param {number} [fps=30] - The FPS.
  30245. * @return {AnimationClip} The new sub clip.
  30246. */
  30247. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30248. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30249. }
  30250. /**
  30251. * Converts the keyframes of the given animation clip to an additive format.
  30252. *
  30253. * @static
  30254. * @param {AnimationClip} targetClip - The clip to make additive.
  30255. * @param {number} [referenceFrame=0] - The reference frame.
  30256. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30257. * @param {number} [fps=30] - The FPS.
  30258. * @return {AnimationClip} The updated clip which is now additive.
  30259. */
  30260. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30261. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30262. }
  30263. }
  30264. /**
  30265. * Abstract base class of interpolants over parametric samples.
  30266. *
  30267. * The parameter domain is one dimensional, typically the time or a path
  30268. * along a curve defined by the data.
  30269. *
  30270. * The sample values can have any dimensionality and derived classes may
  30271. * apply special interpretations to the data.
  30272. *
  30273. * This class provides the interval seek in a Template Method, deferring
  30274. * the actual interpolation to derived classes.
  30275. *
  30276. * Time complexity is O(1) for linear access crossing at most two points
  30277. * and O(log N) for random access, where N is the number of positions.
  30278. *
  30279. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30280. *
  30281. * @abstract
  30282. */
  30283. class Interpolant {
  30284. /**
  30285. * Constructs a new interpolant.
  30286. *
  30287. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30288. * @param {TypedArray} sampleValues - The sample values.
  30289. * @param {number} sampleSize - The sample size
  30290. * @param {TypedArray} [resultBuffer] - The result buffer.
  30291. */
  30292. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30293. /**
  30294. * The parameter positions.
  30295. *
  30296. * @type {TypedArray}
  30297. */
  30298. this.parameterPositions = parameterPositions;
  30299. /**
  30300. * A cache index.
  30301. *
  30302. * @private
  30303. * @type {number}
  30304. * @default 0
  30305. */
  30306. this._cachedIndex = 0;
  30307. /**
  30308. * The result buffer.
  30309. *
  30310. * @type {TypedArray}
  30311. */
  30312. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30313. /**
  30314. * The sample values.
  30315. *
  30316. * @type {TypedArray}
  30317. */
  30318. this.sampleValues = sampleValues;
  30319. /**
  30320. * The value size.
  30321. *
  30322. * @type {TypedArray}
  30323. */
  30324. this.valueSize = sampleSize;
  30325. /**
  30326. * The interpolation settings.
  30327. *
  30328. * @type {?Object}
  30329. * @default null
  30330. */
  30331. this.settings = null;
  30332. /**
  30333. * The default settings object.
  30334. *
  30335. * @type {Object}
  30336. */
  30337. this.DefaultSettings_ = {};
  30338. }
  30339. /**
  30340. * Evaluate the interpolant at position `t`.
  30341. *
  30342. * @param {number} t - The interpolation factor.
  30343. * @return {TypedArray} The result buffer.
  30344. */
  30345. evaluate( t ) {
  30346. const pp = this.parameterPositions;
  30347. let i1 = this._cachedIndex,
  30348. t1 = pp[ i1 ],
  30349. t0 = pp[ i1 - 1 ];
  30350. validate_interval: {
  30351. seek: {
  30352. let right;
  30353. linear_scan: {
  30354. //- See http://jsperf.com/comparison-to-undefined/3
  30355. //- slower code:
  30356. //-
  30357. //- if ( t >= t1 || t1 === undefined ) {
  30358. forward_scan: if ( ! ( t < t1 ) ) {
  30359. for ( let giveUpAt = i1 + 2; ; ) {
  30360. if ( t1 === undefined ) {
  30361. if ( t < t0 ) break forward_scan;
  30362. // after end
  30363. i1 = pp.length;
  30364. this._cachedIndex = i1;
  30365. return this.copySampleValue_( i1 - 1 );
  30366. }
  30367. if ( i1 === giveUpAt ) break; // this loop
  30368. t0 = t1;
  30369. t1 = pp[ ++ i1 ];
  30370. if ( t < t1 ) {
  30371. // we have arrived at the sought interval
  30372. break seek;
  30373. }
  30374. }
  30375. // prepare binary search on the right side of the index
  30376. right = pp.length;
  30377. break linear_scan;
  30378. }
  30379. //- slower code:
  30380. //- if ( t < t0 || t0 === undefined ) {
  30381. if ( ! ( t >= t0 ) ) {
  30382. // looping?
  30383. const t1global = pp[ 1 ];
  30384. if ( t < t1global ) {
  30385. i1 = 2; // + 1, using the scan for the details
  30386. t0 = t1global;
  30387. }
  30388. // linear reverse scan
  30389. for ( let giveUpAt = i1 - 2; ; ) {
  30390. if ( t0 === undefined ) {
  30391. // before start
  30392. this._cachedIndex = 0;
  30393. return this.copySampleValue_( 0 );
  30394. }
  30395. if ( i1 === giveUpAt ) break; // this loop
  30396. t1 = t0;
  30397. t0 = pp[ -- i1 - 1 ];
  30398. if ( t >= t0 ) {
  30399. // we have arrived at the sought interval
  30400. break seek;
  30401. }
  30402. }
  30403. // prepare binary search on the left side of the index
  30404. right = i1;
  30405. i1 = 0;
  30406. break linear_scan;
  30407. }
  30408. // the interval is valid
  30409. break validate_interval;
  30410. } // linear scan
  30411. // binary search
  30412. while ( i1 < right ) {
  30413. const mid = ( i1 + right ) >>> 1;
  30414. if ( t < pp[ mid ] ) {
  30415. right = mid;
  30416. } else {
  30417. i1 = mid + 1;
  30418. }
  30419. }
  30420. t1 = pp[ i1 ];
  30421. t0 = pp[ i1 - 1 ];
  30422. // check boundary cases, again
  30423. if ( t0 === undefined ) {
  30424. this._cachedIndex = 0;
  30425. return this.copySampleValue_( 0 );
  30426. }
  30427. if ( t1 === undefined ) {
  30428. i1 = pp.length;
  30429. this._cachedIndex = i1;
  30430. return this.copySampleValue_( i1 - 1 );
  30431. }
  30432. } // seek
  30433. this._cachedIndex = i1;
  30434. this.intervalChanged_( i1, t0, t1 );
  30435. } // validate_interval
  30436. return this.interpolate_( i1, t0, t, t1 );
  30437. }
  30438. /**
  30439. * Returns the interpolation settings.
  30440. *
  30441. * @return {Object} The interpolation settings.
  30442. */
  30443. getSettings_() {
  30444. return this.settings || this.DefaultSettings_;
  30445. }
  30446. /**
  30447. * Copies a sample value to the result buffer.
  30448. *
  30449. * @param {number} index - An index into the sample value buffer.
  30450. * @return {TypedArray} The result buffer.
  30451. */
  30452. copySampleValue_( index ) {
  30453. // copies a sample value to the result buffer
  30454. const result = this.resultBuffer,
  30455. values = this.sampleValues,
  30456. stride = this.valueSize,
  30457. offset = index * stride;
  30458. for ( let i = 0; i !== stride; ++ i ) {
  30459. result[ i ] = values[ offset + i ];
  30460. }
  30461. return result;
  30462. }
  30463. /**
  30464. * Copies a sample value to the result buffer.
  30465. *
  30466. * @abstract
  30467. * @param {number} i1 - An index into the sample value buffer.
  30468. * @param {number} t0 - The previous interpolation factor.
  30469. * @param {number} t - The current interpolation factor.
  30470. * @param {number} t1 - The next interpolation factor.
  30471. * @return {TypedArray} The result buffer.
  30472. */
  30473. interpolate_( /* i1, t0, t, t1 */ ) {
  30474. throw new Error( 'call to abstract method' );
  30475. // implementations shall return this.resultBuffer
  30476. }
  30477. /**
  30478. * Optional method that is executed when the interval has changed.
  30479. *
  30480. * @param {number} i1 - An index into the sample value buffer.
  30481. * @param {number} t0 - The previous interpolation factor.
  30482. * @param {number} t - The current interpolation factor.
  30483. */
  30484. intervalChanged_( /* i1, t0, t1 */ ) {
  30485. // empty
  30486. }
  30487. }
  30488. /**
  30489. * Fast and simple cubic spline interpolant.
  30490. *
  30491. * It was derived from a Hermitian construction setting the first derivative
  30492. * at each sample position to the linear slope between neighboring positions
  30493. * over their parameter interval.
  30494. *
  30495. * @augments Interpolant
  30496. */
  30497. class CubicInterpolant extends Interpolant {
  30498. /**
  30499. * Constructs a new cubic interpolant.
  30500. *
  30501. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30502. * @param {TypedArray} sampleValues - The sample values.
  30503. * @param {number} sampleSize - The sample size
  30504. * @param {TypedArray} [resultBuffer] - The result buffer.
  30505. */
  30506. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30507. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30508. this._weightPrev = -0;
  30509. this._offsetPrev = -0;
  30510. this._weightNext = -0;
  30511. this._offsetNext = -0;
  30512. this.DefaultSettings_ = {
  30513. endingStart: ZeroCurvatureEnding,
  30514. endingEnd: ZeroCurvatureEnding
  30515. };
  30516. }
  30517. intervalChanged_( i1, t0, t1 ) {
  30518. const pp = this.parameterPositions;
  30519. let iPrev = i1 - 2,
  30520. iNext = i1 + 1,
  30521. tPrev = pp[ iPrev ],
  30522. tNext = pp[ iNext ];
  30523. if ( tPrev === undefined ) {
  30524. switch ( this.getSettings_().endingStart ) {
  30525. case ZeroSlopeEnding:
  30526. // f'(t0) = 0
  30527. iPrev = i1;
  30528. tPrev = 2 * t0 - t1;
  30529. break;
  30530. case WrapAroundEnding:
  30531. // use the other end of the curve
  30532. iPrev = pp.length - 2;
  30533. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30534. break;
  30535. default: // ZeroCurvatureEnding
  30536. // f''(t0) = 0 a.k.a. Natural Spline
  30537. iPrev = i1;
  30538. tPrev = t1;
  30539. }
  30540. }
  30541. if ( tNext === undefined ) {
  30542. switch ( this.getSettings_().endingEnd ) {
  30543. case ZeroSlopeEnding:
  30544. // f'(tN) = 0
  30545. iNext = i1;
  30546. tNext = 2 * t1 - t0;
  30547. break;
  30548. case WrapAroundEnding:
  30549. // use the other end of the curve
  30550. iNext = 1;
  30551. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30552. break;
  30553. default: // ZeroCurvatureEnding
  30554. // f''(tN) = 0, a.k.a. Natural Spline
  30555. iNext = i1 - 1;
  30556. tNext = t0;
  30557. }
  30558. }
  30559. const halfDt = ( t1 - t0 ) * 0.5,
  30560. stride = this.valueSize;
  30561. this._weightPrev = halfDt / ( t0 - tPrev );
  30562. this._weightNext = halfDt / ( tNext - t1 );
  30563. this._offsetPrev = iPrev * stride;
  30564. this._offsetNext = iNext * stride;
  30565. }
  30566. interpolate_( i1, t0, t, t1 ) {
  30567. const result = this.resultBuffer,
  30568. values = this.sampleValues,
  30569. stride = this.valueSize,
  30570. o1 = i1 * stride, o0 = o1 - stride,
  30571. oP = this._offsetPrev, oN = this._offsetNext,
  30572. wP = this._weightPrev, wN = this._weightNext,
  30573. p = ( t - t0 ) / ( t1 - t0 ),
  30574. pp = p * p,
  30575. ppp = pp * p;
  30576. // evaluate polynomials
  30577. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30578. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30579. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30580. const sN = wN * ppp - wN * pp;
  30581. // combine data linearly
  30582. for ( let i = 0; i !== stride; ++ i ) {
  30583. result[ i ] =
  30584. sP * values[ oP + i ] +
  30585. s0 * values[ o0 + i ] +
  30586. s1 * values[ o1 + i ] +
  30587. sN * values[ oN + i ];
  30588. }
  30589. return result;
  30590. }
  30591. }
  30592. /**
  30593. * A basic linear interpolant.
  30594. *
  30595. * @augments Interpolant
  30596. */
  30597. class LinearInterpolant extends Interpolant {
  30598. /**
  30599. * Constructs a new linear interpolant.
  30600. *
  30601. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30602. * @param {TypedArray} sampleValues - The sample values.
  30603. * @param {number} sampleSize - The sample size
  30604. * @param {TypedArray} [resultBuffer] - The result buffer.
  30605. */
  30606. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30607. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30608. }
  30609. interpolate_( i1, t0, t, t1 ) {
  30610. const result = this.resultBuffer,
  30611. values = this.sampleValues,
  30612. stride = this.valueSize,
  30613. offset1 = i1 * stride,
  30614. offset0 = offset1 - stride,
  30615. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30616. weight0 = 1 - weight1;
  30617. for ( let i = 0; i !== stride; ++ i ) {
  30618. result[ i ] =
  30619. values[ offset0 + i ] * weight0 +
  30620. values[ offset1 + i ] * weight1;
  30621. }
  30622. return result;
  30623. }
  30624. }
  30625. /**
  30626. * Interpolant that evaluates to the sample value at the position preceding
  30627. * the parameter.
  30628. *
  30629. * @augments Interpolant
  30630. */
  30631. class DiscreteInterpolant extends Interpolant {
  30632. /**
  30633. * Constructs a new discrete interpolant.
  30634. *
  30635. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30636. * @param {TypedArray} sampleValues - The sample values.
  30637. * @param {number} sampleSize - The sample size
  30638. * @param {TypedArray} [resultBuffer] - The result buffer.
  30639. */
  30640. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30641. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30642. }
  30643. interpolate_( i1 /*, t0, t, t1 */ ) {
  30644. return this.copySampleValue_( i1 - 1 );
  30645. }
  30646. }
  30647. /**
  30648. * Represents s a timed sequence of keyframes, which are composed of lists of
  30649. * times and related values, and which are used to animate a specific property
  30650. * of an object.
  30651. */
  30652. class KeyframeTrack {
  30653. /**
  30654. * Constructs a new keyframe track.
  30655. *
  30656. * @param {string} name - The keyframe track's name.
  30657. * @param {Array<number>} times - A list of keyframe times.
  30658. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30659. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30660. */
  30661. constructor( name, times, values, interpolation ) {
  30662. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30663. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30664. /**
  30665. * The track's name can refer to morph targets or bones or
  30666. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30667. * for the forms of strings that can be parsed for property binding.
  30668. *
  30669. * @type {string}
  30670. */
  30671. this.name = name;
  30672. /**
  30673. * The keyframe times.
  30674. *
  30675. * @type {Float32Array}
  30676. */
  30677. this.times = convertArray( times, this.TimeBufferType );
  30678. /**
  30679. * The keyframe values.
  30680. *
  30681. * @type {Float32Array}
  30682. */
  30683. this.values = convertArray( values, this.ValueBufferType );
  30684. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30685. }
  30686. /**
  30687. * Converts the keyframe track to JSON.
  30688. *
  30689. * @static
  30690. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30691. * @return {Object} The serialized keyframe track as JSON.
  30692. */
  30693. static toJSON( track ) {
  30694. const trackType = track.constructor;
  30695. let json;
  30696. // derived classes can define a static toJSON method
  30697. if ( trackType.toJSON !== this.toJSON ) {
  30698. json = trackType.toJSON( track );
  30699. } else {
  30700. // by default, we assume the data can be serialized as-is
  30701. json = {
  30702. 'name': track.name,
  30703. 'times': convertArray( track.times, Array ),
  30704. 'values': convertArray( track.values, Array )
  30705. };
  30706. const interpolation = track.getInterpolation();
  30707. if ( interpolation !== track.DefaultInterpolation ) {
  30708. json.interpolation = interpolation;
  30709. }
  30710. }
  30711. json.type = track.ValueTypeName; // mandatory
  30712. return json;
  30713. }
  30714. /**
  30715. * Factory method for creating a new discrete interpolant.
  30716. *
  30717. * @static
  30718. * @param {TypedArray} [result] - The result buffer.
  30719. * @return {DiscreteInterpolant} The new interpolant.
  30720. */
  30721. InterpolantFactoryMethodDiscrete( result ) {
  30722. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30723. }
  30724. /**
  30725. * Factory method for creating a new linear interpolant.
  30726. *
  30727. * @static
  30728. * @param {TypedArray} [result] - The result buffer.
  30729. * @return {LinearInterpolant} The new interpolant.
  30730. */
  30731. InterpolantFactoryMethodLinear( result ) {
  30732. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30733. }
  30734. /**
  30735. * Factory method for creating a new smooth interpolant.
  30736. *
  30737. * @static
  30738. * @param {TypedArray} [result] - The result buffer.
  30739. * @return {CubicInterpolant} The new interpolant.
  30740. */
  30741. InterpolantFactoryMethodSmooth( result ) {
  30742. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30743. }
  30744. /**
  30745. * Defines the interpolation factor method for this keyframe track.
  30746. *
  30747. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  30748. * @return {KeyframeTrack} A reference to this keyframe track.
  30749. */
  30750. setInterpolation( interpolation ) {
  30751. let factoryMethod;
  30752. switch ( interpolation ) {
  30753. case InterpolateDiscrete:
  30754. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30755. break;
  30756. case InterpolateLinear:
  30757. factoryMethod = this.InterpolantFactoryMethodLinear;
  30758. break;
  30759. case InterpolateSmooth:
  30760. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30761. break;
  30762. }
  30763. if ( factoryMethod === undefined ) {
  30764. const message = 'unsupported interpolation for ' +
  30765. this.ValueTypeName + ' keyframe track named ' + this.name;
  30766. if ( this.createInterpolant === undefined ) {
  30767. // fall back to default, unless the default itself is messed up
  30768. if ( interpolation !== this.DefaultInterpolation ) {
  30769. this.setInterpolation( this.DefaultInterpolation );
  30770. } else {
  30771. throw new Error( message ); // fatal, in this case
  30772. }
  30773. }
  30774. console.warn( 'THREE.KeyframeTrack:', message );
  30775. return this;
  30776. }
  30777. this.createInterpolant = factoryMethod;
  30778. return this;
  30779. }
  30780. /**
  30781. * Returns the current interpolation type.
  30782. *
  30783. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  30784. */
  30785. getInterpolation() {
  30786. switch ( this.createInterpolant ) {
  30787. case this.InterpolantFactoryMethodDiscrete:
  30788. return InterpolateDiscrete;
  30789. case this.InterpolantFactoryMethodLinear:
  30790. return InterpolateLinear;
  30791. case this.InterpolantFactoryMethodSmooth:
  30792. return InterpolateSmooth;
  30793. }
  30794. }
  30795. /**
  30796. * Returns the value size.
  30797. *
  30798. * @return {number} The value size.
  30799. */
  30800. getValueSize() {
  30801. return this.values.length / this.times.length;
  30802. }
  30803. /**
  30804. * Moves all keyframes either forward or backward in time.
  30805. *
  30806. * @param {number} timeOffset - The offset to move the time values.
  30807. * @return {KeyframeTrack} A reference to this keyframe track.
  30808. */
  30809. shift( timeOffset ) {
  30810. if ( timeOffset !== 0.0 ) {
  30811. const times = this.times;
  30812. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30813. times[ i ] += timeOffset;
  30814. }
  30815. }
  30816. return this;
  30817. }
  30818. /**
  30819. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30820. *
  30821. * @param {number} timeScale - The time scale.
  30822. * @return {KeyframeTrack} A reference to this keyframe track.
  30823. */
  30824. scale( timeScale ) {
  30825. if ( timeScale !== 1.0 ) {
  30826. const times = this.times;
  30827. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30828. times[ i ] *= timeScale;
  30829. }
  30830. }
  30831. return this;
  30832. }
  30833. /**
  30834. * Removes keyframes before and after animation without changing any values within the defined time range.
  30835. *
  30836. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30837. * keys this will change their values
  30838. *
  30839. * @param {number} startTime - The start time.
  30840. * @param {number} endTime - The end time.
  30841. * @return {KeyframeTrack} A reference to this keyframe track.
  30842. */
  30843. trim( startTime, endTime ) {
  30844. const times = this.times,
  30845. nKeys = times.length;
  30846. let from = 0,
  30847. to = nKeys - 1;
  30848. while ( from !== nKeys && times[ from ] < startTime ) {
  30849. ++ from;
  30850. }
  30851. while ( to !== -1 && times[ to ] > endTime ) {
  30852. -- to;
  30853. }
  30854. ++ to; // inclusive -> exclusive bound
  30855. if ( from !== 0 || to !== nKeys ) {
  30856. // empty tracks are forbidden, so keep at least one keyframe
  30857. if ( from >= to ) {
  30858. to = Math.max( to, 1 );
  30859. from = to - 1;
  30860. }
  30861. const stride = this.getValueSize();
  30862. this.times = times.slice( from, to );
  30863. this.values = this.values.slice( from * stride, to * stride );
  30864. }
  30865. return this;
  30866. }
  30867. /**
  30868. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30869. * are valid.
  30870. *
  30871. * @return {boolean} Whether the keyframes are valid or not.
  30872. */
  30873. validate() {
  30874. let valid = true;
  30875. const valueSize = this.getValueSize();
  30876. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30877. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  30878. valid = false;
  30879. }
  30880. const times = this.times,
  30881. values = this.values,
  30882. nKeys = times.length;
  30883. if ( nKeys === 0 ) {
  30884. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  30885. valid = false;
  30886. }
  30887. let prevTime = null;
  30888. for ( let i = 0; i !== nKeys; i ++ ) {
  30889. const currTime = times[ i ];
  30890. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30891. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30892. valid = false;
  30893. break;
  30894. }
  30895. if ( prevTime !== null && prevTime > currTime ) {
  30896. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30897. valid = false;
  30898. break;
  30899. }
  30900. prevTime = currTime;
  30901. }
  30902. if ( values !== undefined ) {
  30903. if ( isTypedArray( values ) ) {
  30904. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30905. const value = values[ i ];
  30906. if ( isNaN( value ) ) {
  30907. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  30908. valid = false;
  30909. break;
  30910. }
  30911. }
  30912. }
  30913. }
  30914. return valid;
  30915. }
  30916. /**
  30917. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30918. * common in morph target sequences).
  30919. *
  30920. * @return {AnimationClip} A reference to this animation clip.
  30921. */
  30922. optimize() {
  30923. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30924. // times or values may be shared with other tracks, so overwriting is unsafe
  30925. const times = this.times.slice(),
  30926. values = this.values.slice(),
  30927. stride = this.getValueSize(),
  30928. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30929. lastIndex = times.length - 1;
  30930. let writeIndex = 1;
  30931. for ( let i = 1; i < lastIndex; ++ i ) {
  30932. let keep = false;
  30933. const time = times[ i ];
  30934. const timeNext = times[ i + 1 ];
  30935. // remove adjacent keyframes scheduled at the same time
  30936. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30937. if ( ! smoothInterpolation ) {
  30938. // remove unnecessary keyframes same as their neighbors
  30939. const offset = i * stride,
  30940. offsetP = offset - stride,
  30941. offsetN = offset + stride;
  30942. for ( let j = 0; j !== stride; ++ j ) {
  30943. const value = values[ offset + j ];
  30944. if ( value !== values[ offsetP + j ] ||
  30945. value !== values[ offsetN + j ] ) {
  30946. keep = true;
  30947. break;
  30948. }
  30949. }
  30950. } else {
  30951. keep = true;
  30952. }
  30953. }
  30954. // in-place compaction
  30955. if ( keep ) {
  30956. if ( i !== writeIndex ) {
  30957. times[ writeIndex ] = times[ i ];
  30958. const readOffset = i * stride,
  30959. writeOffset = writeIndex * stride;
  30960. for ( let j = 0; j !== stride; ++ j ) {
  30961. values[ writeOffset + j ] = values[ readOffset + j ];
  30962. }
  30963. }
  30964. ++ writeIndex;
  30965. }
  30966. }
  30967. // flush last keyframe (compaction looks ahead)
  30968. if ( lastIndex > 0 ) {
  30969. times[ writeIndex ] = times[ lastIndex ];
  30970. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  30971. values[ writeOffset + j ] = values[ readOffset + j ];
  30972. }
  30973. ++ writeIndex;
  30974. }
  30975. if ( writeIndex !== times.length ) {
  30976. this.times = times.slice( 0, writeIndex );
  30977. this.values = values.slice( 0, writeIndex * stride );
  30978. } else {
  30979. this.times = times;
  30980. this.values = values;
  30981. }
  30982. return this;
  30983. }
  30984. /**
  30985. * Returns a new keyframe track with copied values from this instance.
  30986. *
  30987. * @return {KeyframeTrack} A clone of this instance.
  30988. */
  30989. clone() {
  30990. const times = this.times.slice();
  30991. const values = this.values.slice();
  30992. const TypedKeyframeTrack = this.constructor;
  30993. const track = new TypedKeyframeTrack( this.name, times, values );
  30994. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  30995. track.createInterpolant = this.createInterpolant;
  30996. return track;
  30997. }
  30998. }
  30999. /**
  31000. * The value type name.
  31001. *
  31002. * @type {String}
  31003. * @default ''
  31004. */
  31005. KeyframeTrack.prototype.ValueTypeName = '';
  31006. /**
  31007. * The time buffer type of this keyframe track.
  31008. *
  31009. * @type {TypedArray|Array}
  31010. * @default Float32Array.constructor
  31011. */
  31012. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31013. /**
  31014. * The value buffer type of this keyframe track.
  31015. *
  31016. * @type {TypedArray|Array}
  31017. * @default Float32Array.constructor
  31018. */
  31019. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31020. /**
  31021. * The default interpolation type of this keyframe track.
  31022. *
  31023. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31024. * @default InterpolateLinear
  31025. */
  31026. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31027. /**
  31028. * A track for boolean keyframe values.
  31029. *
  31030. * @augments KeyframeTrack
  31031. */
  31032. class BooleanKeyframeTrack extends KeyframeTrack {
  31033. /**
  31034. * Constructs a new boolean keyframe track.
  31035. *
  31036. * This keyframe track type has no `interpolation` parameter because the
  31037. * interpolation is always discrete.
  31038. *
  31039. * @param {string} name - The keyframe track's name.
  31040. * @param {Array<number>} times - A list of keyframe times.
  31041. * @param {Array<boolean>} values - A list of keyframe values.
  31042. */
  31043. constructor( name, times, values ) {
  31044. super( name, times, values );
  31045. }
  31046. }
  31047. /**
  31048. * The value type name.
  31049. *
  31050. * @type {String}
  31051. * @default 'bool'
  31052. */
  31053. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31054. /**
  31055. * The value buffer type of this keyframe track.
  31056. *
  31057. * @type {TypedArray|Array}
  31058. * @default Array.constructor
  31059. */
  31060. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31061. /**
  31062. * The default interpolation type of this keyframe track.
  31063. *
  31064. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31065. * @default InterpolateDiscrete
  31066. */
  31067. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31068. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31069. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31070. /**
  31071. * A track for color keyframe values.
  31072. *
  31073. * @augments KeyframeTrack
  31074. */
  31075. class ColorKeyframeTrack extends KeyframeTrack {
  31076. /**
  31077. * Constructs a new color keyframe track.
  31078. *
  31079. * @param {string} name - The keyframe track's name.
  31080. * @param {Array<number>} times - A list of keyframe times.
  31081. * @param {Array<number>} values - A list of keyframe values.
  31082. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31083. */
  31084. constructor( name, times, values, interpolation ) {
  31085. super( name, times, values, interpolation );
  31086. }
  31087. }
  31088. /**
  31089. * The value type name.
  31090. *
  31091. * @type {String}
  31092. * @default 'color'
  31093. */
  31094. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31095. /**
  31096. * A track for numeric keyframe values.
  31097. *
  31098. * @augments KeyframeTrack
  31099. */
  31100. class NumberKeyframeTrack extends KeyframeTrack {
  31101. /**
  31102. * Constructs a new number keyframe track.
  31103. *
  31104. * @param {string} name - The keyframe track's name.
  31105. * @param {Array<number>} times - A list of keyframe times.
  31106. * @param {Array<number>} values - A list of keyframe values.
  31107. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31108. */
  31109. constructor( name, times, values, interpolation ) {
  31110. super( name, times, values, interpolation );
  31111. }
  31112. }
  31113. /**
  31114. * The value type name.
  31115. *
  31116. * @type {String}
  31117. * @default 'number'
  31118. */
  31119. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31120. /**
  31121. * Spherical linear unit quaternion interpolant.
  31122. *
  31123. * @augments Interpolant
  31124. */
  31125. class QuaternionLinearInterpolant extends Interpolant {
  31126. /**
  31127. * Constructs a new SLERP interpolant.
  31128. *
  31129. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31130. * @param {TypedArray} sampleValues - The sample values.
  31131. * @param {number} sampleSize - The sample size
  31132. * @param {TypedArray} [resultBuffer] - The result buffer.
  31133. */
  31134. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31135. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31136. }
  31137. interpolate_( i1, t0, t, t1 ) {
  31138. const result = this.resultBuffer,
  31139. values = this.sampleValues,
  31140. stride = this.valueSize,
  31141. alpha = ( t - t0 ) / ( t1 - t0 );
  31142. let offset = i1 * stride;
  31143. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31144. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31145. }
  31146. return result;
  31147. }
  31148. }
  31149. /**
  31150. * A track for Quaternion keyframe values.
  31151. *
  31152. * @augments KeyframeTrack
  31153. */
  31154. class QuaternionKeyframeTrack extends KeyframeTrack {
  31155. /**
  31156. * Constructs a new Quaternion keyframe track.
  31157. *
  31158. * @param {string} name - The keyframe track's name.
  31159. * @param {Array<number>} times - A list of keyframe times.
  31160. * @param {Array<number>} values - A list of keyframe values.
  31161. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31162. */
  31163. constructor( name, times, values, interpolation ) {
  31164. super( name, times, values, interpolation );
  31165. }
  31166. /**
  31167. * Overwritten so the method returns Quaternion based interpolant.
  31168. *
  31169. * @static
  31170. * @param {TypedArray} [result] - The result buffer.
  31171. * @return {QuaternionLinearInterpolant} The new interpolant.
  31172. */
  31173. InterpolantFactoryMethodLinear( result ) {
  31174. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31175. }
  31176. }
  31177. /**
  31178. * The value type name.
  31179. *
  31180. * @type {String}
  31181. * @default 'quaternion'
  31182. */
  31183. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31184. // ValueBufferType is inherited
  31185. // DefaultInterpolation is inherited;
  31186. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31187. /**
  31188. * A track for string keyframe values.
  31189. *
  31190. * @augments KeyframeTrack
  31191. */
  31192. class StringKeyframeTrack extends KeyframeTrack {
  31193. /**
  31194. * Constructs a new string keyframe track.
  31195. *
  31196. * This keyframe track type has no `interpolation` parameter because the
  31197. * interpolation is always discrete.
  31198. *
  31199. * @param {string} name - The keyframe track's name.
  31200. * @param {Array<number>} times - A list of keyframe times.
  31201. * @param {Array<string>} values - A list of keyframe values.
  31202. */
  31203. constructor( name, times, values ) {
  31204. super( name, times, values );
  31205. }
  31206. }
  31207. /**
  31208. * The value type name.
  31209. *
  31210. * @type {String}
  31211. * @default 'string'
  31212. */
  31213. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31214. /**
  31215. * The value buffer type of this keyframe track.
  31216. *
  31217. * @type {TypedArray|Array}
  31218. * @default Array.constructor
  31219. */
  31220. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31221. /**
  31222. * The default interpolation type of this keyframe track.
  31223. *
  31224. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31225. * @default InterpolateDiscrete
  31226. */
  31227. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31228. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31229. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31230. /**
  31231. * A track for vector keyframe values.
  31232. *
  31233. * @augments KeyframeTrack
  31234. */
  31235. class VectorKeyframeTrack extends KeyframeTrack {
  31236. /**
  31237. * Constructs a new vector keyframe track.
  31238. *
  31239. * @param {string} name - The keyframe track's name.
  31240. * @param {Array<number>} times - A list of keyframe times.
  31241. * @param {Array<number>} values - A list of keyframe values.
  31242. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31243. */
  31244. constructor( name, times, values, interpolation ) {
  31245. super( name, times, values, interpolation );
  31246. }
  31247. }
  31248. /**
  31249. * The value type name.
  31250. *
  31251. * @type {String}
  31252. * @default 'vector'
  31253. */
  31254. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31255. /**
  31256. * A reusable set of keyframe tracks which represent an animation.
  31257. */
  31258. class AnimationClip {
  31259. /**
  31260. * Constructs a new animation clip.
  31261. *
  31262. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31263. * use the static interface of this class for creating clips. In most cases though, animation clips
  31264. * will automatically be created by loaders when importing animated 3D assets.
  31265. *
  31266. * @param {string} [name=''] - The clip's name.
  31267. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31268. * the duration will be calculated from the passed keyframes.
  31269. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31270. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31271. * is blended/combined when two or more animations are simultaneously played.
  31272. */
  31273. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31274. /**
  31275. * The clip's name.
  31276. *
  31277. * @type {string}
  31278. */
  31279. this.name = name;
  31280. /**
  31281. * An array of keyframe tracks.
  31282. *
  31283. * @type {Array<KeyframeTrack>}
  31284. */
  31285. this.tracks = tracks;
  31286. /**
  31287. * The clip's duration in seconds.
  31288. *
  31289. * @type {number}
  31290. */
  31291. this.duration = duration;
  31292. /**
  31293. * Defines how the animation is blended/combined when two or more animations
  31294. * are simultaneously played.
  31295. *
  31296. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31297. */
  31298. this.blendMode = blendMode;
  31299. /**
  31300. * The UUID of the animation clip.
  31301. *
  31302. * @type {string}
  31303. * @readonly
  31304. */
  31305. this.uuid = generateUUID();
  31306. /**
  31307. * An object that can be used to store custom data about the animation clip.
  31308. * It should not hold references to functions as these will not be cloned.
  31309. *
  31310. * @type {Object}
  31311. */
  31312. this.userData = {};
  31313. // this means it should figure out its duration by scanning the tracks
  31314. if ( this.duration < 0 ) {
  31315. this.resetDuration();
  31316. }
  31317. }
  31318. /**
  31319. * Factory method for creating an animation clip from the given JSON.
  31320. *
  31321. * @static
  31322. * @param {Object} json - The serialized animation clip.
  31323. * @return {AnimationClip} The new animation clip.
  31324. */
  31325. static parse( json ) {
  31326. const tracks = [],
  31327. jsonTracks = json.tracks,
  31328. frameTime = 1.0 / ( json.fps || 1.0 );
  31329. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31330. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31331. }
  31332. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31333. clip.uuid = json.uuid;
  31334. clip.userData = JSON.parse( json.userData || '{}' );
  31335. return clip;
  31336. }
  31337. /**
  31338. * Serializes the given animation clip into JSON.
  31339. *
  31340. * @static
  31341. * @param {AnimationClip} clip - The animation clip to serialize.
  31342. * @return {Object} The JSON object.
  31343. */
  31344. static toJSON( clip ) {
  31345. const tracks = [],
  31346. clipTracks = clip.tracks;
  31347. const json = {
  31348. 'name': clip.name,
  31349. 'duration': clip.duration,
  31350. 'tracks': tracks,
  31351. 'uuid': clip.uuid,
  31352. 'blendMode': clip.blendMode,
  31353. 'userData': JSON.stringify( clip.userData ),
  31354. };
  31355. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31356. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31357. }
  31358. return json;
  31359. }
  31360. /**
  31361. * Returns a new animation clip from the passed morph targets array of a
  31362. * geometry, taking a name and the number of frames per second.
  31363. *
  31364. * Note: The fps parameter is required, but the animation speed can be
  31365. * overridden via {@link AnimationAction#setDuration}.
  31366. *
  31367. * @static
  31368. * @param {string} name - The name of the animation clip.
  31369. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31370. * @param {number} fps - The Frames-Per-Second value.
  31371. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31372. * @return {AnimationClip} The new animation clip.
  31373. */
  31374. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31375. const numMorphTargets = morphTargetSequence.length;
  31376. const tracks = [];
  31377. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31378. let times = [];
  31379. let values = [];
  31380. times.push(
  31381. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31382. i,
  31383. ( i + 1 ) % numMorphTargets );
  31384. values.push( 0, 1, 0 );
  31385. const order = getKeyframeOrder( times );
  31386. times = sortedArray( times, 1, order );
  31387. values = sortedArray( values, 1, order );
  31388. // if there is a key at the first frame, duplicate it as the
  31389. // last frame as well for perfect loop.
  31390. if ( ! noLoop && times[ 0 ] === 0 ) {
  31391. times.push( numMorphTargets );
  31392. values.push( values[ 0 ] );
  31393. }
  31394. tracks.push(
  31395. new NumberKeyframeTrack(
  31396. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31397. times, values
  31398. ).scale( 1.0 / fps ) );
  31399. }
  31400. return new this( name, -1, tracks );
  31401. }
  31402. /**
  31403. * Searches for an animation clip by name, taking as its first parameter
  31404. * either an array of clips, or a mesh or geometry that contains an
  31405. * array named "animations" property.
  31406. *
  31407. * @static
  31408. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31409. * @param {string} name - The name to search for.
  31410. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31411. */
  31412. static findByName( objectOrClipArray, name ) {
  31413. let clipArray = objectOrClipArray;
  31414. if ( ! Array.isArray( objectOrClipArray ) ) {
  31415. const o = objectOrClipArray;
  31416. clipArray = o.geometry && o.geometry.animations || o.animations;
  31417. }
  31418. for ( let i = 0; i < clipArray.length; i ++ ) {
  31419. if ( clipArray[ i ].name === name ) {
  31420. return clipArray[ i ];
  31421. }
  31422. }
  31423. return null;
  31424. }
  31425. /**
  31426. * Returns an array of new AnimationClips created from the morph target
  31427. * sequences of a geometry, trying to sort morph target names into
  31428. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31429. *
  31430. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31431. *
  31432. * @static
  31433. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31434. * @param {number} fps - The Frames-Per-Second value.
  31435. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31436. * @return {Array<AnimationClip>} An array of new animation clips.
  31437. */
  31438. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31439. const animationToMorphTargets = {};
  31440. // tested with https://regex101.com/ on trick sequences
  31441. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31442. const pattern = /^([\w-]*?)([\d]+)$/;
  31443. // sort morph target names into animation groups based
  31444. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31445. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31446. const morphTarget = morphTargets[ i ];
  31447. const parts = morphTarget.name.match( pattern );
  31448. if ( parts && parts.length > 1 ) {
  31449. const name = parts[ 1 ];
  31450. let animationMorphTargets = animationToMorphTargets[ name ];
  31451. if ( ! animationMorphTargets ) {
  31452. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31453. }
  31454. animationMorphTargets.push( morphTarget );
  31455. }
  31456. }
  31457. const clips = [];
  31458. for ( const name in animationToMorphTargets ) {
  31459. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31460. }
  31461. return clips;
  31462. }
  31463. /**
  31464. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31465. *
  31466. * @static
  31467. * @deprecated since r175.
  31468. * @param {Object} animation - A serialized animation clip as JSON.
  31469. * @param {Array<Bones>} bones - An array of bones.
  31470. * @return {?AnimationClip} The new animation clip.
  31471. */
  31472. static parseAnimation( animation, bones ) {
  31473. console.warn( 'THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31474. if ( ! animation ) {
  31475. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  31476. return null;
  31477. }
  31478. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31479. // only return track if there are actually keys.
  31480. if ( animationKeys.length !== 0 ) {
  31481. const times = [];
  31482. const values = [];
  31483. flattenJSON( animationKeys, times, values, propertyName );
  31484. // empty keys are filtered out, so check again
  31485. if ( times.length !== 0 ) {
  31486. destTracks.push( new trackType( trackName, times, values ) );
  31487. }
  31488. }
  31489. };
  31490. const tracks = [];
  31491. const clipName = animation.name || 'default';
  31492. const fps = animation.fps || 30;
  31493. const blendMode = animation.blendMode;
  31494. // automatic length determination in AnimationClip.
  31495. let duration = animation.length || -1;
  31496. const hierarchyTracks = animation.hierarchy || [];
  31497. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31498. const animationKeys = hierarchyTracks[ h ].keys;
  31499. // skip empty tracks
  31500. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31501. // process morph targets
  31502. if ( animationKeys[ 0 ].morphTargets ) {
  31503. // figure out all morph targets used in this track
  31504. const morphTargetNames = {};
  31505. let k;
  31506. for ( k = 0; k < animationKeys.length; k ++ ) {
  31507. if ( animationKeys[ k ].morphTargets ) {
  31508. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31509. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31510. }
  31511. }
  31512. }
  31513. // create a track for each morph target with all zero
  31514. // morphTargetInfluences except for the keys in which
  31515. // the morphTarget is named.
  31516. for ( const morphTargetName in morphTargetNames ) {
  31517. const times = [];
  31518. const values = [];
  31519. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31520. const animationKey = animationKeys[ k ];
  31521. times.push( animationKey.time );
  31522. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31523. }
  31524. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31525. }
  31526. duration = morphTargetNames.length * fps;
  31527. } else {
  31528. // ...assume skeletal animation
  31529. const boneName = '.bones[' + bones[ h ].name + ']';
  31530. addNonemptyTrack(
  31531. VectorKeyframeTrack, boneName + '.position',
  31532. animationKeys, 'pos', tracks );
  31533. addNonemptyTrack(
  31534. QuaternionKeyframeTrack, boneName + '.quaternion',
  31535. animationKeys, 'rot', tracks );
  31536. addNonemptyTrack(
  31537. VectorKeyframeTrack, boneName + '.scale',
  31538. animationKeys, 'scl', tracks );
  31539. }
  31540. }
  31541. if ( tracks.length === 0 ) {
  31542. return null;
  31543. }
  31544. const clip = new this( clipName, duration, tracks, blendMode );
  31545. return clip;
  31546. }
  31547. /**
  31548. * Sets the duration of this clip to the duration of its longest keyframe track.
  31549. *
  31550. * @return {AnimationClip} A reference to this animation clip.
  31551. */
  31552. resetDuration() {
  31553. const tracks = this.tracks;
  31554. let duration = 0;
  31555. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31556. const track = this.tracks[ i ];
  31557. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31558. }
  31559. this.duration = duration;
  31560. return this;
  31561. }
  31562. /**
  31563. * Trims all tracks to the clip's duration.
  31564. *
  31565. * @return {AnimationClip} A reference to this animation clip.
  31566. */
  31567. trim() {
  31568. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31569. this.tracks[ i ].trim( 0, this.duration );
  31570. }
  31571. return this;
  31572. }
  31573. /**
  31574. * Performs minimal validation on each track in the clip. Returns `true` if all
  31575. * tracks are valid.
  31576. *
  31577. * @return {boolean} Whether the clip's keyframes are valid or not.
  31578. */
  31579. validate() {
  31580. let valid = true;
  31581. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31582. valid = valid && this.tracks[ i ].validate();
  31583. }
  31584. return valid;
  31585. }
  31586. /**
  31587. * Optimizes each track by removing equivalent sequential keys (which are
  31588. * common in morph target sequences).
  31589. *
  31590. * @return {AnimationClip} A reference to this animation clip.
  31591. */
  31592. optimize() {
  31593. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31594. this.tracks[ i ].optimize();
  31595. }
  31596. return this;
  31597. }
  31598. /**
  31599. * Returns a new animation clip with copied values from this instance.
  31600. *
  31601. * @return {AnimationClip} A clone of this instance.
  31602. */
  31603. clone() {
  31604. const tracks = [];
  31605. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31606. tracks.push( this.tracks[ i ].clone() );
  31607. }
  31608. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31609. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31610. return clip;
  31611. }
  31612. /**
  31613. * Serializes this animation clip into JSON.
  31614. *
  31615. * @return {Object} The JSON object.
  31616. */
  31617. toJSON() {
  31618. return this.constructor.toJSON( this );
  31619. }
  31620. }
  31621. function getTrackTypeForValueTypeName( typeName ) {
  31622. switch ( typeName.toLowerCase() ) {
  31623. case 'scalar':
  31624. case 'double':
  31625. case 'float':
  31626. case 'number':
  31627. case 'integer':
  31628. return NumberKeyframeTrack;
  31629. case 'vector':
  31630. case 'vector2':
  31631. case 'vector3':
  31632. case 'vector4':
  31633. return VectorKeyframeTrack;
  31634. case 'color':
  31635. return ColorKeyframeTrack;
  31636. case 'quaternion':
  31637. return QuaternionKeyframeTrack;
  31638. case 'bool':
  31639. case 'boolean':
  31640. return BooleanKeyframeTrack;
  31641. case 'string':
  31642. return StringKeyframeTrack;
  31643. }
  31644. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31645. }
  31646. function parseKeyframeTrack( json ) {
  31647. if ( json.type === undefined ) {
  31648. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31649. }
  31650. const trackType = getTrackTypeForValueTypeName( json.type );
  31651. if ( json.times === undefined ) {
  31652. const times = [], values = [];
  31653. flattenJSON( json.keys, times, values, 'value' );
  31654. json.times = times;
  31655. json.values = values;
  31656. }
  31657. // derived classes can define a static parse method
  31658. if ( trackType.parse !== undefined ) {
  31659. return trackType.parse( json );
  31660. } else {
  31661. // by default, we assume a constructor compatible with the base
  31662. return new trackType( json.name, json.times, json.values, json.interpolation );
  31663. }
  31664. }
  31665. /**
  31666. * @class
  31667. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31668. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31669. * @hideconstructor
  31670. */
  31671. const Cache = {
  31672. /**
  31673. * Whether caching is enabled or not.
  31674. *
  31675. * @static
  31676. * @type {boolean}
  31677. * @default false
  31678. */
  31679. enabled: false,
  31680. /**
  31681. * A dictionary that holds cached files.
  31682. *
  31683. * @static
  31684. * @type {Object<string,Object>}
  31685. */
  31686. files: {},
  31687. /**
  31688. * Adds a cache entry with a key to reference the file. If this key already
  31689. * holds a file, it is overwritten.
  31690. *
  31691. * @static
  31692. * @param {string} key - The key to reference the cached file.
  31693. * @param {Object} file - The file to be cached.
  31694. */
  31695. add: function ( key, file ) {
  31696. if ( this.enabled === false ) return;
  31697. // console.log( 'THREE.Cache', 'Adding key:', key );
  31698. this.files[ key ] = file;
  31699. },
  31700. /**
  31701. * Gets the cached value for the given key.
  31702. *
  31703. * @static
  31704. * @param {string} key - The key to reference the cached file.
  31705. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31706. */
  31707. get: function ( key ) {
  31708. if ( this.enabled === false ) return;
  31709. // console.log( 'THREE.Cache', 'Checking key:', key );
  31710. return this.files[ key ];
  31711. },
  31712. /**
  31713. * Removes the cached file associated with the given key.
  31714. *
  31715. * @static
  31716. * @param {string} key - The key to reference the cached file.
  31717. */
  31718. remove: function ( key ) {
  31719. delete this.files[ key ];
  31720. },
  31721. /**
  31722. * Remove all values from the cache.
  31723. *
  31724. * @static
  31725. */
  31726. clear: function () {
  31727. this.files = {};
  31728. }
  31729. };
  31730. /**
  31731. * Handles and keeps track of loaded and pending data. A default global
  31732. * instance of this class is created and used by loaders if not supplied
  31733. * manually.
  31734. *
  31735. * In general that should be sufficient, however there are times when it can
  31736. * be useful to have separate loaders - for example if you want to show
  31737. * separate loading bars for objects and textures.
  31738. *
  31739. * ```js
  31740. * const manager = new THREE.LoadingManager();
  31741. * manager.onLoad = () => console.log( 'Loading complete!' );
  31742. *
  31743. * const loader1 = new OBJLoader( manager );
  31744. * const loader2 = new ColladaLoader( manager );
  31745. * ```
  31746. */
  31747. class LoadingManager {
  31748. /**
  31749. * Constructs a new loading manager.
  31750. *
  31751. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31752. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31753. * @param {Function} [onError] - Executes when an error occurs.
  31754. */
  31755. constructor( onLoad, onProgress, onError ) {
  31756. const scope = this;
  31757. let isLoading = false;
  31758. let itemsLoaded = 0;
  31759. let itemsTotal = 0;
  31760. let urlModifier = undefined;
  31761. const handlers = [];
  31762. // Refer to #5689 for the reason why we don't set .onStart
  31763. // in the constructor
  31764. /**
  31765. * Executes when an item starts loading.
  31766. *
  31767. * @type {Function|undefined}
  31768. * @default undefined
  31769. */
  31770. this.onStart = undefined;
  31771. /**
  31772. * Executes when all items have been loaded.
  31773. *
  31774. * @type {Function|undefined}
  31775. * @default undefined
  31776. */
  31777. this.onLoad = onLoad;
  31778. /**
  31779. * Executes when single items have been loaded.
  31780. *
  31781. * @type {Function|undefined}
  31782. * @default undefined
  31783. */
  31784. this.onProgress = onProgress;
  31785. /**
  31786. * Executes when an error occurs.
  31787. *
  31788. * @type {Function|undefined}
  31789. * @default undefined
  31790. */
  31791. this.onError = onError;
  31792. /**
  31793. * Used for aborting ongoing requests in loaders using this manager.
  31794. *
  31795. * @type {AbortController}
  31796. */
  31797. this.abortController = new AbortController();
  31798. /**
  31799. * This should be called by any loader using the manager when the loader
  31800. * starts loading an item.
  31801. *
  31802. * @param {string} url - The URL to load.
  31803. */
  31804. this.itemStart = function ( url ) {
  31805. itemsTotal ++;
  31806. if ( isLoading === false ) {
  31807. if ( scope.onStart !== undefined ) {
  31808. scope.onStart( url, itemsLoaded, itemsTotal );
  31809. }
  31810. }
  31811. isLoading = true;
  31812. };
  31813. /**
  31814. * This should be called by any loader using the manager when the loader
  31815. * ended loading an item.
  31816. *
  31817. * @param {string} url - The URL of the loaded item.
  31818. */
  31819. this.itemEnd = function ( url ) {
  31820. itemsLoaded ++;
  31821. if ( scope.onProgress !== undefined ) {
  31822. scope.onProgress( url, itemsLoaded, itemsTotal );
  31823. }
  31824. if ( itemsLoaded === itemsTotal ) {
  31825. isLoading = false;
  31826. if ( scope.onLoad !== undefined ) {
  31827. scope.onLoad();
  31828. }
  31829. }
  31830. };
  31831. /**
  31832. * This should be called by any loader using the manager when the loader
  31833. * encounters an error when loading an item.
  31834. *
  31835. * @param {string} url - The URL of the item that produces an error.
  31836. */
  31837. this.itemError = function ( url ) {
  31838. if ( scope.onError !== undefined ) {
  31839. scope.onError( url );
  31840. }
  31841. };
  31842. /**
  31843. * Given a URL, uses the URL modifier callback (if any) and returns a
  31844. * resolved URL. If no URL modifier is set, returns the original URL.
  31845. *
  31846. * @param {string} url - The URL to load.
  31847. * @return {string} The resolved URL.
  31848. */
  31849. this.resolveURL = function ( url ) {
  31850. if ( urlModifier ) {
  31851. return urlModifier( url );
  31852. }
  31853. return url;
  31854. };
  31855. /**
  31856. * If provided, the callback will be passed each resource URL before a
  31857. * request is sent. The callback may return the original URL, or a new URL to
  31858. * override loading behavior. This behavior can be used to load assets from
  31859. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31860. *
  31861. * ```js
  31862. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31863. *
  31864. * const manager = new THREE.LoadingManager();
  31865. *
  31866. * // Initialize loading manager with URL callback.
  31867. * const objectURLs = [];
  31868. * manager.setURLModifier( ( url ) => {
  31869. *
  31870. * url = URL.createObjectURL( blobs[ url ] );
  31871. * objectURLs.push( url );
  31872. * return url;
  31873. *
  31874. * } );
  31875. *
  31876. * // Load as usual, then revoke the blob URLs.
  31877. * const loader = new GLTFLoader( manager );
  31878. * loader.load( 'fish.gltf', (gltf) => {
  31879. *
  31880. * scene.add( gltf.scene );
  31881. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31882. *
  31883. * } );
  31884. * ```
  31885. *
  31886. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31887. * @return {LoadingManager} A reference to this loading manager.
  31888. */
  31889. this.setURLModifier = function ( transform ) {
  31890. urlModifier = transform;
  31891. return this;
  31892. };
  31893. /**
  31894. * Registers a loader with the given regular expression. Can be used to
  31895. * define what loader should be used in order to load specific files. A
  31896. * typical use case is to overwrite the default loader for textures.
  31897. *
  31898. * ```js
  31899. * // add handler for TGA textures
  31900. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31901. * ```
  31902. *
  31903. * @param {string} regex - A regular expression.
  31904. * @param {Loader} loader - A loader that should handle matched cases.
  31905. * @return {LoadingManager} A reference to this loading manager.
  31906. */
  31907. this.addHandler = function ( regex, loader ) {
  31908. handlers.push( regex, loader );
  31909. return this;
  31910. };
  31911. /**
  31912. * Removes the loader for the given regular expression.
  31913. *
  31914. * @param {string} regex - A regular expression.
  31915. * @return {LoadingManager} A reference to this loading manager.
  31916. */
  31917. this.removeHandler = function ( regex ) {
  31918. const index = handlers.indexOf( regex );
  31919. if ( index !== -1 ) {
  31920. handlers.splice( index, 2 );
  31921. }
  31922. return this;
  31923. };
  31924. /**
  31925. * Can be used to retrieve the registered loader for the given file path.
  31926. *
  31927. * @param {string} file - The file path.
  31928. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31929. */
  31930. this.getHandler = function ( file ) {
  31931. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31932. const regex = handlers[ i ];
  31933. const loader = handlers[ i + 1 ];
  31934. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31935. if ( regex.test( file ) ) {
  31936. return loader;
  31937. }
  31938. }
  31939. return null;
  31940. };
  31941. /**
  31942. * Can be used to abort ongoing loading requests in loaders using this manager.
  31943. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  31944. * is supported in the browser.
  31945. *
  31946. * @return {LoadingManager} A reference to this loading manager.
  31947. */
  31948. this.abort = function () {
  31949. this.abortController.abort();
  31950. this.abortController = new AbortController();
  31951. return this;
  31952. };
  31953. }
  31954. }
  31955. /**
  31956. * The global default loading manager.
  31957. *
  31958. * @constant
  31959. * @type {LoadingManager}
  31960. */
  31961. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  31962. /**
  31963. * Abstract base class for loaders.
  31964. *
  31965. * @abstract
  31966. */
  31967. class Loader {
  31968. /**
  31969. * Constructs a new loader.
  31970. *
  31971. * @param {LoadingManager} [manager] - The loading manager.
  31972. */
  31973. constructor( manager ) {
  31974. /**
  31975. * The loading manager.
  31976. *
  31977. * @type {LoadingManager}
  31978. * @default DefaultLoadingManager
  31979. */
  31980. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  31981. /**
  31982. * The crossOrigin string to implement CORS for loading the url from a
  31983. * different domain that allows CORS.
  31984. *
  31985. * @type {string}
  31986. * @default 'anonymous'
  31987. */
  31988. this.crossOrigin = 'anonymous';
  31989. /**
  31990. * Whether the XMLHttpRequest uses credentials.
  31991. *
  31992. * @type {boolean}
  31993. * @default false
  31994. */
  31995. this.withCredentials = false;
  31996. /**
  31997. * The base path from which the asset will be loaded.
  31998. *
  31999. * @type {string}
  32000. */
  32001. this.path = '';
  32002. /**
  32003. * The base path from which additional resources like textures will be loaded.
  32004. *
  32005. * @type {string}
  32006. */
  32007. this.resourcePath = '';
  32008. /**
  32009. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  32010. * used in HTTP request.
  32011. *
  32012. * @type {Object<string, any>}
  32013. */
  32014. this.requestHeader = {};
  32015. }
  32016. /**
  32017. * This method needs to be implemented by all concrete loaders. It holds the
  32018. * logic for loading assets from the backend.
  32019. *
  32020. * @abstract
  32021. * @param {string} url - The path/URL of the file to be loaded.
  32022. * @param {Function} onLoad - Executed when the loading process has been finished.
  32023. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32024. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32025. */
  32026. load( /* url, onLoad, onProgress, onError */ ) {}
  32027. /**
  32028. * A async version of {@link Loader#load}.
  32029. *
  32030. * @param {string} url - The path/URL of the file to be loaded.
  32031. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32032. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32033. */
  32034. loadAsync( url, onProgress ) {
  32035. const scope = this;
  32036. return new Promise( function ( resolve, reject ) {
  32037. scope.load( url, resolve, onProgress, reject );
  32038. } );
  32039. }
  32040. /**
  32041. * This method needs to be implemented by all concrete loaders. It holds the
  32042. * logic for parsing the asset into three.js entities.
  32043. *
  32044. * @abstract
  32045. * @param {any} data - The data to parse.
  32046. */
  32047. parse( /* data */ ) {}
  32048. /**
  32049. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32050. * from a different domain that allows CORS.
  32051. *
  32052. * @param {string} crossOrigin - The `crossOrigin` value.
  32053. * @return {Loader} A reference to this instance.
  32054. */
  32055. setCrossOrigin( crossOrigin ) {
  32056. this.crossOrigin = crossOrigin;
  32057. return this;
  32058. }
  32059. /**
  32060. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32061. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  32062. *
  32063. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32064. *
  32065. * @param {boolean} value - The `withCredentials` value.
  32066. * @return {Loader} A reference to this instance.
  32067. */
  32068. setWithCredentials( value ) {
  32069. this.withCredentials = value;
  32070. return this;
  32071. }
  32072. /**
  32073. * Sets the base path for the asset.
  32074. *
  32075. * @param {string} path - The base path.
  32076. * @return {Loader} A reference to this instance.
  32077. */
  32078. setPath( path ) {
  32079. this.path = path;
  32080. return this;
  32081. }
  32082. /**
  32083. * Sets the base path for dependent resources like textures.
  32084. *
  32085. * @param {string} resourcePath - The resource path.
  32086. * @return {Loader} A reference to this instance.
  32087. */
  32088. setResourcePath( resourcePath ) {
  32089. this.resourcePath = resourcePath;
  32090. return this;
  32091. }
  32092. /**
  32093. * Sets the given request header.
  32094. *
  32095. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  32096. * for configuring the HTTP request.
  32097. * @return {Loader} A reference to this instance.
  32098. */
  32099. setRequestHeader( requestHeader ) {
  32100. this.requestHeader = requestHeader;
  32101. return this;
  32102. }
  32103. /**
  32104. * This method can be implemented in loaders for aborting ongoing requests.
  32105. *
  32106. * @abstract
  32107. * @return {Loader} A reference to this instance.
  32108. */
  32109. abort() {
  32110. return this;
  32111. }
  32112. }
  32113. /**
  32114. * Callback for onProgress in loaders.
  32115. *
  32116. * @callback onProgressCallback
  32117. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32118. */
  32119. /**
  32120. * Callback for onError in loaders.
  32121. *
  32122. * @callback onErrorCallback
  32123. * @param {Error} error - The error which occurred during the loading process.
  32124. */
  32125. /**
  32126. * The default material name that is used by loaders
  32127. * when creating materials for loaded 3D objects.
  32128. *
  32129. * Note: Not all loaders might honor this setting.
  32130. *
  32131. * @static
  32132. * @type {string}
  32133. * @default '__DEFAULT'
  32134. */
  32135. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32136. const loading = {};
  32137. class HttpError extends Error {
  32138. constructor( message, response ) {
  32139. super( message );
  32140. this.response = response;
  32141. }
  32142. }
  32143. /**
  32144. * A low level class for loading resources with the Fetch API, used internally by
  32145. * most loaders. It can also be used directly to load any file type that does
  32146. * not have a loader.
  32147. *
  32148. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32149. * once to your application.
  32150. *
  32151. * ```js
  32152. * const loader = new THREE.FileLoader();
  32153. * const data = await loader.loadAsync( 'example.txt' );
  32154. * ```
  32155. *
  32156. * @augments Loader
  32157. */
  32158. class FileLoader extends Loader {
  32159. /**
  32160. * Constructs a new file loader.
  32161. *
  32162. * @param {LoadingManager} [manager] - The loading manager.
  32163. */
  32164. constructor( manager ) {
  32165. super( manager );
  32166. /**
  32167. * The expected mime type. Valid values can be found
  32168. * [here]{@link hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype}
  32169. *
  32170. * @type {string}
  32171. */
  32172. this.mimeType = '';
  32173. /**
  32174. * The expected response type.
  32175. *
  32176. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32177. * @default ''
  32178. */
  32179. this.responseType = '';
  32180. /**
  32181. * Used for aborting requests.
  32182. *
  32183. * @private
  32184. * @type {AbortController}
  32185. */
  32186. this._abortController = new AbortController();
  32187. }
  32188. /**
  32189. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32190. *
  32191. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32192. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32193. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32194. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32195. * @return {any|undefined} The cached resource if available.
  32196. */
  32197. load( url, onLoad, onProgress, onError ) {
  32198. if ( url === undefined ) url = '';
  32199. if ( this.path !== undefined ) url = this.path + url;
  32200. url = this.manager.resolveURL( url );
  32201. const cached = Cache.get( `file:${url}` );
  32202. if ( cached !== undefined ) {
  32203. this.manager.itemStart( url );
  32204. setTimeout( () => {
  32205. if ( onLoad ) onLoad( cached );
  32206. this.manager.itemEnd( url );
  32207. }, 0 );
  32208. return cached;
  32209. }
  32210. // Check if request is duplicate
  32211. if ( loading[ url ] !== undefined ) {
  32212. loading[ url ].push( {
  32213. onLoad: onLoad,
  32214. onProgress: onProgress,
  32215. onError: onError
  32216. } );
  32217. return;
  32218. }
  32219. // Initialise array for duplicate requests
  32220. loading[ url ] = [];
  32221. loading[ url ].push( {
  32222. onLoad: onLoad,
  32223. onProgress: onProgress,
  32224. onError: onError,
  32225. } );
  32226. // create request
  32227. const req = new Request( url, {
  32228. headers: new Headers( this.requestHeader ),
  32229. credentials: this.withCredentials ? 'include' : 'same-origin',
  32230. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32231. } );
  32232. // record states ( avoid data race )
  32233. const mimeType = this.mimeType;
  32234. const responseType = this.responseType;
  32235. // start the fetch
  32236. fetch( req )
  32237. .then( response => {
  32238. if ( response.status === 200 || response.status === 0 ) {
  32239. // Some browsers return HTTP Status 0 when using non-http protocol
  32240. // e.g. 'file://' or 'data://'. Handle as success.
  32241. if ( response.status === 0 ) {
  32242. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  32243. }
  32244. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32245. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32246. return response;
  32247. }
  32248. const callbacks = loading[ url ];
  32249. const reader = response.body.getReader();
  32250. // Nginx needs X-File-Size check
  32251. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32252. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32253. const total = contentLength ? parseInt( contentLength ) : 0;
  32254. const lengthComputable = total !== 0;
  32255. let loaded = 0;
  32256. // periodically read data into the new stream tracking while download progress
  32257. const stream = new ReadableStream( {
  32258. start( controller ) {
  32259. readData();
  32260. function readData() {
  32261. reader.read().then( ( { done, value } ) => {
  32262. if ( done ) {
  32263. controller.close();
  32264. } else {
  32265. loaded += value.byteLength;
  32266. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32267. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32268. const callback = callbacks[ i ];
  32269. if ( callback.onProgress ) callback.onProgress( event );
  32270. }
  32271. controller.enqueue( value );
  32272. readData();
  32273. }
  32274. }, ( e ) => {
  32275. controller.error( e );
  32276. } );
  32277. }
  32278. }
  32279. } );
  32280. return new Response( stream );
  32281. } else {
  32282. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32283. }
  32284. } )
  32285. .then( response => {
  32286. switch ( responseType ) {
  32287. case 'arraybuffer':
  32288. return response.arrayBuffer();
  32289. case 'blob':
  32290. return response.blob();
  32291. case 'document':
  32292. return response.text()
  32293. .then( text => {
  32294. const parser = new DOMParser();
  32295. return parser.parseFromString( text, mimeType );
  32296. } );
  32297. case 'json':
  32298. return response.json();
  32299. default:
  32300. if ( mimeType === '' ) {
  32301. return response.text();
  32302. } else {
  32303. // sniff encoding
  32304. const re = /charset="?([^;"\s]*)"?/i;
  32305. const exec = re.exec( mimeType );
  32306. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32307. const decoder = new TextDecoder( label );
  32308. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32309. }
  32310. }
  32311. } )
  32312. .then( data => {
  32313. // Add to cache only on HTTP success, so that we do not cache
  32314. // error response bodies as proper responses to requests.
  32315. Cache.add( `file:${url}`, data );
  32316. const callbacks = loading[ url ];
  32317. delete loading[ url ];
  32318. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32319. const callback = callbacks[ i ];
  32320. if ( callback.onLoad ) callback.onLoad( data );
  32321. }
  32322. } )
  32323. .catch( err => {
  32324. // Abort errors and other errors are handled the same
  32325. const callbacks = loading[ url ];
  32326. if ( callbacks === undefined ) {
  32327. // When onLoad was called and url was deleted in `loading`
  32328. this.manager.itemError( url );
  32329. throw err;
  32330. }
  32331. delete loading[ url ];
  32332. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32333. const callback = callbacks[ i ];
  32334. if ( callback.onError ) callback.onError( err );
  32335. }
  32336. this.manager.itemError( url );
  32337. } )
  32338. .finally( () => {
  32339. this.manager.itemEnd( url );
  32340. } );
  32341. this.manager.itemStart( url );
  32342. }
  32343. /**
  32344. * Sets the expected response type.
  32345. *
  32346. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32347. * @return {FileLoader} A reference to this file loader.
  32348. */
  32349. setResponseType( value ) {
  32350. this.responseType = value;
  32351. return this;
  32352. }
  32353. /**
  32354. * Sets the expected mime type of the loaded file.
  32355. *
  32356. * @param {string} value - The mime type.
  32357. * @return {FileLoader} A reference to this file loader.
  32358. */
  32359. setMimeType( value ) {
  32360. this.mimeType = value;
  32361. return this;
  32362. }
  32363. /**
  32364. * Aborts ongoing fetch requests.
  32365. *
  32366. * @return {FileLoader} A reference to this instance.
  32367. */
  32368. abort() {
  32369. this._abortController.abort();
  32370. this._abortController = new AbortController();
  32371. return this;
  32372. }
  32373. }
  32374. /**
  32375. * Class for loading animation clips in the JSON format. The files are internally
  32376. * loaded via {@link FileLoader}.
  32377. *
  32378. * ```js
  32379. * const loader = new THREE.AnimationLoader();
  32380. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32381. * ```
  32382. *
  32383. * @augments Loader
  32384. */
  32385. class AnimationLoader extends Loader {
  32386. /**
  32387. * Constructs a new animation loader.
  32388. *
  32389. * @param {LoadingManager} [manager] - The loading manager.
  32390. */
  32391. constructor( manager ) {
  32392. super( manager );
  32393. }
  32394. /**
  32395. * Starts loading from the given URL and pass the loaded animations as an array
  32396. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32397. *
  32398. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32399. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32400. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32401. * @param {onErrorCallback} onError - Executed when errors occur.
  32402. */
  32403. load( url, onLoad, onProgress, onError ) {
  32404. const scope = this;
  32405. const loader = new FileLoader( this.manager );
  32406. loader.setPath( this.path );
  32407. loader.setRequestHeader( this.requestHeader );
  32408. loader.setWithCredentials( this.withCredentials );
  32409. loader.load( url, function ( text ) {
  32410. try {
  32411. onLoad( scope.parse( JSON.parse( text ) ) );
  32412. } catch ( e ) {
  32413. if ( onError ) {
  32414. onError( e );
  32415. } else {
  32416. console.error( e );
  32417. }
  32418. scope.manager.itemError( url );
  32419. }
  32420. }, onProgress, onError );
  32421. }
  32422. /**
  32423. * Parses the given JSON object and returns an array of animation clips.
  32424. *
  32425. * @param {Object} json - The serialized animation clips.
  32426. * @return {Array<AnimationClip>} The parsed animation clips.
  32427. */
  32428. parse( json ) {
  32429. const animations = [];
  32430. for ( let i = 0; i < json.length; i ++ ) {
  32431. const clip = AnimationClip.parse( json[ i ] );
  32432. animations.push( clip );
  32433. }
  32434. return animations;
  32435. }
  32436. }
  32437. /**
  32438. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32439. * Textures are internally loaded via {@link FileLoader}.
  32440. *
  32441. * Derived classes have to implement the `parse()` method which holds the parsing
  32442. * for the respective format.
  32443. *
  32444. * @abstract
  32445. * @augments Loader
  32446. */
  32447. class CompressedTextureLoader extends Loader {
  32448. /**
  32449. * Constructs a new compressed texture loader.
  32450. *
  32451. * @param {LoadingManager} [manager] - The loading manager.
  32452. */
  32453. constructor( manager ) {
  32454. super( manager );
  32455. }
  32456. /**
  32457. * Starts loading from the given URL and passes the loaded compressed texture
  32458. * to the `onLoad()` callback. The method also returns a new texture object which can
  32459. * directly be used for material creation. If you do it this way, the texture
  32460. * may pop up in your scene once the respective loading process is finished.
  32461. *
  32462. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32463. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32464. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32465. * @param {onErrorCallback} onError - Executed when errors occur.
  32466. * @return {CompressedTexture} The compressed texture.
  32467. */
  32468. load( url, onLoad, onProgress, onError ) {
  32469. const scope = this;
  32470. const images = [];
  32471. const texture = new CompressedTexture();
  32472. const loader = new FileLoader( this.manager );
  32473. loader.setPath( this.path );
  32474. loader.setResponseType( 'arraybuffer' );
  32475. loader.setRequestHeader( this.requestHeader );
  32476. loader.setWithCredentials( scope.withCredentials );
  32477. let loaded = 0;
  32478. function loadTexture( i ) {
  32479. loader.load( url[ i ], function ( buffer ) {
  32480. const texDatas = scope.parse( buffer, true );
  32481. images[ i ] = {
  32482. width: texDatas.width,
  32483. height: texDatas.height,
  32484. format: texDatas.format,
  32485. mipmaps: texDatas.mipmaps
  32486. };
  32487. loaded += 1;
  32488. if ( loaded === 6 ) {
  32489. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32490. texture.image = images;
  32491. texture.format = texDatas.format;
  32492. texture.needsUpdate = true;
  32493. if ( onLoad ) onLoad( texture );
  32494. }
  32495. }, onProgress, onError );
  32496. }
  32497. if ( Array.isArray( url ) ) {
  32498. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32499. loadTexture( i );
  32500. }
  32501. } else {
  32502. // compressed cubemap texture stored in a single DDS file
  32503. loader.load( url, function ( buffer ) {
  32504. const texDatas = scope.parse( buffer, true );
  32505. if ( texDatas.isCubemap ) {
  32506. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32507. for ( let f = 0; f < faces; f ++ ) {
  32508. images[ f ] = { mipmaps: [] };
  32509. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32510. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32511. images[ f ].format = texDatas.format;
  32512. images[ f ].width = texDatas.width;
  32513. images[ f ].height = texDatas.height;
  32514. }
  32515. }
  32516. texture.image = images;
  32517. } else {
  32518. texture.image.width = texDatas.width;
  32519. texture.image.height = texDatas.height;
  32520. texture.mipmaps = texDatas.mipmaps;
  32521. }
  32522. if ( texDatas.mipmapCount === 1 ) {
  32523. texture.minFilter = LinearFilter;
  32524. }
  32525. texture.format = texDatas.format;
  32526. texture.needsUpdate = true;
  32527. if ( onLoad ) onLoad( texture );
  32528. }, onProgress, onError );
  32529. }
  32530. return texture;
  32531. }
  32532. }
  32533. const _loading = new WeakMap();
  32534. /**
  32535. * A loader for loading images. The class loads images with the HTML `Image` API.
  32536. *
  32537. * ```js
  32538. * const loader = new THREE.ImageLoader();
  32539. * const image = await loader.loadAsync( 'image.png' );
  32540. * ```
  32541. * Please note that `ImageLoader` has dropped support for progress
  32542. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32543. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}.
  32544. *
  32545. * @augments Loader
  32546. */
  32547. class ImageLoader extends Loader {
  32548. /**
  32549. * Constructs a new image loader.
  32550. *
  32551. * @param {LoadingManager} [manager] - The loading manager.
  32552. */
  32553. constructor( manager ) {
  32554. super( manager );
  32555. }
  32556. /**
  32557. * Starts loading from the given URL and passes the loaded image
  32558. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32559. * directly be used for texture creation. If you do it this way, the texture
  32560. * may pop up in your scene once the respective loading process is finished.
  32561. *
  32562. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32563. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32564. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32565. * @param {onErrorCallback} onError - Executed when errors occur.
  32566. * @return {Image} The image.
  32567. */
  32568. load( url, onLoad, onProgress, onError ) {
  32569. if ( this.path !== undefined ) url = this.path + url;
  32570. url = this.manager.resolveURL( url );
  32571. const scope = this;
  32572. const cached = Cache.get( `image:${url}` );
  32573. if ( cached !== undefined ) {
  32574. if ( cached.complete === true ) {
  32575. scope.manager.itemStart( url );
  32576. setTimeout( function () {
  32577. if ( onLoad ) onLoad( cached );
  32578. scope.manager.itemEnd( url );
  32579. }, 0 );
  32580. } else {
  32581. let arr = _loading.get( cached );
  32582. if ( arr === undefined ) {
  32583. arr = [];
  32584. _loading.set( cached, arr );
  32585. }
  32586. arr.push( { onLoad, onError } );
  32587. }
  32588. return cached;
  32589. }
  32590. const image = createElementNS( 'img' );
  32591. function onImageLoad() {
  32592. removeEventListeners();
  32593. if ( onLoad ) onLoad( this );
  32594. //
  32595. const callbacks = _loading.get( this ) || [];
  32596. for ( let i = 0; i < callbacks.length; i ++ ) {
  32597. const callback = callbacks[ i ];
  32598. if ( callback.onLoad ) callback.onLoad( this );
  32599. }
  32600. _loading.delete( this );
  32601. scope.manager.itemEnd( url );
  32602. }
  32603. function onImageError( event ) {
  32604. removeEventListeners();
  32605. if ( onError ) onError( event );
  32606. Cache.remove( `image:${url}` );
  32607. //
  32608. const callbacks = _loading.get( this ) || [];
  32609. for ( let i = 0; i < callbacks.length; i ++ ) {
  32610. const callback = callbacks[ i ];
  32611. if ( callback.onError ) callback.onError( event );
  32612. }
  32613. _loading.delete( this );
  32614. scope.manager.itemError( url );
  32615. scope.manager.itemEnd( url );
  32616. }
  32617. function removeEventListeners() {
  32618. image.removeEventListener( 'load', onImageLoad, false );
  32619. image.removeEventListener( 'error', onImageError, false );
  32620. }
  32621. image.addEventListener( 'load', onImageLoad, false );
  32622. image.addEventListener( 'error', onImageError, false );
  32623. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32624. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32625. }
  32626. Cache.add( `image:${url}`, image );
  32627. scope.manager.itemStart( url );
  32628. image.src = url;
  32629. return image;
  32630. }
  32631. }
  32632. /**
  32633. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32634. *
  32635. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32636. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32637. * like vertical and horizontal cross, column and row layouts are not supported.
  32638. *
  32639. * Note that, by convention, cube maps are specified in a coordinate system
  32640. * in which positive-x is to the right when looking up the positive-z axis --
  32641. * in other words, using a left-handed coordinate system. Since three.js uses
  32642. * a right-handed coordinate system, environment maps used in three.js will
  32643. * have pos-x and neg-x swapped.
  32644. *
  32645. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32646. * is set to `SRGBColorSpace` by default.
  32647. *
  32648. * ```js
  32649. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32650. * const cubeTexture = await loader.loadAsync( [
  32651. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32652. * ] );
  32653. * scene.background = cubeTexture;
  32654. * ```
  32655. *
  32656. * @augments Loader
  32657. */
  32658. class CubeTextureLoader extends Loader {
  32659. /**
  32660. * Constructs a new cube texture loader.
  32661. *
  32662. * @param {LoadingManager} [manager] - The loading manager.
  32663. */
  32664. constructor( manager ) {
  32665. super( manager );
  32666. }
  32667. /**
  32668. * Starts loading from the given URL and pass the fully loaded cube texture
  32669. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32670. * directly be used for material creation. If you do it this way, the cube texture
  32671. * may pop up in your scene once the respective loading process is finished.
  32672. *
  32673. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32674. * cube texture. The urls should be specified in the following order: pos-x,
  32675. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32676. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32677. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32678. * @param {onErrorCallback} onError - Executed when errors occur.
  32679. * @return {CubeTexture} The cube texture.
  32680. */
  32681. load( urls, onLoad, onProgress, onError ) {
  32682. const texture = new CubeTexture();
  32683. texture.colorSpace = SRGBColorSpace;
  32684. const loader = new ImageLoader( this.manager );
  32685. loader.setCrossOrigin( this.crossOrigin );
  32686. loader.setPath( this.path );
  32687. let loaded = 0;
  32688. function loadTexture( i ) {
  32689. loader.load( urls[ i ], function ( image ) {
  32690. texture.images[ i ] = image;
  32691. loaded ++;
  32692. if ( loaded === 6 ) {
  32693. texture.needsUpdate = true;
  32694. if ( onLoad ) onLoad( texture );
  32695. }
  32696. }, undefined, onError );
  32697. }
  32698. for ( let i = 0; i < urls.length; ++ i ) {
  32699. loadTexture( i );
  32700. }
  32701. return texture;
  32702. }
  32703. }
  32704. /**
  32705. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32706. * Textures are internally loaded via {@link FileLoader}.
  32707. *
  32708. * Derived classes have to implement the `parse()` method which holds the parsing
  32709. * for the respective format.
  32710. *
  32711. * @abstract
  32712. * @augments Loader
  32713. */
  32714. class DataTextureLoader extends Loader {
  32715. /**
  32716. * Constructs a new data texture loader.
  32717. *
  32718. * @param {LoadingManager} [manager] - The loading manager.
  32719. */
  32720. constructor( manager ) {
  32721. super( manager );
  32722. }
  32723. /**
  32724. * Starts loading from the given URL and passes the loaded data texture
  32725. * to the `onLoad()` callback. The method also returns a new texture object which can
  32726. * directly be used for material creation. If you do it this way, the texture
  32727. * may pop up in your scene once the respective loading process is finished.
  32728. *
  32729. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32730. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32731. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32732. * @param {onErrorCallback} onError - Executed when errors occur.
  32733. * @return {DataTexture} The data texture.
  32734. */
  32735. load( url, onLoad, onProgress, onError ) {
  32736. const scope = this;
  32737. const texture = new DataTexture();
  32738. const loader = new FileLoader( this.manager );
  32739. loader.setResponseType( 'arraybuffer' );
  32740. loader.setRequestHeader( this.requestHeader );
  32741. loader.setPath( this.path );
  32742. loader.setWithCredentials( scope.withCredentials );
  32743. loader.load( url, function ( buffer ) {
  32744. let texData;
  32745. try {
  32746. texData = scope.parse( buffer );
  32747. } catch ( error ) {
  32748. if ( onError !== undefined ) {
  32749. onError( error );
  32750. } else {
  32751. console.error( error );
  32752. return;
  32753. }
  32754. }
  32755. if ( texData.image !== undefined ) {
  32756. texture.image = texData.image;
  32757. } else if ( texData.data !== undefined ) {
  32758. texture.image.width = texData.width;
  32759. texture.image.height = texData.height;
  32760. texture.image.data = texData.data;
  32761. }
  32762. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32763. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32764. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32765. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32766. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32767. if ( texData.colorSpace !== undefined ) {
  32768. texture.colorSpace = texData.colorSpace;
  32769. }
  32770. if ( texData.flipY !== undefined ) {
  32771. texture.flipY = texData.flipY;
  32772. }
  32773. if ( texData.format !== undefined ) {
  32774. texture.format = texData.format;
  32775. }
  32776. if ( texData.type !== undefined ) {
  32777. texture.type = texData.type;
  32778. }
  32779. if ( texData.mipmaps !== undefined ) {
  32780. texture.mipmaps = texData.mipmaps;
  32781. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32782. }
  32783. if ( texData.mipmapCount === 1 ) {
  32784. texture.minFilter = LinearFilter;
  32785. }
  32786. if ( texData.generateMipmaps !== undefined ) {
  32787. texture.generateMipmaps = texData.generateMipmaps;
  32788. }
  32789. texture.needsUpdate = true;
  32790. if ( onLoad ) onLoad( texture, texData );
  32791. }, onProgress, onError );
  32792. return texture;
  32793. }
  32794. }
  32795. /**
  32796. * Class for loading textures. Images are internally
  32797. * loaded via {@link ImageLoader}.
  32798. *
  32799. * ```js
  32800. * const loader = new THREE.TextureLoader();
  32801. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32802. *
  32803. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32804. * ```
  32805. * Please note that `TextureLoader` has dropped support for progress
  32806. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32807. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}.
  32808. *
  32809. * @augments Loader
  32810. */
  32811. class TextureLoader extends Loader {
  32812. /**
  32813. * Constructs a new texture loader.
  32814. *
  32815. * @param {LoadingManager} [manager] - The loading manager.
  32816. */
  32817. constructor( manager ) {
  32818. super( manager );
  32819. }
  32820. /**
  32821. * Starts loading from the given URL and pass the fully loaded texture
  32822. * to the `onLoad()` callback. The method also returns a new texture object which can
  32823. * directly be used for material creation. If you do it this way, the texture
  32824. * may pop up in your scene once the respective loading process is finished.
  32825. *
  32826. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32827. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32828. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32829. * @param {onErrorCallback} onError - Executed when errors occur.
  32830. * @return {Texture} The texture.
  32831. */
  32832. load( url, onLoad, onProgress, onError ) {
  32833. const texture = new Texture();
  32834. const loader = new ImageLoader( this.manager );
  32835. loader.setCrossOrigin( this.crossOrigin );
  32836. loader.setPath( this.path );
  32837. loader.load( url, function ( image ) {
  32838. texture.image = image;
  32839. texture.needsUpdate = true;
  32840. if ( onLoad !== undefined ) {
  32841. onLoad( texture );
  32842. }
  32843. }, onProgress, onError );
  32844. return texture;
  32845. }
  32846. }
  32847. /**
  32848. * Abstract base class for lights - all other light types inherit the
  32849. * properties and methods described here.
  32850. *
  32851. * @abstract
  32852. * @augments Object3D
  32853. */
  32854. class Light extends Object3D {
  32855. /**
  32856. * Constructs a new light.
  32857. *
  32858. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32859. * @param {number} [intensity=1] - The light's strength/intensity.
  32860. */
  32861. constructor( color, intensity = 1 ) {
  32862. super();
  32863. /**
  32864. * This flag can be used for type testing.
  32865. *
  32866. * @type {boolean}
  32867. * @readonly
  32868. * @default true
  32869. */
  32870. this.isLight = true;
  32871. this.type = 'Light';
  32872. /**
  32873. * The light's color.
  32874. *
  32875. * @type {Color}
  32876. */
  32877. this.color = new Color( color );
  32878. /**
  32879. * The light's intensity.
  32880. *
  32881. * @type {number}
  32882. * @default 1
  32883. */
  32884. this.intensity = intensity;
  32885. }
  32886. /**
  32887. * Frees the GPU-related resources allocated by this instance. Call this
  32888. * method whenever this instance is no longer used in your app.
  32889. */
  32890. dispose() {
  32891. // Empty here in base class; some subclasses override.
  32892. }
  32893. copy( source, recursive ) {
  32894. super.copy( source, recursive );
  32895. this.color.copy( source.color );
  32896. this.intensity = source.intensity;
  32897. return this;
  32898. }
  32899. toJSON( meta ) {
  32900. const data = super.toJSON( meta );
  32901. data.object.color = this.color.getHex();
  32902. data.object.intensity = this.intensity;
  32903. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  32904. if ( this.distance !== undefined ) data.object.distance = this.distance;
  32905. if ( this.angle !== undefined ) data.object.angle = this.angle;
  32906. if ( this.decay !== undefined ) data.object.decay = this.decay;
  32907. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  32908. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  32909. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  32910. return data;
  32911. }
  32912. }
  32913. /**
  32914. * A light source positioned directly above the scene, with color fading from
  32915. * the sky color to the ground color.
  32916. *
  32917. * This light cannot be used to cast shadows.
  32918. *
  32919. * ```js
  32920. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32921. * scene.add( light );
  32922. * ```
  32923. *
  32924. * @augments Light
  32925. */
  32926. class HemisphereLight extends Light {
  32927. /**
  32928. * Constructs a new hemisphere light.
  32929. *
  32930. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32931. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32932. * @param {number} [intensity=1] - The light's strength/intensity.
  32933. */
  32934. constructor( skyColor, groundColor, intensity ) {
  32935. super( skyColor, intensity );
  32936. /**
  32937. * This flag can be used for type testing.
  32938. *
  32939. * @type {boolean}
  32940. * @readonly
  32941. * @default true
  32942. */
  32943. this.isHemisphereLight = true;
  32944. this.type = 'HemisphereLight';
  32945. this.position.copy( Object3D.DEFAULT_UP );
  32946. this.updateMatrix();
  32947. /**
  32948. * The light's ground color.
  32949. *
  32950. * @type {Color}
  32951. */
  32952. this.groundColor = new Color( groundColor );
  32953. }
  32954. copy( source, recursive ) {
  32955. super.copy( source, recursive );
  32956. this.groundColor.copy( source.groundColor );
  32957. return this;
  32958. }
  32959. }
  32960. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32961. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  32962. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  32963. /**
  32964. * Abstract base class for light shadow classes. These classes
  32965. * represent the shadow configuration for different light types.
  32966. *
  32967. * @abstract
  32968. */
  32969. class LightShadow {
  32970. /**
  32971. * Constructs a new light shadow.
  32972. *
  32973. * @param {Camera} camera - The light's view of the world.
  32974. */
  32975. constructor( camera ) {
  32976. /**
  32977. * The light's view of the world.
  32978. *
  32979. * @type {Camera}
  32980. */
  32981. this.camera = camera;
  32982. /**
  32983. * The intensity of the shadow. The default is `1`.
  32984. * Valid values are in the range `[0, 1]`.
  32985. *
  32986. * @type {number}
  32987. * @default 1
  32988. */
  32989. this.intensity = 1;
  32990. /**
  32991. * Shadow map bias, how much to add or subtract from the normalized depth
  32992. * when deciding whether a surface is in shadow.
  32993. *
  32994. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  32995. * may help reduce artifacts in shadows.
  32996. *
  32997. * @type {number}
  32998. * @default 0
  32999. */
  33000. this.bias = 0;
  33001. /**
  33002. * Defines how much the position used to query the shadow map is offset along
  33003. * the object normal. The default is `0`. Increasing this value can be used to
  33004. * reduce shadow acne especially in large scenes where light shines onto
  33005. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33006. *
  33007. * @type {number}
  33008. * @default 0
  33009. */
  33010. this.normalBias = 0;
  33011. /**
  33012. * Setting this to values greater than 1 will blur the edges of the shadow.
  33013. * High values will cause unwanted banding effects in the shadows - a greater
  33014. * map size will allow for a higher value to be used here before these effects
  33015. * become visible.
  33016. *
  33017. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  33018. * and it is recommended to increase softness by decreasing the shadow map size instead.
  33019. *
  33020. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33021. *
  33022. * @type {number}
  33023. * @default 1
  33024. */
  33025. this.radius = 1;
  33026. /**
  33027. * The amount of samples to use when blurring a VSM shadow map.
  33028. *
  33029. * @type {number}
  33030. * @default 8
  33031. */
  33032. this.blurSamples = 8;
  33033. /**
  33034. * Defines the width and height of the shadow map. Higher values give better quality
  33035. * shadows at the cost of computation time. Values must be powers of two.
  33036. *
  33037. * @type {Vector2}
  33038. * @default (512,512)
  33039. */
  33040. this.mapSize = new Vector2( 512, 512 );
  33041. /**
  33042. * The type of shadow texture. The default is `UnsignedByteType`.
  33043. *
  33044. * @type {number}
  33045. * @default UnsignedByteType
  33046. */
  33047. this.mapType = UnsignedByteType;
  33048. /**
  33049. * The depth map generated using the internal camera; a location beyond a
  33050. * pixel's depth is in shadow. Computed internally during rendering.
  33051. *
  33052. * @type {?RenderTarget}
  33053. * @default null
  33054. */
  33055. this.map = null;
  33056. /**
  33057. * The distribution map generated using the internal camera; an occlusion is
  33058. * calculated based on the distribution of depths. Computed internally during
  33059. * rendering.
  33060. *
  33061. * @type {?RenderTarget}
  33062. * @default null
  33063. */
  33064. this.mapPass = null;
  33065. /**
  33066. * Model to shadow camera space, to compute location and depth in shadow map.
  33067. * This is computed internally during rendering.
  33068. *
  33069. * @type {Matrix4}
  33070. */
  33071. this.matrix = new Matrix4();
  33072. /**
  33073. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33074. * lighting / shadows, you may set this to `false`.
  33075. *
  33076. * @type {boolean}
  33077. * @default true
  33078. */
  33079. this.autoUpdate = true;
  33080. /**
  33081. * When set to `true`, shadow maps will be updated in the next `render` call.
  33082. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33083. * set this property to `true` and then make a render call to update the light's shadow.
  33084. *
  33085. * @type {boolean}
  33086. * @default false
  33087. */
  33088. this.needsUpdate = false;
  33089. this._frustum = new Frustum();
  33090. this._frameExtents = new Vector2( 1, 1 );
  33091. this._viewportCount = 1;
  33092. this._viewports = [
  33093. new Vector4( 0, 0, 1, 1 )
  33094. ];
  33095. }
  33096. /**
  33097. * Used internally by the renderer to get the number of viewports that need
  33098. * to be rendered for this shadow.
  33099. *
  33100. * @return {number} The viewport count.
  33101. */
  33102. getViewportCount() {
  33103. return this._viewportCount;
  33104. }
  33105. /**
  33106. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33107. *
  33108. * @return {Frustum} The shadow camera frustum.
  33109. */
  33110. getFrustum() {
  33111. return this._frustum;
  33112. }
  33113. /**
  33114. * Update the matrices for the camera and shadow, used internally by the renderer.
  33115. *
  33116. * @param {Light} light - The light for which the shadow is being rendered.
  33117. */
  33118. updateMatrices( light ) {
  33119. const shadowCamera = this.camera;
  33120. const shadowMatrix = this.matrix;
  33121. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33122. shadowCamera.position.copy( _lightPositionWorld$1 );
  33123. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33124. shadowCamera.lookAt( _lookTarget$1 );
  33125. shadowCamera.updateMatrixWorld();
  33126. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33127. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33128. if ( shadowCamera.reversedDepth ) {
  33129. shadowMatrix.set(
  33130. 0.5, 0.0, 0.0, 0.5,
  33131. 0.0, 0.5, 0.0, 0.5,
  33132. 0.0, 0.0, 1.0, 0.0,
  33133. 0.0, 0.0, 0.0, 1.0
  33134. );
  33135. } else {
  33136. shadowMatrix.set(
  33137. 0.5, 0.0, 0.0, 0.5,
  33138. 0.0, 0.5, 0.0, 0.5,
  33139. 0.0, 0.0, 0.5, 0.5,
  33140. 0.0, 0.0, 0.0, 1.0
  33141. );
  33142. }
  33143. shadowMatrix.multiply( _projScreenMatrix$1 );
  33144. }
  33145. /**
  33146. * Returns a viewport definition for the given viewport index.
  33147. *
  33148. * @param {number} viewportIndex - The viewport index.
  33149. * @return {Vector4} The viewport.
  33150. */
  33151. getViewport( viewportIndex ) {
  33152. return this._viewports[ viewportIndex ];
  33153. }
  33154. /**
  33155. * Returns the frame extends.
  33156. *
  33157. * @return {Vector2} The frame extends.
  33158. */
  33159. getFrameExtents() {
  33160. return this._frameExtents;
  33161. }
  33162. /**
  33163. * Frees the GPU-related resources allocated by this instance. Call this
  33164. * method whenever this instance is no longer used in your app.
  33165. */
  33166. dispose() {
  33167. if ( this.map ) {
  33168. this.map.dispose();
  33169. }
  33170. if ( this.mapPass ) {
  33171. this.mapPass.dispose();
  33172. }
  33173. }
  33174. /**
  33175. * Copies the values of the given light shadow instance to this instance.
  33176. *
  33177. * @param {LightShadow} source - The light shadow to copy.
  33178. * @return {LightShadow} A reference to this light shadow instance.
  33179. */
  33180. copy( source ) {
  33181. this.camera = source.camera.clone();
  33182. this.intensity = source.intensity;
  33183. this.bias = source.bias;
  33184. this.radius = source.radius;
  33185. this.autoUpdate = source.autoUpdate;
  33186. this.needsUpdate = source.needsUpdate;
  33187. this.normalBias = source.normalBias;
  33188. this.blurSamples = source.blurSamples;
  33189. this.mapSize.copy( source.mapSize );
  33190. return this;
  33191. }
  33192. /**
  33193. * Returns a new light shadow instance with copied values from this instance.
  33194. *
  33195. * @return {LightShadow} A clone of this instance.
  33196. */
  33197. clone() {
  33198. return new this.constructor().copy( this );
  33199. }
  33200. /**
  33201. * Serializes the light shadow into JSON.
  33202. *
  33203. * @return {Object} A JSON object representing the serialized light shadow.
  33204. * @see {@link ObjectLoader#parse}
  33205. */
  33206. toJSON() {
  33207. const object = {};
  33208. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33209. if ( this.bias !== 0 ) object.bias = this.bias;
  33210. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33211. if ( this.radius !== 1 ) object.radius = this.radius;
  33212. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33213. object.camera = this.camera.toJSON( false ).object;
  33214. delete object.camera.matrix;
  33215. return object;
  33216. }
  33217. }
  33218. /**
  33219. * Represents the shadow configuration of directional lights.
  33220. *
  33221. * @augments LightShadow
  33222. */
  33223. class SpotLightShadow extends LightShadow {
  33224. /**
  33225. * Constructs a new spot light shadow.
  33226. */
  33227. constructor() {
  33228. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33229. /**
  33230. * This flag can be used for type testing.
  33231. *
  33232. * @type {boolean}
  33233. * @readonly
  33234. * @default true
  33235. */
  33236. this.isSpotLightShadow = true;
  33237. /**
  33238. * Used to focus the shadow camera. The camera's field of view is set as a
  33239. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33240. *
  33241. * @type {number}
  33242. * @default 1
  33243. */
  33244. this.focus = 1;
  33245. /**
  33246. * Texture aspect ratio.
  33247. *
  33248. * @type {number}
  33249. * @default 1
  33250. */
  33251. this.aspect = 1;
  33252. }
  33253. updateMatrices( light ) {
  33254. const camera = this.camera;
  33255. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33256. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33257. const far = light.distance || camera.far;
  33258. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33259. camera.fov = fov;
  33260. camera.aspect = aspect;
  33261. camera.far = far;
  33262. camera.updateProjectionMatrix();
  33263. }
  33264. super.updateMatrices( light );
  33265. }
  33266. copy( source ) {
  33267. super.copy( source );
  33268. this.focus = source.focus;
  33269. return this;
  33270. }
  33271. }
  33272. /**
  33273. * This light gets emitted from a single point in one direction, along a cone
  33274. * that increases in size the further from the light it gets.
  33275. *
  33276. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33277. *
  33278. * ```js
  33279. * // white spotlight shining from the side, modulated by a texture
  33280. * const spotLight = new THREE.SpotLight( 0xffffff );
  33281. * spotLight.position.set( 100, 1000, 100 );
  33282. * spotLight.map = new THREE.TextureLoader().load( url );
  33283. *
  33284. * spotLight.castShadow = true;
  33285. * spotLight.shadow.mapSize.width = 1024;
  33286. * spotLight.shadow.mapSize.height = 1024;
  33287. * spotLight.shadow.camera.near = 500;
  33288. * spotLight.shadow.camera.far = 4000;
  33289. * spotLight.shadow.camera.fov = 30;s
  33290. * ```
  33291. *
  33292. * @augments Light
  33293. */
  33294. class SpotLight extends Light {
  33295. /**
  33296. * Constructs a new spot light.
  33297. *
  33298. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33299. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33300. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33301. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33302. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33303. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33304. */
  33305. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33306. super( color, intensity );
  33307. /**
  33308. * This flag can be used for type testing.
  33309. *
  33310. * @type {boolean}
  33311. * @readonly
  33312. * @default true
  33313. */
  33314. this.isSpotLight = true;
  33315. this.type = 'SpotLight';
  33316. this.position.copy( Object3D.DEFAULT_UP );
  33317. this.updateMatrix();
  33318. /**
  33319. * The spot light points from its position to the
  33320. * target's position.
  33321. *
  33322. * For the target's position to be changed to anything other
  33323. * than the default, it must be added to the scene.
  33324. *
  33325. * It is also possible to set the target to be another 3D object
  33326. * in the scene. The light will now track the target object.
  33327. *
  33328. * @type {Object3D}
  33329. */
  33330. this.target = new Object3D();
  33331. /**
  33332. * Maximum range of the light. `0` means no limit.
  33333. *
  33334. * @type {number}
  33335. * @default 0
  33336. */
  33337. this.distance = distance;
  33338. /**
  33339. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33340. *
  33341. * @type {number}
  33342. * @default Math.PI/3
  33343. */
  33344. this.angle = angle;
  33345. /**
  33346. * Percent of the spotlight cone that is attenuated due to penumbra.
  33347. * Value range is `[0,1]`.
  33348. *
  33349. * @type {number}
  33350. * @default 0
  33351. */
  33352. this.penumbra = penumbra;
  33353. /**
  33354. * The amount the light dims along the distance of the light. In context of
  33355. * physically-correct rendering the default value should not be changed.
  33356. *
  33357. * @type {number}
  33358. * @default 2
  33359. */
  33360. this.decay = decay;
  33361. /**
  33362. * A texture used to modulate the color of the light. The spot light
  33363. * color is mixed with the RGB value of this texture, with a ratio
  33364. * corresponding to its alpha value. The cookie-like masking effect is
  33365. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33366. *
  33367. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33368. *
  33369. * @type {?Texture}
  33370. * @default null
  33371. */
  33372. this.map = null;
  33373. /**
  33374. * This property holds the light's shadow configuration.
  33375. *
  33376. * @type {SpotLightShadow}
  33377. */
  33378. this.shadow = new SpotLightShadow();
  33379. }
  33380. /**
  33381. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33382. * Changing the power will also change the light's intensity.
  33383. *
  33384. * @type {number}
  33385. */
  33386. get power() {
  33387. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33388. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33389. return this.intensity * Math.PI;
  33390. }
  33391. set power( power ) {
  33392. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33393. this.intensity = power / Math.PI;
  33394. }
  33395. dispose() {
  33396. this.shadow.dispose();
  33397. }
  33398. copy( source, recursive ) {
  33399. super.copy( source, recursive );
  33400. this.distance = source.distance;
  33401. this.angle = source.angle;
  33402. this.penumbra = source.penumbra;
  33403. this.decay = source.decay;
  33404. this.target = source.target.clone();
  33405. this.shadow = source.shadow.clone();
  33406. return this;
  33407. }
  33408. }
  33409. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33410. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33411. const _lookTarget = /*@__PURE__*/ new Vector3();
  33412. /**
  33413. * Represents the shadow configuration of point lights.
  33414. *
  33415. * @augments LightShadow
  33416. */
  33417. class PointLightShadow extends LightShadow {
  33418. /**
  33419. * Constructs a new point light shadow.
  33420. */
  33421. constructor() {
  33422. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33423. /**
  33424. * This flag can be used for type testing.
  33425. *
  33426. * @type {boolean}
  33427. * @readonly
  33428. * @default true
  33429. */
  33430. this.isPointLightShadow = true;
  33431. this._frameExtents = new Vector2( 4, 2 );
  33432. this._viewportCount = 6;
  33433. this._viewports = [
  33434. // These viewports map a cube-map onto a 2D texture with the
  33435. // following orientation:
  33436. //
  33437. // xzXZ
  33438. // y Y
  33439. //
  33440. // X - Positive x direction
  33441. // x - Negative x direction
  33442. // Y - Positive y direction
  33443. // y - Negative y direction
  33444. // Z - Positive z direction
  33445. // z - Negative z direction
  33446. // positive X
  33447. new Vector4( 2, 1, 1, 1 ),
  33448. // negative X
  33449. new Vector4( 0, 1, 1, 1 ),
  33450. // positive Z
  33451. new Vector4( 3, 1, 1, 1 ),
  33452. // negative Z
  33453. new Vector4( 1, 1, 1, 1 ),
  33454. // positive Y
  33455. new Vector4( 3, 0, 1, 1 ),
  33456. // negative Y
  33457. new Vector4( 1, 0, 1, 1 )
  33458. ];
  33459. this._cubeDirections = [
  33460. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  33461. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  33462. ];
  33463. this._cubeUps = [
  33464. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  33465. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  33466. ];
  33467. }
  33468. /**
  33469. * Update the matrices for the camera and shadow, used internally by the renderer.
  33470. *
  33471. * @param {Light} light - The light for which the shadow is being rendered.
  33472. * @param {number} [viewportIndex=0] - The viewport index.
  33473. */
  33474. updateMatrices( light, viewportIndex = 0 ) {
  33475. const camera = this.camera;
  33476. const shadowMatrix = this.matrix;
  33477. const far = light.distance || camera.far;
  33478. if ( far !== camera.far ) {
  33479. camera.far = far;
  33480. camera.updateProjectionMatrix();
  33481. }
  33482. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33483. camera.position.copy( _lightPositionWorld );
  33484. _lookTarget.copy( camera.position );
  33485. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  33486. camera.up.copy( this._cubeUps[ viewportIndex ] );
  33487. camera.lookAt( _lookTarget );
  33488. camera.updateMatrixWorld();
  33489. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  33490. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33491. this._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  33492. }
  33493. }
  33494. /**
  33495. * A light that gets emitted from a single point in all directions. A common
  33496. * use case for this is to replicate the light emitted from a bare
  33497. * lightbulb.
  33498. *
  33499. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33500. *
  33501. * ```js
  33502. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33503. * light.position.set( 50, 50, 50 );
  33504. * scene.add( light );
  33505. * ```
  33506. *
  33507. * @augments Light
  33508. */
  33509. class PointLight extends Light {
  33510. /**
  33511. * Constructs a new point light.
  33512. *
  33513. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33514. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33515. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33516. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33517. */
  33518. constructor( color, intensity, distance = 0, decay = 2 ) {
  33519. super( color, intensity );
  33520. /**
  33521. * This flag can be used for type testing.
  33522. *
  33523. * @type {boolean}
  33524. * @readonly
  33525. * @default true
  33526. */
  33527. this.isPointLight = true;
  33528. this.type = 'PointLight';
  33529. /**
  33530. * When distance is zero, light will attenuate according to inverse-square
  33531. * law to infinite distance. When distance is non-zero, light will attenuate
  33532. * according to inverse-square law until near the distance cutoff, where it
  33533. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33534. * physically correct.
  33535. *
  33536. * @type {number}
  33537. * @default 0
  33538. */
  33539. this.distance = distance;
  33540. /**
  33541. * The amount the light dims along the distance of the light. In context of
  33542. * physically-correct rendering the default value should not be changed.
  33543. *
  33544. * @type {number}
  33545. * @default 2
  33546. */
  33547. this.decay = decay;
  33548. /**
  33549. * This property holds the light's shadow configuration.
  33550. *
  33551. * @type {PointLightShadow}
  33552. */
  33553. this.shadow = new PointLightShadow();
  33554. }
  33555. /**
  33556. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33557. * Changing the power will also change the light's intensity.
  33558. *
  33559. * @type {number}
  33560. */
  33561. get power() {
  33562. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33563. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33564. return this.intensity * 4 * Math.PI;
  33565. }
  33566. set power( power ) {
  33567. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33568. this.intensity = power / ( 4 * Math.PI );
  33569. }
  33570. dispose() {
  33571. this.shadow.dispose();
  33572. }
  33573. copy( source, recursive ) {
  33574. super.copy( source, recursive );
  33575. this.distance = source.distance;
  33576. this.decay = source.decay;
  33577. this.shadow = source.shadow.clone();
  33578. return this;
  33579. }
  33580. }
  33581. /**
  33582. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  33583. *
  33584. * In this projection mode, an object's size in the rendered image stays
  33585. * constant regardless of its distance from the camera. This can be useful
  33586. * for rendering 2D scenes and UI elements, amongst other things.
  33587. *
  33588. * ```js
  33589. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33590. * scene.add( camera );
  33591. * ```
  33592. *
  33593. * @augments Camera
  33594. */
  33595. class OrthographicCamera extends Camera {
  33596. /**
  33597. * Constructs a new orthographic camera.
  33598. *
  33599. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33600. * @param {number} [right=1] - The right plane of the camera's frustum.
  33601. * @param {number} [top=1] - The top plane of the camera's frustum.
  33602. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33603. * @param {number} [near=0.1] - The camera's near plane.
  33604. * @param {number} [far=2000] - The camera's far plane.
  33605. */
  33606. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33607. super();
  33608. /**
  33609. * This flag can be used for type testing.
  33610. *
  33611. * @type {boolean}
  33612. * @readonly
  33613. * @default true
  33614. */
  33615. this.isOrthographicCamera = true;
  33616. this.type = 'OrthographicCamera';
  33617. /**
  33618. * The zoom factor of the camera.
  33619. *
  33620. * @type {number}
  33621. * @default 1
  33622. */
  33623. this.zoom = 1;
  33624. /**
  33625. * Represents the frustum window specification. This property should not be edited
  33626. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33627. *
  33628. * @type {?Object}
  33629. * @default null
  33630. */
  33631. this.view = null;
  33632. /**
  33633. * The left plane of the camera's frustum.
  33634. *
  33635. * @type {number}
  33636. * @default -1
  33637. */
  33638. this.left = left;
  33639. /**
  33640. * The right plane of the camera's frustum.
  33641. *
  33642. * @type {number}
  33643. * @default 1
  33644. */
  33645. this.right = right;
  33646. /**
  33647. * The top plane of the camera's frustum.
  33648. *
  33649. * @type {number}
  33650. * @default 1
  33651. */
  33652. this.top = top;
  33653. /**
  33654. * The bottom plane of the camera's frustum.
  33655. *
  33656. * @type {number}
  33657. * @default -1
  33658. */
  33659. this.bottom = bottom;
  33660. /**
  33661. * The camera's near plane. The valid range is greater than `0`
  33662. * and less than the current value of {@link OrthographicCamera#far}.
  33663. *
  33664. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33665. * valid value for an orthographic camera's near plane.
  33666. *
  33667. * @type {number}
  33668. * @default 0.1
  33669. */
  33670. this.near = near;
  33671. /**
  33672. * The camera's far plane. Must be greater than the
  33673. * current value of {@link OrthographicCamera#near}.
  33674. *
  33675. * @type {number}
  33676. * @default 2000
  33677. */
  33678. this.far = far;
  33679. this.updateProjectionMatrix();
  33680. }
  33681. copy( source, recursive ) {
  33682. super.copy( source, recursive );
  33683. this.left = source.left;
  33684. this.right = source.right;
  33685. this.top = source.top;
  33686. this.bottom = source.bottom;
  33687. this.near = source.near;
  33688. this.far = source.far;
  33689. this.zoom = source.zoom;
  33690. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33691. return this;
  33692. }
  33693. /**
  33694. * Sets an offset in a larger frustum. This is useful for multi-window or
  33695. * multi-monitor/multi-machine setups.
  33696. *
  33697. * @param {number} fullWidth - The full width of multiview setup.
  33698. * @param {number} fullHeight - The full height of multiview setup.
  33699. * @param {number} x - The horizontal offset of the subcamera.
  33700. * @param {number} y - The vertical offset of the subcamera.
  33701. * @param {number} width - The width of subcamera.
  33702. * @param {number} height - The height of subcamera.
  33703. * @see {@link PerspectiveCamera#setViewOffset}
  33704. */
  33705. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33706. if ( this.view === null ) {
  33707. this.view = {
  33708. enabled: true,
  33709. fullWidth: 1,
  33710. fullHeight: 1,
  33711. offsetX: 0,
  33712. offsetY: 0,
  33713. width: 1,
  33714. height: 1
  33715. };
  33716. }
  33717. this.view.enabled = true;
  33718. this.view.fullWidth = fullWidth;
  33719. this.view.fullHeight = fullHeight;
  33720. this.view.offsetX = x;
  33721. this.view.offsetY = y;
  33722. this.view.width = width;
  33723. this.view.height = height;
  33724. this.updateProjectionMatrix();
  33725. }
  33726. /**
  33727. * Removes the view offset from the projection matrix.
  33728. */
  33729. clearViewOffset() {
  33730. if ( this.view !== null ) {
  33731. this.view.enabled = false;
  33732. }
  33733. this.updateProjectionMatrix();
  33734. }
  33735. /**
  33736. * Updates the camera's projection matrix. Must be called after any change of
  33737. * camera properties.
  33738. */
  33739. updateProjectionMatrix() {
  33740. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33741. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33742. const cx = ( this.right + this.left ) / 2;
  33743. const cy = ( this.top + this.bottom ) / 2;
  33744. let left = cx - dx;
  33745. let right = cx + dx;
  33746. let top = cy + dy;
  33747. let bottom = cy - dy;
  33748. if ( this.view !== null && this.view.enabled ) {
  33749. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33750. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33751. left += scaleW * this.view.offsetX;
  33752. right = left + scaleW * this.view.width;
  33753. top -= scaleH * this.view.offsetY;
  33754. bottom = top - scaleH * this.view.height;
  33755. }
  33756. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  33757. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33758. }
  33759. toJSON( meta ) {
  33760. const data = super.toJSON( meta );
  33761. data.object.zoom = this.zoom;
  33762. data.object.left = this.left;
  33763. data.object.right = this.right;
  33764. data.object.top = this.top;
  33765. data.object.bottom = this.bottom;
  33766. data.object.near = this.near;
  33767. data.object.far = this.far;
  33768. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33769. return data;
  33770. }
  33771. }
  33772. /**
  33773. * Represents the shadow configuration of directional lights.
  33774. *
  33775. * @augments LightShadow
  33776. */
  33777. class DirectionalLightShadow extends LightShadow {
  33778. /**
  33779. * Constructs a new directional light shadow.
  33780. */
  33781. constructor() {
  33782. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  33783. /**
  33784. * This flag can be used for type testing.
  33785. *
  33786. * @type {boolean}
  33787. * @readonly
  33788. * @default true
  33789. */
  33790. this.isDirectionalLightShadow = true;
  33791. }
  33792. }
  33793. /**
  33794. * A light that gets emitted in a specific direction. This light will behave
  33795. * as though it is infinitely far away and the rays produced from it are all
  33796. * parallel. The common use case for this is to simulate daylight; the sun is
  33797. * far enough away that its position can be considered to be infinite, and
  33798. * all light rays coming from it are parallel.
  33799. *
  33800. * A common point of confusion for directional lights is that setting the
  33801. * rotation has no effect. This is because three.js's DirectionalLight is the
  33802. * equivalent to what is often called a 'Target Direct Light' in other
  33803. * applications.
  33804. *
  33805. * This means that its direction is calculated as pointing from the light's
  33806. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  33807. * (as opposed to a 'Free Direct Light' that just has a rotation
  33808. * component).
  33809. *
  33810. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  33811. *
  33812. * ```js
  33813. * // White directional light at half intensity shining from the top.
  33814. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  33815. * scene.add( directionalLight );
  33816. * ```
  33817. *
  33818. * @augments Light
  33819. */
  33820. class DirectionalLight extends Light {
  33821. /**
  33822. * Constructs a new directional light.
  33823. *
  33824. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33825. * @param {number} [intensity=1] - The light's strength/intensity.
  33826. */
  33827. constructor( color, intensity ) {
  33828. super( color, intensity );
  33829. /**
  33830. * This flag can be used for type testing.
  33831. *
  33832. * @type {boolean}
  33833. * @readonly
  33834. * @default true
  33835. */
  33836. this.isDirectionalLight = true;
  33837. this.type = 'DirectionalLight';
  33838. this.position.copy( Object3D.DEFAULT_UP );
  33839. this.updateMatrix();
  33840. /**
  33841. * The directional light points from its position to the
  33842. * target's position.
  33843. *
  33844. * For the target's position to be changed to anything other
  33845. * than the default, it must be added to the scene.
  33846. *
  33847. * It is also possible to set the target to be another 3D object
  33848. * in the scene. The light will now track the target object.
  33849. *
  33850. * @type {Object3D}
  33851. */
  33852. this.target = new Object3D();
  33853. /**
  33854. * This property holds the light's shadow configuration.
  33855. *
  33856. * @type {DirectionalLightShadow}
  33857. */
  33858. this.shadow = new DirectionalLightShadow();
  33859. }
  33860. dispose() {
  33861. this.shadow.dispose();
  33862. }
  33863. copy( source ) {
  33864. super.copy( source );
  33865. this.target = source.target.clone();
  33866. this.shadow = source.shadow.clone();
  33867. return this;
  33868. }
  33869. }
  33870. /**
  33871. * This light globally illuminates all objects in the scene equally.
  33872. *
  33873. * It cannot be used to cast shadows as it does not have a direction.
  33874. *
  33875. * ```js
  33876. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  33877. * scene.add( light );
  33878. * ```
  33879. *
  33880. * @augments Light
  33881. */
  33882. class AmbientLight extends Light {
  33883. /**
  33884. * Constructs a new ambient light.
  33885. *
  33886. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33887. * @param {number} [intensity=1] - The light's strength/intensity.
  33888. */
  33889. constructor( color, intensity ) {
  33890. super( color, intensity );
  33891. /**
  33892. * This flag can be used for type testing.
  33893. *
  33894. * @type {boolean}
  33895. * @readonly
  33896. * @default true
  33897. */
  33898. this.isAmbientLight = true;
  33899. this.type = 'AmbientLight';
  33900. }
  33901. }
  33902. /**
  33903. * This class emits light uniformly across the face a rectangular plane.
  33904. * This light type can be used to simulate light sources such as bright
  33905. * windows or strip lighting.
  33906. *
  33907. * Important Notes:
  33908. *
  33909. * - There is no shadow support.
  33910. * - Only PBR materials are supported.
  33911. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  33912. * into your app and init the uniforms/textures.
  33913. *
  33914. * ```js
  33915. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  33916. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  33917. *
  33918. * const intensity = 1; const width = 10; const height = 10;
  33919. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  33920. * rectLight.position.set( 5, 5, 0 );
  33921. * rectLight.lookAt( 0, 0, 0 );
  33922. * scene.add( rectLight )
  33923. * ```
  33924. *
  33925. * @augments Light
  33926. */
  33927. class RectAreaLight extends Light {
  33928. /**
  33929. * Constructs a new area light.
  33930. *
  33931. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33932. * @param {number} [intensity=1] - The light's strength/intensity.
  33933. * @param {number} [width=10] - The width of the light.
  33934. * @param {number} [height=10] - The height of the light.
  33935. */
  33936. constructor( color, intensity, width = 10, height = 10 ) {
  33937. super( color, intensity );
  33938. /**
  33939. * This flag can be used for type testing.
  33940. *
  33941. * @type {boolean}
  33942. * @readonly
  33943. * @default true
  33944. */
  33945. this.isRectAreaLight = true;
  33946. this.type = 'RectAreaLight';
  33947. /**
  33948. * The width of the light.
  33949. *
  33950. * @type {number}
  33951. * @default 10
  33952. */
  33953. this.width = width;
  33954. /**
  33955. * The height of the light.
  33956. *
  33957. * @type {number}
  33958. * @default 10
  33959. */
  33960. this.height = height;
  33961. }
  33962. /**
  33963. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33964. * Changing the power will also change the light's intensity.
  33965. *
  33966. * @type {number}
  33967. */
  33968. get power() {
  33969. // compute the light's luminous power (in lumens) from its intensity (in nits)
  33970. return this.intensity * this.width * this.height * Math.PI;
  33971. }
  33972. set power( power ) {
  33973. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  33974. this.intensity = power / ( this.width * this.height * Math.PI );
  33975. }
  33976. copy( source ) {
  33977. super.copy( source );
  33978. this.width = source.width;
  33979. this.height = source.height;
  33980. return this;
  33981. }
  33982. toJSON( meta ) {
  33983. const data = super.toJSON( meta );
  33984. data.object.width = this.width;
  33985. data.object.height = this.height;
  33986. return data;
  33987. }
  33988. }
  33989. /**
  33990. * Represents a third-order spherical harmonics (SH). Light probes use this class
  33991. * to encode lighting information.
  33992. *
  33993. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  33994. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  33995. */
  33996. class SphericalHarmonics3 {
  33997. /**
  33998. * Constructs a new spherical harmonics.
  33999. */
  34000. constructor() {
  34001. /**
  34002. * This flag can be used for type testing.
  34003. *
  34004. * @type {boolean}
  34005. * @readonly
  34006. * @default true
  34007. */
  34008. this.isSphericalHarmonics3 = true;
  34009. /**
  34010. * An array holding the (9) SH coefficients.
  34011. *
  34012. * @type {Array<Vector3>}
  34013. */
  34014. this.coefficients = [];
  34015. for ( let i = 0; i < 9; i ++ ) {
  34016. this.coefficients.push( new Vector3() );
  34017. }
  34018. }
  34019. /**
  34020. * Sets the given SH coefficients to this instance by copying
  34021. * the values.
  34022. *
  34023. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34024. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34025. */
  34026. set( coefficients ) {
  34027. for ( let i = 0; i < 9; i ++ ) {
  34028. this.coefficients[ i ].copy( coefficients[ i ] );
  34029. }
  34030. return this;
  34031. }
  34032. /**
  34033. * Sets all SH coefficients to `0`.
  34034. *
  34035. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34036. */
  34037. zero() {
  34038. for ( let i = 0; i < 9; i ++ ) {
  34039. this.coefficients[ i ].set( 0, 0, 0 );
  34040. }
  34041. return this;
  34042. }
  34043. /**
  34044. * Returns the radiance in the direction of the given normal.
  34045. *
  34046. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34047. * @param {Vector3} target - The target vector that is used to store the method's result.
  34048. * @return {Vector3} The radiance.
  34049. */
  34050. getAt( normal, target ) {
  34051. // normal is assumed to be unit length
  34052. const x = normal.x, y = normal.y, z = normal.z;
  34053. const coeff = this.coefficients;
  34054. // band 0
  34055. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34056. // band 1
  34057. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34058. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34059. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34060. // band 2
  34061. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34062. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34063. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34064. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34065. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34066. return target;
  34067. }
  34068. /**
  34069. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34070. * direction of the given normal.
  34071. *
  34072. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34073. * @param {Vector3} target - The target vector that is used to store the method's result.
  34074. * @return {Vector3} The irradiance.
  34075. */
  34076. getIrradianceAt( normal, target ) {
  34077. // normal is assumed to be unit length
  34078. const x = normal.x, y = normal.y, z = normal.z;
  34079. const coeff = this.coefficients;
  34080. // band 0
  34081. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34082. // band 1
  34083. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34084. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34085. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34086. // band 2
  34087. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34088. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34089. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34090. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34091. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34092. return target;
  34093. }
  34094. /**
  34095. * Adds the given SH to this instance.
  34096. *
  34097. * @param {SphericalHarmonics3} sh - The SH to add.
  34098. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34099. */
  34100. add( sh ) {
  34101. for ( let i = 0; i < 9; i ++ ) {
  34102. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34103. }
  34104. return this;
  34105. }
  34106. /**
  34107. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34108. * {@link SphericalHarmonics3#scale} at once.
  34109. *
  34110. * @param {SphericalHarmonics3} sh - The SH to add.
  34111. * @param {number} s - The scale factor.
  34112. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34113. */
  34114. addScaledSH( sh, s ) {
  34115. for ( let i = 0; i < 9; i ++ ) {
  34116. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34117. }
  34118. return this;
  34119. }
  34120. /**
  34121. * Scales this SH by the given scale factor.
  34122. *
  34123. * @param {number} s - The scale factor.
  34124. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34125. */
  34126. scale( s ) {
  34127. for ( let i = 0; i < 9; i ++ ) {
  34128. this.coefficients[ i ].multiplyScalar( s );
  34129. }
  34130. return this;
  34131. }
  34132. /**
  34133. * Linear interpolates between the given SH and this instance by the given
  34134. * alpha factor.
  34135. *
  34136. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34137. * @param {number} alpha - The alpha factor.
  34138. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34139. */
  34140. lerp( sh, alpha ) {
  34141. for ( let i = 0; i < 9; i ++ ) {
  34142. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34143. }
  34144. return this;
  34145. }
  34146. /**
  34147. * Returns `true` if this spherical harmonics is equal with the given one.
  34148. *
  34149. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34150. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34151. */
  34152. equals( sh ) {
  34153. for ( let i = 0; i < 9; i ++ ) {
  34154. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34155. return false;
  34156. }
  34157. }
  34158. return true;
  34159. }
  34160. /**
  34161. * Copies the values of the given spherical harmonics to this instance.
  34162. *
  34163. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34164. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34165. */
  34166. copy( sh ) {
  34167. return this.set( sh.coefficients );
  34168. }
  34169. /**
  34170. * Returns a new spherical harmonics with copied values from this instance.
  34171. *
  34172. * @return {SphericalHarmonics3} A clone of this instance.
  34173. */
  34174. clone() {
  34175. return new this.constructor().copy( this );
  34176. }
  34177. /**
  34178. * Sets the SH coefficients of this instance from the given array.
  34179. *
  34180. * @param {Array<number>} array - An array holding the SH coefficients.
  34181. * @param {number} [offset=0] - The array offset where to start copying.
  34182. * @return {SphericalHarmonics3} A clone of this instance.
  34183. */
  34184. fromArray( array, offset = 0 ) {
  34185. const coefficients = this.coefficients;
  34186. for ( let i = 0; i < 9; i ++ ) {
  34187. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34188. }
  34189. return this;
  34190. }
  34191. /**
  34192. * Returns an array with the SH coefficients, or copies them into the provided
  34193. * array. The coefficients are represented as numbers.
  34194. *
  34195. * @param {Array<number>} [array=[]] - The target array.
  34196. * @param {number} [offset=0] - The array offset where to start copying.
  34197. * @return {Array<number>} An array with flat SH coefficients.
  34198. */
  34199. toArray( array = [], offset = 0 ) {
  34200. const coefficients = this.coefficients;
  34201. for ( let i = 0; i < 9; i ++ ) {
  34202. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34203. }
  34204. return array;
  34205. }
  34206. /**
  34207. * Computes the SH basis for the given normal vector.
  34208. *
  34209. * @param {Vector3} normal - The normal.
  34210. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34211. */
  34212. static getBasisAt( normal, shBasis ) {
  34213. // normal is assumed to be unit length
  34214. const x = normal.x, y = normal.y, z = normal.z;
  34215. // band 0
  34216. shBasis[ 0 ] = 0.282095;
  34217. // band 1
  34218. shBasis[ 1 ] = 0.488603 * y;
  34219. shBasis[ 2 ] = 0.488603 * z;
  34220. shBasis[ 3 ] = 0.488603 * x;
  34221. // band 2
  34222. shBasis[ 4 ] = 1.092548 * x * y;
  34223. shBasis[ 5 ] = 1.092548 * y * z;
  34224. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34225. shBasis[ 7 ] = 1.092548 * x * z;
  34226. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34227. }
  34228. }
  34229. /**
  34230. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34231. * classical light sources (e.g. directional, point or spot lights), light
  34232. * probes do not emit light. Instead they store information about light
  34233. * passing through 3D space. During rendering, the light that hits a 3D
  34234. * object is approximated by using the data from the light probe.
  34235. *
  34236. * Light probes are usually created from (radiance) environment maps. The
  34237. * class {@link LightProbeGenerator} can be used to create light probes from
  34238. * cube textures or render targets. However, light estimation data could also
  34239. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34240. * augmented reality content that reacts to real world lighting.
  34241. *
  34242. * The current probe implementation in three.js supports so-called diffuse
  34243. * light probes. This type of light probe is functionally equivalent to an
  34244. * irradiance environment map.
  34245. *
  34246. * @augments Light
  34247. */
  34248. class LightProbe extends Light {
  34249. /**
  34250. * Constructs a new light probe.
  34251. *
  34252. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34253. * @param {number} [intensity=1] - The light's strength/intensity.
  34254. */
  34255. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34256. super( undefined, intensity );
  34257. /**
  34258. * This flag can be used for type testing.
  34259. *
  34260. * @type {boolean}
  34261. * @readonly
  34262. * @default true
  34263. */
  34264. this.isLightProbe = true;
  34265. /**
  34266. * A light probe uses spherical harmonics to encode lighting information.
  34267. *
  34268. * @type {SphericalHarmonics3}
  34269. */
  34270. this.sh = sh;
  34271. }
  34272. copy( source ) {
  34273. super.copy( source );
  34274. this.sh.copy( source.sh );
  34275. return this;
  34276. }
  34277. /**
  34278. * Deserializes the light prove from the given JSON.
  34279. *
  34280. * @param {Object} json - The JSON holding the serialized light probe.
  34281. * @return {LightProbe} A reference to this light probe.
  34282. */
  34283. fromJSON( json ) {
  34284. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  34285. this.sh.fromArray( json.sh );
  34286. return this;
  34287. }
  34288. toJSON( meta ) {
  34289. const data = super.toJSON( meta );
  34290. data.object.sh = this.sh.toArray();
  34291. return data;
  34292. }
  34293. }
  34294. /**
  34295. * Class for loading geometries. The files are internally
  34296. * loaded via {@link FileLoader}.
  34297. *
  34298. * ```js
  34299. * const loader = new THREE.MaterialLoader();
  34300. * const material = await loader.loadAsync( 'material.json' );
  34301. * ```
  34302. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34303. *
  34304. * @augments Loader
  34305. */
  34306. class MaterialLoader extends Loader {
  34307. /**
  34308. * Constructs a new material loader.
  34309. *
  34310. * @param {LoadingManager} [manager] - The loading manager.
  34311. */
  34312. constructor( manager ) {
  34313. super( manager );
  34314. /**
  34315. * A dictionary holding textures used by the material.
  34316. *
  34317. * @type {Object<string,Texture>}
  34318. */
  34319. this.textures = {};
  34320. }
  34321. /**
  34322. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34323. *
  34324. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34325. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34326. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34327. * @param {onErrorCallback} onError - Executed when errors occur.
  34328. */
  34329. load( url, onLoad, onProgress, onError ) {
  34330. const scope = this;
  34331. const loader = new FileLoader( scope.manager );
  34332. loader.setPath( scope.path );
  34333. loader.setRequestHeader( scope.requestHeader );
  34334. loader.setWithCredentials( scope.withCredentials );
  34335. loader.load( url, function ( text ) {
  34336. try {
  34337. onLoad( scope.parse( JSON.parse( text ) ) );
  34338. } catch ( e ) {
  34339. if ( onError ) {
  34340. onError( e );
  34341. } else {
  34342. console.error( e );
  34343. }
  34344. scope.manager.itemError( url );
  34345. }
  34346. }, onProgress, onError );
  34347. }
  34348. /**
  34349. * Parses the given JSON object and returns a material.
  34350. *
  34351. * @param {Object} json - The serialized material.
  34352. * @return {Material} The parsed material.
  34353. */
  34354. parse( json ) {
  34355. const textures = this.textures;
  34356. function getTexture( name ) {
  34357. if ( textures[ name ] === undefined ) {
  34358. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  34359. }
  34360. return textures[ name ];
  34361. }
  34362. const material = this.createMaterialFromType( json.type );
  34363. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34364. if ( json.name !== undefined ) material.name = json.name;
  34365. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34366. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34367. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34368. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34369. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34370. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34371. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34372. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34373. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34374. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34375. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34376. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34377. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34378. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34379. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34380. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34381. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34382. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34383. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34384. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34385. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34386. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34387. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34388. if ( json.fog !== undefined ) material.fog = json.fog;
  34389. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34390. if ( json.blending !== undefined ) material.blending = json.blending;
  34391. if ( json.combine !== undefined ) material.combine = json.combine;
  34392. if ( json.side !== undefined ) material.side = json.side;
  34393. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34394. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34395. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34396. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34397. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34398. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34399. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34400. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34401. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34402. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34403. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34404. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34405. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34406. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34407. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34408. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34409. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34410. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34411. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34412. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34413. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34414. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34415. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34416. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34417. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34418. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34419. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34420. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34421. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34422. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34423. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34424. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34425. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34426. if ( json.scale !== undefined ) material.scale = json.scale;
  34427. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34428. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34429. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34430. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34431. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34432. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34433. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34434. if ( json.visible !== undefined ) material.visible = json.visible;
  34435. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34436. if ( json.userData !== undefined ) material.userData = json.userData;
  34437. if ( json.vertexColors !== undefined ) {
  34438. if ( typeof json.vertexColors === 'number' ) {
  34439. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34440. } else {
  34441. material.vertexColors = json.vertexColors;
  34442. }
  34443. }
  34444. // Shader Material
  34445. if ( json.uniforms !== undefined ) {
  34446. for ( const name in json.uniforms ) {
  34447. const uniform = json.uniforms[ name ];
  34448. material.uniforms[ name ] = {};
  34449. switch ( uniform.type ) {
  34450. case 't':
  34451. material.uniforms[ name ].value = getTexture( uniform.value );
  34452. break;
  34453. case 'c':
  34454. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34455. break;
  34456. case 'v2':
  34457. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34458. break;
  34459. case 'v3':
  34460. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34461. break;
  34462. case 'v4':
  34463. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34464. break;
  34465. case 'm3':
  34466. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34467. break;
  34468. case 'm4':
  34469. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34470. break;
  34471. default:
  34472. material.uniforms[ name ].value = uniform.value;
  34473. }
  34474. }
  34475. }
  34476. if ( json.defines !== undefined ) material.defines = json.defines;
  34477. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34478. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34479. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34480. if ( json.extensions !== undefined ) {
  34481. for ( const key in json.extensions ) {
  34482. material.extensions[ key ] = json.extensions[ key ];
  34483. }
  34484. }
  34485. if ( json.lights !== undefined ) material.lights = json.lights;
  34486. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34487. // for PointsMaterial
  34488. if ( json.size !== undefined ) material.size = json.size;
  34489. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34490. // maps
  34491. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34492. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34493. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34494. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34495. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34496. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34497. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34498. if ( json.normalScale !== undefined ) {
  34499. let normalScale = json.normalScale;
  34500. if ( Array.isArray( normalScale ) === false ) {
  34501. // Blender exporter used to export a scalar. See #7459
  34502. normalScale = [ normalScale, normalScale ];
  34503. }
  34504. material.normalScale = new Vector2().fromArray( normalScale );
  34505. }
  34506. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34507. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34508. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34509. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34510. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34511. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34512. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34513. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34514. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34515. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34516. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34517. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34518. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34519. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34520. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34521. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34522. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34523. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34524. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34525. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34526. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34527. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34528. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34529. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34530. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34531. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34532. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34533. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34534. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34535. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34536. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34537. return material;
  34538. }
  34539. /**
  34540. * Textures are not embedded in the material JSON so they have
  34541. * to be injected before the loading process starts.
  34542. *
  34543. * @param {Object} value - A dictionary holding textures for material properties.
  34544. * @return {MaterialLoader} A reference to this material loader.
  34545. */
  34546. setTextures( value ) {
  34547. this.textures = value;
  34548. return this;
  34549. }
  34550. /**
  34551. * Creates a material for the given type.
  34552. *
  34553. * @param {string} type - The material type.
  34554. * @return {Material} The new material.
  34555. */
  34556. createMaterialFromType( type ) {
  34557. return MaterialLoader.createMaterialFromType( type );
  34558. }
  34559. /**
  34560. * Creates a material for the given type.
  34561. *
  34562. * @static
  34563. * @param {string} type - The material type.
  34564. * @return {Material} The new material.
  34565. */
  34566. static createMaterialFromType( type ) {
  34567. const materialLib = {
  34568. ShadowMaterial,
  34569. SpriteMaterial,
  34570. RawShaderMaterial,
  34571. ShaderMaterial,
  34572. PointsMaterial,
  34573. MeshPhysicalMaterial,
  34574. MeshStandardMaterial,
  34575. MeshPhongMaterial,
  34576. MeshToonMaterial,
  34577. MeshNormalMaterial,
  34578. MeshLambertMaterial,
  34579. MeshDepthMaterial,
  34580. MeshDistanceMaterial,
  34581. MeshBasicMaterial,
  34582. MeshMatcapMaterial,
  34583. LineDashedMaterial,
  34584. LineBasicMaterial,
  34585. Material
  34586. };
  34587. return new materialLib[ type ]();
  34588. }
  34589. }
  34590. /**
  34591. * A class with loader utility functions.
  34592. */
  34593. class LoaderUtils {
  34594. /**
  34595. * Extracts the base URL from the given URL.
  34596. *
  34597. * @param {string} url -The URL to extract the base URL from.
  34598. * @return {string} The extracted base URL.
  34599. */
  34600. static extractUrlBase( url ) {
  34601. const index = url.lastIndexOf( '/' );
  34602. if ( index === -1 ) return './';
  34603. return url.slice( 0, index + 1 );
  34604. }
  34605. /**
  34606. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34607. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34608. * string.
  34609. *
  34610. * @param {string} url -The URL to resolve.
  34611. * @param {string} path - The base path for relative URLs to be resolved against.
  34612. * @return {string} The resolved URL.
  34613. */
  34614. static resolveURL( url, path ) {
  34615. // Invalid URL
  34616. if ( typeof url !== 'string' || url === '' ) return '';
  34617. // Host Relative URL
  34618. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34619. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34620. }
  34621. // Absolute URL http://,https://,//
  34622. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34623. // Data URI
  34624. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34625. // Blob URL
  34626. if ( /^blob:.*$/i.test( url ) ) return url;
  34627. // Relative URL
  34628. return path + url;
  34629. }
  34630. }
  34631. /**
  34632. * An instanced version of a geometry.
  34633. */
  34634. class InstancedBufferGeometry extends BufferGeometry {
  34635. /**
  34636. * Constructs a new instanced buffer geometry.
  34637. */
  34638. constructor() {
  34639. super();
  34640. /**
  34641. * This flag can be used for type testing.
  34642. *
  34643. * @type {boolean}
  34644. * @readonly
  34645. * @default true
  34646. */
  34647. this.isInstancedBufferGeometry = true;
  34648. this.type = 'InstancedBufferGeometry';
  34649. /**
  34650. * The instance count.
  34651. *
  34652. * @type {number}
  34653. * @default Infinity
  34654. */
  34655. this.instanceCount = Infinity;
  34656. }
  34657. copy( source ) {
  34658. super.copy( source );
  34659. this.instanceCount = source.instanceCount;
  34660. return this;
  34661. }
  34662. toJSON() {
  34663. const data = super.toJSON();
  34664. data.instanceCount = this.instanceCount;
  34665. data.isInstancedBufferGeometry = true;
  34666. return data;
  34667. }
  34668. }
  34669. /**
  34670. * Class for loading geometries. The files are internally
  34671. * loaded via {@link FileLoader}.
  34672. *
  34673. * ```js
  34674. * const loader = new THREE.BufferGeometryLoader();
  34675. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34676. *
  34677. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34678. * const object = new THREE.Mesh( geometry, material );
  34679. * scene.add( object );
  34680. * ```
  34681. *
  34682. * @augments Loader
  34683. */
  34684. class BufferGeometryLoader extends Loader {
  34685. /**
  34686. * Constructs a new geometry loader.
  34687. *
  34688. * @param {LoadingManager} [manager] - The loading manager.
  34689. */
  34690. constructor( manager ) {
  34691. super( manager );
  34692. }
  34693. /**
  34694. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34695. *
  34696. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34697. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34698. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34699. * @param {onErrorCallback} onError - Executed when errors occur.
  34700. */
  34701. load( url, onLoad, onProgress, onError ) {
  34702. const scope = this;
  34703. const loader = new FileLoader( scope.manager );
  34704. loader.setPath( scope.path );
  34705. loader.setRequestHeader( scope.requestHeader );
  34706. loader.setWithCredentials( scope.withCredentials );
  34707. loader.load( url, function ( text ) {
  34708. try {
  34709. onLoad( scope.parse( JSON.parse( text ) ) );
  34710. } catch ( e ) {
  34711. if ( onError ) {
  34712. onError( e );
  34713. } else {
  34714. console.error( e );
  34715. }
  34716. scope.manager.itemError( url );
  34717. }
  34718. }, onProgress, onError );
  34719. }
  34720. /**
  34721. * Parses the given JSON object and returns a geometry.
  34722. *
  34723. * @param {Object} json - The serialized geometry.
  34724. * @return {BufferGeometry} The parsed geometry.
  34725. */
  34726. parse( json ) {
  34727. const interleavedBufferMap = {};
  34728. const arrayBufferMap = {};
  34729. function getInterleavedBuffer( json, uuid ) {
  34730. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34731. const interleavedBuffers = json.interleavedBuffers;
  34732. const interleavedBuffer = interleavedBuffers[ uuid ];
  34733. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34734. const array = getTypedArray( interleavedBuffer.type, buffer );
  34735. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34736. ib.uuid = interleavedBuffer.uuid;
  34737. interleavedBufferMap[ uuid ] = ib;
  34738. return ib;
  34739. }
  34740. function getArrayBuffer( json, uuid ) {
  34741. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34742. const arrayBuffers = json.arrayBuffers;
  34743. const arrayBuffer = arrayBuffers[ uuid ];
  34744. const ab = new Uint32Array( arrayBuffer ).buffer;
  34745. arrayBufferMap[ uuid ] = ab;
  34746. return ab;
  34747. }
  34748. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34749. const index = json.data.index;
  34750. if ( index !== undefined ) {
  34751. const typedArray = getTypedArray( index.type, index.array );
  34752. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34753. }
  34754. const attributes = json.data.attributes;
  34755. for ( const key in attributes ) {
  34756. const attribute = attributes[ key ];
  34757. let bufferAttribute;
  34758. if ( attribute.isInterleavedBufferAttribute ) {
  34759. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34760. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34761. } else {
  34762. const typedArray = getTypedArray( attribute.type, attribute.array );
  34763. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34764. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  34765. }
  34766. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34767. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  34768. geometry.setAttribute( key, bufferAttribute );
  34769. }
  34770. const morphAttributes = json.data.morphAttributes;
  34771. if ( morphAttributes ) {
  34772. for ( const key in morphAttributes ) {
  34773. const attributeArray = morphAttributes[ key ];
  34774. const array = [];
  34775. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  34776. const attribute = attributeArray[ i ];
  34777. let bufferAttribute;
  34778. if ( attribute.isInterleavedBufferAttribute ) {
  34779. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34780. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34781. } else {
  34782. const typedArray = getTypedArray( attribute.type, attribute.array );
  34783. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  34784. }
  34785. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34786. array.push( bufferAttribute );
  34787. }
  34788. geometry.morphAttributes[ key ] = array;
  34789. }
  34790. }
  34791. const morphTargetsRelative = json.data.morphTargetsRelative;
  34792. if ( morphTargetsRelative ) {
  34793. geometry.morphTargetsRelative = true;
  34794. }
  34795. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  34796. if ( groups !== undefined ) {
  34797. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  34798. const group = groups[ i ];
  34799. geometry.addGroup( group.start, group.count, group.materialIndex );
  34800. }
  34801. }
  34802. const boundingSphere = json.data.boundingSphere;
  34803. if ( boundingSphere !== undefined ) {
  34804. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  34805. }
  34806. if ( json.name ) geometry.name = json.name;
  34807. if ( json.userData ) geometry.userData = json.userData;
  34808. return geometry;
  34809. }
  34810. }
  34811. /**
  34812. * A loader for loading a JSON resource in the [JSON Object/Scene format]{@link https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4}.
  34813. * The files are internally loaded via {@link FileLoader}.
  34814. *
  34815. * ```js
  34816. * const loader = new THREE.ObjectLoader();
  34817. * const obj = await loader.loadAsync( 'models/json/example.json' );
  34818. * scene.add( obj );
  34819. *
  34820. * // Alternatively, to parse a previously loaded JSON structure
  34821. * const object = await loader.parseAsync( a_json_object );
  34822. * scene.add( object );
  34823. * ```
  34824. *
  34825. * @augments Loader
  34826. */
  34827. class ObjectLoader extends Loader {
  34828. /**
  34829. * Constructs a new object loader.
  34830. *
  34831. * @param {LoadingManager} [manager] - The loading manager.
  34832. */
  34833. constructor( manager ) {
  34834. super( manager );
  34835. }
  34836. /**
  34837. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  34838. *
  34839. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34840. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  34841. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34842. * @param {onErrorCallback} onError - Executed when errors occur.
  34843. */
  34844. load( url, onLoad, onProgress, onError ) {
  34845. const scope = this;
  34846. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34847. this.resourcePath = this.resourcePath || path;
  34848. const loader = new FileLoader( this.manager );
  34849. loader.setPath( this.path );
  34850. loader.setRequestHeader( this.requestHeader );
  34851. loader.setWithCredentials( this.withCredentials );
  34852. loader.load( url, function ( text ) {
  34853. let json = null;
  34854. try {
  34855. json = JSON.parse( text );
  34856. } catch ( error ) {
  34857. if ( onError !== undefined ) onError( error );
  34858. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  34859. return;
  34860. }
  34861. const metadata = json.metadata;
  34862. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34863. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  34864. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34865. return;
  34866. }
  34867. scope.parse( json, onLoad );
  34868. }, onProgress, onError );
  34869. }
  34870. /**
  34871. * Async version of {@link ObjectLoader#load}.
  34872. *
  34873. * @async
  34874. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34875. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34876. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  34877. */
  34878. async loadAsync( url, onProgress ) {
  34879. const scope = this;
  34880. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34881. this.resourcePath = this.resourcePath || path;
  34882. const loader = new FileLoader( this.manager );
  34883. loader.setPath( this.path );
  34884. loader.setRequestHeader( this.requestHeader );
  34885. loader.setWithCredentials( this.withCredentials );
  34886. const text = await loader.loadAsync( url, onProgress );
  34887. const json = JSON.parse( text );
  34888. const metadata = json.metadata;
  34889. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34890. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34891. }
  34892. return await scope.parseAsync( json );
  34893. }
  34894. /**
  34895. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  34896. * but can also be used directly to parse a previously loaded JSON structure.
  34897. *
  34898. * @param {Object} json - The serialized 3D object.
  34899. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  34900. * @return {Object3D} The parsed 3D object.
  34901. */
  34902. parse( json, onLoad ) {
  34903. const animations = this.parseAnimations( json.animations );
  34904. const shapes = this.parseShapes( json.shapes );
  34905. const geometries = this.parseGeometries( json.geometries, shapes );
  34906. const images = this.parseImages( json.images, function () {
  34907. if ( onLoad !== undefined ) onLoad( object );
  34908. } );
  34909. const textures = this.parseTextures( json.textures, images );
  34910. const materials = this.parseMaterials( json.materials, textures );
  34911. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34912. const skeletons = this.parseSkeletons( json.skeletons, object );
  34913. this.bindSkeletons( object, skeletons );
  34914. this.bindLightTargets( object );
  34915. //
  34916. if ( onLoad !== undefined ) {
  34917. let hasImages = false;
  34918. for ( const uuid in images ) {
  34919. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  34920. hasImages = true;
  34921. break;
  34922. }
  34923. }
  34924. if ( hasImages === false ) onLoad( object );
  34925. }
  34926. return object;
  34927. }
  34928. /**
  34929. * Async version of {@link ObjectLoader#parse}.
  34930. *
  34931. * @param {Object} json - The serialized 3D object.
  34932. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  34933. */
  34934. async parseAsync( json ) {
  34935. const animations = this.parseAnimations( json.animations );
  34936. const shapes = this.parseShapes( json.shapes );
  34937. const geometries = this.parseGeometries( json.geometries, shapes );
  34938. const images = await this.parseImagesAsync( json.images );
  34939. const textures = this.parseTextures( json.textures, images );
  34940. const materials = this.parseMaterials( json.materials, textures );
  34941. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34942. const skeletons = this.parseSkeletons( json.skeletons, object );
  34943. this.bindSkeletons( object, skeletons );
  34944. this.bindLightTargets( object );
  34945. return object;
  34946. }
  34947. // internals
  34948. parseShapes( json ) {
  34949. const shapes = {};
  34950. if ( json !== undefined ) {
  34951. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34952. const shape = new Shape().fromJSON( json[ i ] );
  34953. shapes[ shape.uuid ] = shape;
  34954. }
  34955. }
  34956. return shapes;
  34957. }
  34958. parseSkeletons( json, object ) {
  34959. const skeletons = {};
  34960. const bones = {};
  34961. // generate bone lookup table
  34962. object.traverse( function ( child ) {
  34963. if ( child.isBone ) bones[ child.uuid ] = child;
  34964. } );
  34965. // create skeletons
  34966. if ( json !== undefined ) {
  34967. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34968. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  34969. skeletons[ skeleton.uuid ] = skeleton;
  34970. }
  34971. }
  34972. return skeletons;
  34973. }
  34974. parseGeometries( json, shapes ) {
  34975. const geometries = {};
  34976. if ( json !== undefined ) {
  34977. const bufferGeometryLoader = new BufferGeometryLoader();
  34978. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34979. let geometry;
  34980. const data = json[ i ];
  34981. switch ( data.type ) {
  34982. case 'BufferGeometry':
  34983. case 'InstancedBufferGeometry':
  34984. geometry = bufferGeometryLoader.parse( data );
  34985. break;
  34986. default:
  34987. if ( data.type in Geometries ) {
  34988. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  34989. } else {
  34990. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  34991. }
  34992. }
  34993. geometry.uuid = data.uuid;
  34994. if ( data.name !== undefined ) geometry.name = data.name;
  34995. if ( data.userData !== undefined ) geometry.userData = data.userData;
  34996. geometries[ data.uuid ] = geometry;
  34997. }
  34998. }
  34999. return geometries;
  35000. }
  35001. parseMaterials( json, textures ) {
  35002. const cache = {}; // MultiMaterial
  35003. const materials = {};
  35004. if ( json !== undefined ) {
  35005. const loader = new MaterialLoader();
  35006. loader.setTextures( textures );
  35007. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35008. const data = json[ i ];
  35009. if ( cache[ data.uuid ] === undefined ) {
  35010. cache[ data.uuid ] = loader.parse( data );
  35011. }
  35012. materials[ data.uuid ] = cache[ data.uuid ];
  35013. }
  35014. }
  35015. return materials;
  35016. }
  35017. parseAnimations( json ) {
  35018. const animations = {};
  35019. if ( json !== undefined ) {
  35020. for ( let i = 0; i < json.length; i ++ ) {
  35021. const data = json[ i ];
  35022. const clip = AnimationClip.parse( data );
  35023. animations[ clip.uuid ] = clip;
  35024. }
  35025. }
  35026. return animations;
  35027. }
  35028. parseImages( json, onLoad ) {
  35029. const scope = this;
  35030. const images = {};
  35031. let loader;
  35032. function loadImage( url ) {
  35033. scope.manager.itemStart( url );
  35034. return loader.load( url, function () {
  35035. scope.manager.itemEnd( url );
  35036. }, undefined, function () {
  35037. scope.manager.itemError( url );
  35038. scope.manager.itemEnd( url );
  35039. } );
  35040. }
  35041. function deserializeImage( image ) {
  35042. if ( typeof image === 'string' ) {
  35043. const url = image;
  35044. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35045. return loadImage( path );
  35046. } else {
  35047. if ( image.data ) {
  35048. return {
  35049. data: getTypedArray( image.type, image.data ),
  35050. width: image.width,
  35051. height: image.height
  35052. };
  35053. } else {
  35054. return null;
  35055. }
  35056. }
  35057. }
  35058. if ( json !== undefined && json.length > 0 ) {
  35059. const manager = new LoadingManager( onLoad );
  35060. loader = new ImageLoader( manager );
  35061. loader.setCrossOrigin( this.crossOrigin );
  35062. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35063. const image = json[ i ];
  35064. const url = image.url;
  35065. if ( Array.isArray( url ) ) {
  35066. // load array of images e.g CubeTexture
  35067. const imageArray = [];
  35068. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35069. const currentUrl = url[ j ];
  35070. const deserializedImage = deserializeImage( currentUrl );
  35071. if ( deserializedImage !== null ) {
  35072. if ( deserializedImage instanceof HTMLImageElement ) {
  35073. imageArray.push( deserializedImage );
  35074. } else {
  35075. // special case: handle array of data textures for cube textures
  35076. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35077. }
  35078. }
  35079. }
  35080. images[ image.uuid ] = new Source( imageArray );
  35081. } else {
  35082. // load single image
  35083. const deserializedImage = deserializeImage( image.url );
  35084. images[ image.uuid ] = new Source( deserializedImage );
  35085. }
  35086. }
  35087. }
  35088. return images;
  35089. }
  35090. async parseImagesAsync( json ) {
  35091. const scope = this;
  35092. const images = {};
  35093. let loader;
  35094. async function deserializeImage( image ) {
  35095. if ( typeof image === 'string' ) {
  35096. const url = image;
  35097. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35098. return await loader.loadAsync( path );
  35099. } else {
  35100. if ( image.data ) {
  35101. return {
  35102. data: getTypedArray( image.type, image.data ),
  35103. width: image.width,
  35104. height: image.height
  35105. };
  35106. } else {
  35107. return null;
  35108. }
  35109. }
  35110. }
  35111. if ( json !== undefined && json.length > 0 ) {
  35112. loader = new ImageLoader( this.manager );
  35113. loader.setCrossOrigin( this.crossOrigin );
  35114. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35115. const image = json[ i ];
  35116. const url = image.url;
  35117. if ( Array.isArray( url ) ) {
  35118. // load array of images e.g CubeTexture
  35119. const imageArray = [];
  35120. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35121. const currentUrl = url[ j ];
  35122. const deserializedImage = await deserializeImage( currentUrl );
  35123. if ( deserializedImage !== null ) {
  35124. if ( deserializedImage instanceof HTMLImageElement ) {
  35125. imageArray.push( deserializedImage );
  35126. } else {
  35127. // special case: handle array of data textures for cube textures
  35128. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35129. }
  35130. }
  35131. }
  35132. images[ image.uuid ] = new Source( imageArray );
  35133. } else {
  35134. // load single image
  35135. const deserializedImage = await deserializeImage( image.url );
  35136. images[ image.uuid ] = new Source( deserializedImage );
  35137. }
  35138. }
  35139. }
  35140. return images;
  35141. }
  35142. parseTextures( json, images ) {
  35143. function parseConstant( value, type ) {
  35144. if ( typeof value === 'number' ) return value;
  35145. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35146. return type[ value ];
  35147. }
  35148. const textures = {};
  35149. if ( json !== undefined ) {
  35150. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35151. const data = json[ i ];
  35152. if ( data.image === undefined ) {
  35153. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  35154. }
  35155. if ( images[ data.image ] === undefined ) {
  35156. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  35157. }
  35158. const source = images[ data.image ];
  35159. const image = source.data;
  35160. let texture;
  35161. if ( Array.isArray( image ) ) {
  35162. texture = new CubeTexture();
  35163. if ( image.length === 6 ) texture.needsUpdate = true;
  35164. } else {
  35165. if ( image && image.data ) {
  35166. texture = new DataTexture();
  35167. } else {
  35168. texture = new Texture();
  35169. }
  35170. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35171. }
  35172. texture.source = source;
  35173. texture.uuid = data.uuid;
  35174. if ( data.name !== undefined ) texture.name = data.name;
  35175. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35176. if ( data.channel !== undefined ) texture.channel = data.channel;
  35177. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35178. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35179. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35180. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35181. if ( data.wrap !== undefined ) {
  35182. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35183. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35184. }
  35185. if ( data.format !== undefined ) texture.format = data.format;
  35186. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35187. if ( data.type !== undefined ) texture.type = data.type;
  35188. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35189. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35190. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35191. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35192. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35193. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35194. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35195. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35196. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35197. if ( data.userData !== undefined ) texture.userData = data.userData;
  35198. textures[ data.uuid ] = texture;
  35199. }
  35200. }
  35201. return textures;
  35202. }
  35203. parseObject( data, geometries, materials, textures, animations ) {
  35204. let object;
  35205. function getGeometry( name ) {
  35206. if ( geometries[ name ] === undefined ) {
  35207. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  35208. }
  35209. return geometries[ name ];
  35210. }
  35211. function getMaterial( name ) {
  35212. if ( name === undefined ) return undefined;
  35213. if ( Array.isArray( name ) ) {
  35214. const array = [];
  35215. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35216. const uuid = name[ i ];
  35217. if ( materials[ uuid ] === undefined ) {
  35218. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  35219. }
  35220. array.push( materials[ uuid ] );
  35221. }
  35222. return array;
  35223. }
  35224. if ( materials[ name ] === undefined ) {
  35225. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  35226. }
  35227. return materials[ name ];
  35228. }
  35229. function getTexture( uuid ) {
  35230. if ( textures[ uuid ] === undefined ) {
  35231. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  35232. }
  35233. return textures[ uuid ];
  35234. }
  35235. let geometry, material;
  35236. switch ( data.type ) {
  35237. case 'Scene':
  35238. object = new Scene();
  35239. if ( data.background !== undefined ) {
  35240. if ( Number.isInteger( data.background ) ) {
  35241. object.background = new Color( data.background );
  35242. } else {
  35243. object.background = getTexture( data.background );
  35244. }
  35245. }
  35246. if ( data.environment !== undefined ) {
  35247. object.environment = getTexture( data.environment );
  35248. }
  35249. if ( data.fog !== undefined ) {
  35250. if ( data.fog.type === 'Fog' ) {
  35251. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35252. } else if ( data.fog.type === 'FogExp2' ) {
  35253. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35254. }
  35255. if ( data.fog.name !== '' ) {
  35256. object.fog.name = data.fog.name;
  35257. }
  35258. }
  35259. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35260. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35261. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35262. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35263. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35264. break;
  35265. case 'PerspectiveCamera':
  35266. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35267. if ( data.focus !== undefined ) object.focus = data.focus;
  35268. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35269. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35270. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35271. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35272. break;
  35273. case 'OrthographicCamera':
  35274. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35275. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35276. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35277. break;
  35278. case 'AmbientLight':
  35279. object = new AmbientLight( data.color, data.intensity );
  35280. break;
  35281. case 'DirectionalLight':
  35282. object = new DirectionalLight( data.color, data.intensity );
  35283. object.target = data.target || '';
  35284. break;
  35285. case 'PointLight':
  35286. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35287. break;
  35288. case 'RectAreaLight':
  35289. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35290. break;
  35291. case 'SpotLight':
  35292. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35293. object.target = data.target || '';
  35294. break;
  35295. case 'HemisphereLight':
  35296. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35297. break;
  35298. case 'LightProbe':
  35299. object = new LightProbe().fromJSON( data );
  35300. break;
  35301. case 'SkinnedMesh':
  35302. geometry = getGeometry( data.geometry );
  35303. material = getMaterial( data.material );
  35304. object = new SkinnedMesh( geometry, material );
  35305. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35306. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35307. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35308. break;
  35309. case 'Mesh':
  35310. geometry = getGeometry( data.geometry );
  35311. material = getMaterial( data.material );
  35312. object = new Mesh( geometry, material );
  35313. break;
  35314. case 'InstancedMesh':
  35315. geometry = getGeometry( data.geometry );
  35316. material = getMaterial( data.material );
  35317. const count = data.count;
  35318. const instanceMatrix = data.instanceMatrix;
  35319. const instanceColor = data.instanceColor;
  35320. object = new InstancedMesh( geometry, material, count );
  35321. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35322. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35323. break;
  35324. case 'BatchedMesh':
  35325. geometry = getGeometry( data.geometry );
  35326. material = getMaterial( data.material );
  35327. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35328. object.geometry = geometry;
  35329. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35330. object.sortObjects = data.sortObjects;
  35331. object._drawRanges = data.drawRanges;
  35332. object._reservedRanges = data.reservedRanges;
  35333. object._geometryInfo = data.geometryInfo.map( info => {
  35334. let box = null;
  35335. let sphere = null;
  35336. if ( info.boundingBox !== undefined ) {
  35337. box = new Box3().fromJSON( info.boundingBox );
  35338. }
  35339. if ( info.boundingSphere !== undefined ) {
  35340. sphere = new Sphere().fromJSON( info.boundingSphere );
  35341. }
  35342. return {
  35343. ...info,
  35344. boundingBox: box,
  35345. boundingSphere: sphere
  35346. };
  35347. } );
  35348. object._instanceInfo = data.instanceInfo;
  35349. object._availableInstanceIds = data._availableInstanceIds;
  35350. object._availableGeometryIds = data._availableGeometryIds;
  35351. object._nextIndexStart = data.nextIndexStart;
  35352. object._nextVertexStart = data.nextVertexStart;
  35353. object._geometryCount = data.geometryCount;
  35354. object._maxInstanceCount = data.maxInstanceCount;
  35355. object._maxVertexCount = data.maxVertexCount;
  35356. object._maxIndexCount = data.maxIndexCount;
  35357. object._geometryInitialized = data.geometryInitialized;
  35358. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35359. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35360. if ( data.colorsTexture !== undefined ) {
  35361. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35362. }
  35363. if ( data.boundingSphere !== undefined ) {
  35364. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35365. }
  35366. if ( data.boundingBox !== undefined ) {
  35367. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35368. }
  35369. break;
  35370. case 'LOD':
  35371. object = new LOD();
  35372. break;
  35373. case 'Line':
  35374. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35375. break;
  35376. case 'LineLoop':
  35377. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35378. break;
  35379. case 'LineSegments':
  35380. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35381. break;
  35382. case 'PointCloud':
  35383. case 'Points':
  35384. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35385. break;
  35386. case 'Sprite':
  35387. object = new Sprite( getMaterial( data.material ) );
  35388. break;
  35389. case 'Group':
  35390. object = new Group();
  35391. break;
  35392. case 'Bone':
  35393. object = new Bone();
  35394. break;
  35395. default:
  35396. object = new Object3D();
  35397. }
  35398. object.uuid = data.uuid;
  35399. if ( data.name !== undefined ) object.name = data.name;
  35400. if ( data.matrix !== undefined ) {
  35401. object.matrix.fromArray( data.matrix );
  35402. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35403. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35404. } else {
  35405. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35406. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35407. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35408. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35409. }
  35410. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35411. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35412. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35413. if ( data.shadow ) {
  35414. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35415. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35416. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35417. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35418. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35419. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35420. }
  35421. if ( data.visible !== undefined ) object.visible = data.visible;
  35422. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35423. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35424. if ( data.userData !== undefined ) object.userData = data.userData;
  35425. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35426. if ( data.children !== undefined ) {
  35427. const children = data.children;
  35428. for ( let i = 0; i < children.length; i ++ ) {
  35429. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35430. }
  35431. }
  35432. if ( data.animations !== undefined ) {
  35433. const objectAnimations = data.animations;
  35434. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35435. const uuid = objectAnimations[ i ];
  35436. object.animations.push( animations[ uuid ] );
  35437. }
  35438. }
  35439. if ( data.type === 'LOD' ) {
  35440. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35441. const levels = data.levels;
  35442. for ( let l = 0; l < levels.length; l ++ ) {
  35443. const level = levels[ l ];
  35444. const child = object.getObjectByProperty( 'uuid', level.object );
  35445. if ( child !== undefined ) {
  35446. object.addLevel( child, level.distance, level.hysteresis );
  35447. }
  35448. }
  35449. }
  35450. return object;
  35451. }
  35452. bindSkeletons( object, skeletons ) {
  35453. if ( Object.keys( skeletons ).length === 0 ) return;
  35454. object.traverse( function ( child ) {
  35455. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35456. const skeleton = skeletons[ child.skeleton ];
  35457. if ( skeleton === undefined ) {
  35458. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35459. } else {
  35460. child.bind( skeleton, child.bindMatrix );
  35461. }
  35462. }
  35463. } );
  35464. }
  35465. bindLightTargets( object ) {
  35466. object.traverse( function ( child ) {
  35467. if ( child.isDirectionalLight || child.isSpotLight ) {
  35468. const uuid = child.target;
  35469. const target = object.getObjectByProperty( 'uuid', uuid );
  35470. if ( target !== undefined ) {
  35471. child.target = target;
  35472. } else {
  35473. child.target = new Object3D();
  35474. }
  35475. }
  35476. } );
  35477. }
  35478. }
  35479. const TEXTURE_MAPPING = {
  35480. UVMapping: UVMapping,
  35481. CubeReflectionMapping: CubeReflectionMapping,
  35482. CubeRefractionMapping: CubeRefractionMapping,
  35483. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35484. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35485. CubeUVReflectionMapping: CubeUVReflectionMapping
  35486. };
  35487. const TEXTURE_WRAPPING = {
  35488. RepeatWrapping: RepeatWrapping,
  35489. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35490. MirroredRepeatWrapping: MirroredRepeatWrapping
  35491. };
  35492. const TEXTURE_FILTER = {
  35493. NearestFilter: NearestFilter,
  35494. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35495. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35496. LinearFilter: LinearFilter,
  35497. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35498. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35499. };
  35500. const _errorMap = new WeakMap();
  35501. /**
  35502. * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}.
  35503. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35504. * textures for rendering.
  35505. *
  35506. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35507. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  35508. *
  35509. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  35510. *
  35511. * Also note that unlike {@link FileLoader}, this loader avoids multiple concurrent requests to the same URL only if `Cache` is enabled.
  35512. *
  35513. * ```js
  35514. * const loader = new THREE.ImageBitmapLoader();
  35515. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35516. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35517. *
  35518. * const texture = new THREE.Texture( imageBitmap );
  35519. * texture.needsUpdate = true;
  35520. * ```
  35521. *
  35522. * @augments Loader
  35523. */
  35524. class ImageBitmapLoader extends Loader {
  35525. /**
  35526. * Constructs a new image bitmap loader.
  35527. *
  35528. * @param {LoadingManager} [manager] - The loading manager.
  35529. */
  35530. constructor( manager ) {
  35531. super( manager );
  35532. /**
  35533. * This flag can be used for type testing.
  35534. *
  35535. * @type {boolean}
  35536. * @readonly
  35537. * @default true
  35538. */
  35539. this.isImageBitmapLoader = true;
  35540. if ( typeof createImageBitmap === 'undefined' ) {
  35541. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  35542. }
  35543. if ( typeof fetch === 'undefined' ) {
  35544. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  35545. }
  35546. /**
  35547. * Represents the loader options.
  35548. *
  35549. * @type {Object}
  35550. * @default {premultiplyAlpha:'none'}
  35551. */
  35552. this.options = { premultiplyAlpha: 'none' };
  35553. /**
  35554. * Used for aborting requests.
  35555. *
  35556. * @private
  35557. * @type {AbortController}
  35558. */
  35559. this._abortController = new AbortController();
  35560. }
  35561. /**
  35562. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35563. * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
  35564. *
  35565. * @param {Object} options - The loader options to set.
  35566. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35567. */
  35568. setOptions( options ) {
  35569. this.options = options;
  35570. return this;
  35571. }
  35572. /**
  35573. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35574. *
  35575. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35576. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35577. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35578. * @param {onErrorCallback} onError - Executed when errors occur.
  35579. * @return {ImageBitmap|undefined} The image bitmap.
  35580. */
  35581. load( url, onLoad, onProgress, onError ) {
  35582. if ( url === undefined ) url = '';
  35583. if ( this.path !== undefined ) url = this.path + url;
  35584. url = this.manager.resolveURL( url );
  35585. const scope = this;
  35586. const cached = Cache.get( `image-bitmap:${url}` );
  35587. if ( cached !== undefined ) {
  35588. scope.manager.itemStart( url );
  35589. // If cached is a promise, wait for it to resolve
  35590. if ( cached.then ) {
  35591. cached.then( imageBitmap => {
  35592. // check if there is an error for the cached promise
  35593. if ( _errorMap.has( cached ) === true ) {
  35594. if ( onError ) onError( _errorMap.get( cached ) );
  35595. scope.manager.itemError( url );
  35596. scope.manager.itemEnd( url );
  35597. } else {
  35598. if ( onLoad ) onLoad( imageBitmap );
  35599. scope.manager.itemEnd( url );
  35600. return imageBitmap;
  35601. }
  35602. } );
  35603. return;
  35604. }
  35605. // If cached is not a promise (i.e., it's already an imageBitmap)
  35606. setTimeout( function () {
  35607. if ( onLoad ) onLoad( cached );
  35608. scope.manager.itemEnd( url );
  35609. }, 0 );
  35610. return cached;
  35611. }
  35612. const fetchOptions = {};
  35613. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35614. fetchOptions.headers = this.requestHeader;
  35615. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35616. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35617. return res.blob();
  35618. } ).then( function ( blob ) {
  35619. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35620. } ).then( function ( imageBitmap ) {
  35621. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35622. if ( onLoad ) onLoad( imageBitmap );
  35623. scope.manager.itemEnd( url );
  35624. return imageBitmap;
  35625. } ).catch( function ( e ) {
  35626. if ( onError ) onError( e );
  35627. _errorMap.set( promise, e );
  35628. Cache.remove( `image-bitmap:${url}` );
  35629. scope.manager.itemError( url );
  35630. scope.manager.itemEnd( url );
  35631. } );
  35632. Cache.add( `image-bitmap:${url}`, promise );
  35633. scope.manager.itemStart( url );
  35634. }
  35635. /**
  35636. * Aborts ongoing fetch requests.
  35637. *
  35638. * @return {ImageBitmapLoader} A reference to this instance.
  35639. */
  35640. abort() {
  35641. this._abortController.abort();
  35642. this._abortController = new AbortController();
  35643. return this;
  35644. }
  35645. }
  35646. let _context;
  35647. /**
  35648. * Manages the global audio context in the engine.
  35649. *
  35650. * @hideconstructor
  35651. */
  35652. class AudioContext {
  35653. /**
  35654. * Returns the global native audio context.
  35655. *
  35656. * @return {AudioContext} The native audio context.
  35657. */
  35658. static getContext() {
  35659. if ( _context === undefined ) {
  35660. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35661. }
  35662. return _context;
  35663. }
  35664. /**
  35665. * Allows to set the global native audio context from outside.
  35666. *
  35667. * @param {AudioContext} value - The native context to set.
  35668. */
  35669. static setContext( value ) {
  35670. _context = value;
  35671. }
  35672. }
  35673. /**
  35674. * Class for loading audio buffers. Audios are internally
  35675. * loaded via {@link FileLoader}.
  35676. *
  35677. * ```js
  35678. * const audioListener = new THREE.AudioListener();
  35679. * const ambientSound = new THREE.Audio( audioListener );
  35680. *
  35681. * const loader = new THREE.AudioLoader();
  35682. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35683. *
  35684. * ambientSound.setBuffer( audioBuffer );
  35685. * ambientSound.play();
  35686. * ```
  35687. *
  35688. * @augments Loader
  35689. */
  35690. class AudioLoader extends Loader {
  35691. /**
  35692. * Constructs a new audio loader.
  35693. *
  35694. * @param {LoadingManager} [manager] - The loading manager.
  35695. */
  35696. constructor( manager ) {
  35697. super( manager );
  35698. }
  35699. /**
  35700. * Starts loading from the given URL and passes the loaded audio buffer
  35701. * to the `onLoad()` callback.
  35702. *
  35703. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35704. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35705. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35706. * @param {onErrorCallback} onError - Executed when errors occur.
  35707. */
  35708. load( url, onLoad, onProgress, onError ) {
  35709. const scope = this;
  35710. const loader = new FileLoader( this.manager );
  35711. loader.setResponseType( 'arraybuffer' );
  35712. loader.setPath( this.path );
  35713. loader.setRequestHeader( this.requestHeader );
  35714. loader.setWithCredentials( this.withCredentials );
  35715. loader.load( url, function ( buffer ) {
  35716. try {
  35717. // Create a copy of the buffer. The `decodeAudioData` method
  35718. // detaches the buffer when complete, preventing reuse.
  35719. const bufferCopy = buffer.slice( 0 );
  35720. const context = AudioContext.getContext();
  35721. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35722. onLoad( audioBuffer );
  35723. } ).catch( handleError );
  35724. } catch ( e ) {
  35725. handleError( e );
  35726. }
  35727. }, onProgress, onError );
  35728. function handleError( e ) {
  35729. if ( onError ) {
  35730. onError( e );
  35731. } else {
  35732. console.error( e );
  35733. }
  35734. scope.manager.itemError( url );
  35735. }
  35736. }
  35737. }
  35738. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35739. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35740. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35741. /**
  35742. * A special type of camera that uses two perspective cameras with
  35743. * stereoscopic projection. Can be used for rendering stereo effects
  35744. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  35745. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  35746. */
  35747. class StereoCamera {
  35748. /**
  35749. * Constructs a new stereo camera.
  35750. */
  35751. constructor() {
  35752. /**
  35753. * The type property is used for detecting the object type
  35754. * in context of serialization/deserialization.
  35755. *
  35756. * @type {string}
  35757. * @readonly
  35758. */
  35759. this.type = 'StereoCamera';
  35760. /**
  35761. * The aspect.
  35762. *
  35763. * @type {number}
  35764. * @default 1
  35765. */
  35766. this.aspect = 1;
  35767. /**
  35768. * The eye separation which represents the distance
  35769. * between the left and right camera.
  35770. *
  35771. * @type {number}
  35772. * @default 0.064
  35773. */
  35774. this.eyeSep = 0.064;
  35775. /**
  35776. * The camera representing the left eye. This is added to layer `1` so objects to be
  35777. * rendered by the left camera must also be added to this layer.
  35778. *
  35779. * @type {PerspectiveCamera}
  35780. */
  35781. this.cameraL = new PerspectiveCamera();
  35782. this.cameraL.layers.enable( 1 );
  35783. this.cameraL.matrixAutoUpdate = false;
  35784. /**
  35785. * The camera representing the right eye. This is added to layer `2` so objects to be
  35786. * rendered by the right camera must also be added to this layer.
  35787. *
  35788. * @type {PerspectiveCamera}
  35789. */
  35790. this.cameraR = new PerspectiveCamera();
  35791. this.cameraR.layers.enable( 2 );
  35792. this.cameraR.matrixAutoUpdate = false;
  35793. this._cache = {
  35794. focus: null,
  35795. fov: null,
  35796. aspect: null,
  35797. near: null,
  35798. far: null,
  35799. zoom: null,
  35800. eyeSep: null
  35801. };
  35802. }
  35803. /**
  35804. * Updates the stereo camera based on the given perspective camera.
  35805. *
  35806. * @param {PerspectiveCamera} camera - The perspective camera.
  35807. */
  35808. update( camera ) {
  35809. const cache = this._cache;
  35810. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  35811. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  35812. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  35813. if ( needsUpdate ) {
  35814. cache.focus = camera.focus;
  35815. cache.fov = camera.fov;
  35816. cache.aspect = camera.aspect * this.aspect;
  35817. cache.near = camera.near;
  35818. cache.far = camera.far;
  35819. cache.zoom = camera.zoom;
  35820. cache.eyeSep = this.eyeSep;
  35821. // Off-axis stereoscopic effect based on
  35822. // http://paulbourke.net/stereographics/stereorender/
  35823. _projectionMatrix.copy( camera.projectionMatrix );
  35824. const eyeSepHalf = cache.eyeSep / 2;
  35825. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  35826. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  35827. let xmin, xmax;
  35828. // translate xOffset
  35829. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  35830. _eyeRight.elements[ 12 ] = eyeSepHalf;
  35831. // for left eye
  35832. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  35833. xmax = ymax * cache.aspect + eyeSepOnProjection;
  35834. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35835. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35836. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  35837. // for right eye
  35838. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  35839. xmax = ymax * cache.aspect - eyeSepOnProjection;
  35840. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35841. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35842. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  35843. }
  35844. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  35845. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  35846. }
  35847. }
  35848. /**
  35849. * This type of camera can be used in order to efficiently render a scene with a
  35850. * predefined set of cameras. This is an important performance aspect for
  35851. * rendering VR scenes.
  35852. *
  35853. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  35854. * to define for each sub camera the `viewport` property which determines the
  35855. * part of the viewport that is rendered with this camera.
  35856. *
  35857. * @augments PerspectiveCamera
  35858. */
  35859. class ArrayCamera extends PerspectiveCamera {
  35860. /**
  35861. * Constructs a new array camera.
  35862. *
  35863. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  35864. */
  35865. constructor( array = [] ) {
  35866. super();
  35867. /**
  35868. * This flag can be used for type testing.
  35869. *
  35870. * @type {boolean}
  35871. * @readonly
  35872. * @default true
  35873. */
  35874. this.isArrayCamera = true;
  35875. /**
  35876. * Whether this camera is used with multiview rendering or not.
  35877. *
  35878. * @type {boolean}
  35879. * @readonly
  35880. * @default false
  35881. */
  35882. this.isMultiViewCamera = false;
  35883. /**
  35884. * An array of perspective sub cameras.
  35885. *
  35886. * @type {Array<PerspectiveCamera>}
  35887. */
  35888. this.cameras = array;
  35889. }
  35890. }
  35891. /**
  35892. * Class for keeping track of time.
  35893. */
  35894. class Clock {
  35895. /**
  35896. * Constructs a new clock.
  35897. *
  35898. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  35899. * `getDelta()` is called for the first time.
  35900. */
  35901. constructor( autoStart = true ) {
  35902. /**
  35903. * If set to `true`, the clock starts automatically when `getDelta()` is called
  35904. * for the first time.
  35905. *
  35906. * @type {boolean}
  35907. * @default true
  35908. */
  35909. this.autoStart = autoStart;
  35910. /**
  35911. * Holds the time at which the clock's `start()` method was last called.
  35912. *
  35913. * @type {number}
  35914. * @default 0
  35915. */
  35916. this.startTime = 0;
  35917. /**
  35918. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  35919. * `getDelta()` methods were last called.
  35920. *
  35921. * @type {number}
  35922. * @default 0
  35923. */
  35924. this.oldTime = 0;
  35925. /**
  35926. * Keeps track of the total time that the clock has been running.
  35927. *
  35928. * @type {number}
  35929. * @default 0
  35930. */
  35931. this.elapsedTime = 0;
  35932. /**
  35933. * Whether the clock is running or not.
  35934. *
  35935. * @type {boolean}
  35936. * @default true
  35937. */
  35938. this.running = false;
  35939. }
  35940. /**
  35941. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  35942. * called by the class.
  35943. */
  35944. start() {
  35945. this.startTime = performance.now();
  35946. this.oldTime = this.startTime;
  35947. this.elapsedTime = 0;
  35948. this.running = true;
  35949. }
  35950. /**
  35951. * Stops the clock.
  35952. */
  35953. stop() {
  35954. this.getElapsedTime();
  35955. this.running = false;
  35956. this.autoStart = false;
  35957. }
  35958. /**
  35959. * Returns the elapsed time in seconds.
  35960. *
  35961. * @return {number} The elapsed time.
  35962. */
  35963. getElapsedTime() {
  35964. this.getDelta();
  35965. return this.elapsedTime;
  35966. }
  35967. /**
  35968. * Returns the delta time in seconds.
  35969. *
  35970. * @return {number} The delta time.
  35971. */
  35972. getDelta() {
  35973. let diff = 0;
  35974. if ( this.autoStart && ! this.running ) {
  35975. this.start();
  35976. return 0;
  35977. }
  35978. if ( this.running ) {
  35979. const newTime = performance.now();
  35980. diff = ( newTime - this.oldTime ) / 1000;
  35981. this.oldTime = newTime;
  35982. this.elapsedTime += diff;
  35983. }
  35984. return diff;
  35985. }
  35986. }
  35987. const _position$1 = /*@__PURE__*/ new Vector3();
  35988. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  35989. const _scale$1 = /*@__PURE__*/ new Vector3();
  35990. const _forward = /*@__PURE__*/ new Vector3();
  35991. const _up = /*@__PURE__*/ new Vector3();
  35992. /**
  35993. * The class represents a virtual listener of the all positional and non-positional audio effects
  35994. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  35995. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  35996. *
  35997. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  35998. * camera represents the 3D transformation of the listener.
  35999. *
  36000. * @augments Object3D
  36001. */
  36002. class AudioListener extends Object3D {
  36003. /**
  36004. * Constructs a new audio listener.
  36005. */
  36006. constructor() {
  36007. super();
  36008. this.type = 'AudioListener';
  36009. /**
  36010. * The native audio context.
  36011. *
  36012. * @type {AudioContext}
  36013. * @readonly
  36014. */
  36015. this.context = AudioContext.getContext();
  36016. /**
  36017. * The gain node used for volume control.
  36018. *
  36019. * @type {GainNode}
  36020. * @readonly
  36021. */
  36022. this.gain = this.context.createGain();
  36023. this.gain.connect( this.context.destination );
  36024. /**
  36025. * An optional filter.
  36026. *
  36027. * Defined via {@link AudioListener#setFilter}.
  36028. *
  36029. * @type {?AudioNode}
  36030. * @default null
  36031. * @readonly
  36032. */
  36033. this.filter = null;
  36034. /**
  36035. * Time delta values required for `linearRampToValueAtTime()` usage.
  36036. *
  36037. * @type {number}
  36038. * @default 0
  36039. * @readonly
  36040. */
  36041. this.timeDelta = 0;
  36042. // private
  36043. this._clock = new Clock();
  36044. }
  36045. /**
  36046. * Returns the listener's input node.
  36047. *
  36048. * This method is used by other audio nodes to connect to this listener.
  36049. *
  36050. * @return {GainNode} The input node.
  36051. */
  36052. getInput() {
  36053. return this.gain;
  36054. }
  36055. /**
  36056. * Removes the current filter from this listener.
  36057. *
  36058. * @return {AudioListener} A reference to this listener.
  36059. */
  36060. removeFilter() {
  36061. if ( this.filter !== null ) {
  36062. this.gain.disconnect( this.filter );
  36063. this.filter.disconnect( this.context.destination );
  36064. this.gain.connect( this.context.destination );
  36065. this.filter = null;
  36066. }
  36067. return this;
  36068. }
  36069. /**
  36070. * Returns the current set filter.
  36071. *
  36072. * @return {?AudioNode} The filter.
  36073. */
  36074. getFilter() {
  36075. return this.filter;
  36076. }
  36077. /**
  36078. * Sets the given filter to this listener.
  36079. *
  36080. * @param {AudioNode} value - The filter to set.
  36081. * @return {AudioListener} A reference to this listener.
  36082. */
  36083. setFilter( value ) {
  36084. if ( this.filter !== null ) {
  36085. this.gain.disconnect( this.filter );
  36086. this.filter.disconnect( this.context.destination );
  36087. } else {
  36088. this.gain.disconnect( this.context.destination );
  36089. }
  36090. this.filter = value;
  36091. this.gain.connect( this.filter );
  36092. this.filter.connect( this.context.destination );
  36093. return this;
  36094. }
  36095. /**
  36096. * Returns the applications master volume.
  36097. *
  36098. * @return {number} The master volume.
  36099. */
  36100. getMasterVolume() {
  36101. return this.gain.gain.value;
  36102. }
  36103. /**
  36104. * Sets the applications master volume. This volume setting affects
  36105. * all audio nodes in the scene.
  36106. *
  36107. * @param {number} value - The master volume to set.
  36108. * @return {AudioListener} A reference to this listener.
  36109. */
  36110. setMasterVolume( value ) {
  36111. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36112. return this;
  36113. }
  36114. updateMatrixWorld( force ) {
  36115. super.updateMatrixWorld( force );
  36116. const listener = this.context.listener;
  36117. this.timeDelta = this._clock.getDelta();
  36118. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36119. // the initial forward and up directions must be orthogonal
  36120. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36121. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36122. if ( listener.positionX ) {
  36123. // code path for Chrome (see #14393)
  36124. const endTime = this.context.currentTime + this.timeDelta;
  36125. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36126. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36127. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36128. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36129. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36130. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36131. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36132. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36133. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36134. } else {
  36135. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36136. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36137. }
  36138. }
  36139. }
  36140. /**
  36141. * Represents a non-positional ( global ) audio object.
  36142. *
  36143. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  36144. *
  36145. * ```js
  36146. * // create an AudioListener and add it to the camera
  36147. * const listener = new THREE.AudioListener();
  36148. * camera.add( listener );
  36149. *
  36150. * // create a global audio source
  36151. * const sound = new THREE.Audio( listener );
  36152. *
  36153. * // load a sound and set it as the Audio object's buffer
  36154. * const audioLoader = new THREE.AudioLoader();
  36155. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36156. * sound.setBuffer( buffer );
  36157. * sound.setLoop( true );
  36158. * sound.setVolume( 0.5 );
  36159. * sound.play();
  36160. * });
  36161. * ```
  36162. *
  36163. * @augments Object3D
  36164. */
  36165. class Audio extends Object3D {
  36166. /**
  36167. * Constructs a new audio.
  36168. *
  36169. * @param {AudioListener} listener - The global audio listener.
  36170. */
  36171. constructor( listener ) {
  36172. super();
  36173. this.type = 'Audio';
  36174. /**
  36175. * The global audio listener.
  36176. *
  36177. * @type {AudioListener}
  36178. * @readonly
  36179. */
  36180. this.listener = listener;
  36181. /**
  36182. * The audio context.
  36183. *
  36184. * @type {AudioContext}
  36185. * @readonly
  36186. */
  36187. this.context = listener.context;
  36188. /**
  36189. * The gain node used for volume control.
  36190. *
  36191. * @type {GainNode}
  36192. * @readonly
  36193. */
  36194. this.gain = this.context.createGain();
  36195. this.gain.connect( listener.getInput() );
  36196. /**
  36197. * Whether to start playback automatically or not.
  36198. *
  36199. * @type {boolean}
  36200. * @default false
  36201. */
  36202. this.autoplay = false;
  36203. /**
  36204. * A reference to an audio buffer.
  36205. *
  36206. * Defined via {@link Audio#setBuffer}.
  36207. *
  36208. * @type {?AudioBuffer}
  36209. * @default null
  36210. * @readonly
  36211. */
  36212. this.buffer = null;
  36213. /**
  36214. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36215. * +/- 1200 is an octave.
  36216. *
  36217. * Defined via {@link Audio#setDetune}.
  36218. *
  36219. * @type {number}
  36220. * @default 0
  36221. * @readonly
  36222. */
  36223. this.detune = 0;
  36224. /**
  36225. * Whether the audio should loop or not.
  36226. *
  36227. * Defined via {@link Audio#setLoop}.
  36228. *
  36229. * @type {boolean}
  36230. * @default false
  36231. * @readonly
  36232. */
  36233. this.loop = false;
  36234. /**
  36235. * Defines where in the audio buffer the replay should
  36236. * start, in seconds.
  36237. *
  36238. * @type {number}
  36239. * @default 0
  36240. */
  36241. this.loopStart = 0;
  36242. /**
  36243. * Defines where in the audio buffer the replay should
  36244. * stop, in seconds.
  36245. *
  36246. * @type {number}
  36247. * @default 0
  36248. */
  36249. this.loopEnd = 0;
  36250. /**
  36251. * An offset to the time within the audio buffer the playback
  36252. * should begin, in seconds.
  36253. *
  36254. * @type {number}
  36255. * @default 0
  36256. */
  36257. this.offset = 0;
  36258. /**
  36259. * Overrides the default duration of the audio.
  36260. *
  36261. * @type {undefined|number}
  36262. * @default undefined
  36263. */
  36264. this.duration = undefined;
  36265. /**
  36266. * The playback speed.
  36267. *
  36268. * Defined via {@link Audio#setPlaybackRate}.
  36269. *
  36270. * @type {number}
  36271. * @readonly
  36272. * @default 1
  36273. */
  36274. this.playbackRate = 1;
  36275. /**
  36276. * Indicates whether the audio is playing or not.
  36277. *
  36278. * This flag will be automatically set when using {@link Audio#play},
  36279. * {@link Audio#pause}, {@link Audio#stop}.
  36280. *
  36281. * @type {boolean}
  36282. * @readonly
  36283. * @default false
  36284. */
  36285. this.isPlaying = false;
  36286. /**
  36287. * Indicates whether the audio playback can be controlled
  36288. * with method like {@link Audio#play} or {@link Audio#pause}.
  36289. *
  36290. * This flag will be automatically set when audio sources are
  36291. * defined.
  36292. *
  36293. * @type {boolean}
  36294. * @readonly
  36295. * @default true
  36296. */
  36297. this.hasPlaybackControl = true;
  36298. /**
  36299. * Holds a reference to the current audio source.
  36300. *
  36301. * The property is automatically by one of the `set*()` methods.
  36302. *
  36303. * @type {?AudioNode}
  36304. * @readonly
  36305. * @default null
  36306. */
  36307. this.source = null;
  36308. /**
  36309. * Defines the source type.
  36310. *
  36311. * The property is automatically by one of the `set*()` methods.
  36312. *
  36313. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36314. * @readonly
  36315. * @default 'empty'
  36316. */
  36317. this.sourceType = 'empty';
  36318. this._startedAt = 0;
  36319. this._progress = 0;
  36320. this._connected = false;
  36321. /**
  36322. * Can be used to apply a variety of low-order filters to create
  36323. * more complex sound effects e.g. via `BiquadFilterNode`.
  36324. *
  36325. * The property is automatically set by {@link Audio#setFilters}.
  36326. *
  36327. * @type {Array<AudioNode>}
  36328. * @readonly
  36329. */
  36330. this.filters = [];
  36331. }
  36332. /**
  36333. * Returns the output audio node.
  36334. *
  36335. * @return {GainNode} The output node.
  36336. */
  36337. getOutput() {
  36338. return this.gain;
  36339. }
  36340. /**
  36341. * Sets the given audio node as the source of this instance.
  36342. *
  36343. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36344. *
  36345. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36346. * @return {Audio} A reference to this instance.
  36347. */
  36348. setNodeSource( audioNode ) {
  36349. this.hasPlaybackControl = false;
  36350. this.sourceType = 'audioNode';
  36351. this.source = audioNode;
  36352. this.connect();
  36353. return this;
  36354. }
  36355. /**
  36356. * Sets the given media element as the source of this instance.
  36357. *
  36358. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36359. *
  36360. * @param {HTMLMediaElement} mediaElement - The media element.
  36361. * @return {Audio} A reference to this instance.
  36362. */
  36363. setMediaElementSource( mediaElement ) {
  36364. this.hasPlaybackControl = false;
  36365. this.sourceType = 'mediaNode';
  36366. this.source = this.context.createMediaElementSource( mediaElement );
  36367. this.connect();
  36368. return this;
  36369. }
  36370. /**
  36371. * Sets the given media stream as the source of this instance.
  36372. *
  36373. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36374. *
  36375. * @param {MediaStream} mediaStream - The media stream.
  36376. * @return {Audio} A reference to this instance.
  36377. */
  36378. setMediaStreamSource( mediaStream ) {
  36379. this.hasPlaybackControl = false;
  36380. this.sourceType = 'mediaStreamNode';
  36381. this.source = this.context.createMediaStreamSource( mediaStream );
  36382. this.connect();
  36383. return this;
  36384. }
  36385. /**
  36386. * Sets the given audio buffer as the source of this instance.
  36387. *
  36388. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36389. *
  36390. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36391. * @return {Audio} A reference to this instance.
  36392. */
  36393. setBuffer( audioBuffer ) {
  36394. this.buffer = audioBuffer;
  36395. this.sourceType = 'buffer';
  36396. if ( this.autoplay ) this.play();
  36397. return this;
  36398. }
  36399. /**
  36400. * Starts the playback of the audio.
  36401. *
  36402. * Can only be used with compatible audio sources that allow playback control.
  36403. *
  36404. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36405. * @return {Audio|undefined} A reference to this instance.
  36406. */
  36407. play( delay = 0 ) {
  36408. if ( this.isPlaying === true ) {
  36409. console.warn( 'THREE.Audio: Audio is already playing.' );
  36410. return;
  36411. }
  36412. if ( this.hasPlaybackControl === false ) {
  36413. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36414. return;
  36415. }
  36416. this._startedAt = this.context.currentTime + delay;
  36417. const source = this.context.createBufferSource();
  36418. source.buffer = this.buffer;
  36419. source.loop = this.loop;
  36420. source.loopStart = this.loopStart;
  36421. source.loopEnd = this.loopEnd;
  36422. source.onended = this.onEnded.bind( this );
  36423. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36424. this.isPlaying = true;
  36425. this.source = source;
  36426. this.setDetune( this.detune );
  36427. this.setPlaybackRate( this.playbackRate );
  36428. return this.connect();
  36429. }
  36430. /**
  36431. * Pauses the playback of the audio.
  36432. *
  36433. * Can only be used with compatible audio sources that allow playback control.
  36434. *
  36435. * @return {Audio|undefined} A reference to this instance.
  36436. */
  36437. pause() {
  36438. if ( this.hasPlaybackControl === false ) {
  36439. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36440. return;
  36441. }
  36442. if ( this.isPlaying === true ) {
  36443. // update current progress
  36444. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36445. if ( this.loop === true ) {
  36446. // ensure _progress does not exceed duration with looped audios
  36447. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36448. }
  36449. this.source.stop();
  36450. this.source.onended = null;
  36451. this.isPlaying = false;
  36452. }
  36453. return this;
  36454. }
  36455. /**
  36456. * Stops the playback of the audio.
  36457. *
  36458. * Can only be used with compatible audio sources that allow playback control.
  36459. *
  36460. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36461. * @return {Audio|undefined} A reference to this instance.
  36462. */
  36463. stop( delay = 0 ) {
  36464. if ( this.hasPlaybackControl === false ) {
  36465. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36466. return;
  36467. }
  36468. this._progress = 0;
  36469. if ( this.source !== null ) {
  36470. this.source.stop( this.context.currentTime + delay );
  36471. this.source.onended = null;
  36472. }
  36473. this.isPlaying = false;
  36474. return this;
  36475. }
  36476. /**
  36477. * Connects to the audio source. This is used internally on
  36478. * initialisation and when setting / removing filters.
  36479. *
  36480. * @return {Audio} A reference to this instance.
  36481. */
  36482. connect() {
  36483. if ( this.filters.length > 0 ) {
  36484. this.source.connect( this.filters[ 0 ] );
  36485. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36486. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36487. }
  36488. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36489. } else {
  36490. this.source.connect( this.getOutput() );
  36491. }
  36492. this._connected = true;
  36493. return this;
  36494. }
  36495. /**
  36496. * Disconnects to the audio source. This is used internally on
  36497. * initialisation and when setting / removing filters.
  36498. *
  36499. * @return {Audio|undefined} A reference to this instance.
  36500. */
  36501. disconnect() {
  36502. if ( this._connected === false ) {
  36503. return;
  36504. }
  36505. if ( this.filters.length > 0 ) {
  36506. this.source.disconnect( this.filters[ 0 ] );
  36507. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36508. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36509. }
  36510. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36511. } else {
  36512. this.source.disconnect( this.getOutput() );
  36513. }
  36514. this._connected = false;
  36515. return this;
  36516. }
  36517. /**
  36518. * Returns the current set filters.
  36519. *
  36520. * @return {Array<AudioNode>} The list of filters.
  36521. */
  36522. getFilters() {
  36523. return this.filters;
  36524. }
  36525. /**
  36526. * Sets an array of filters and connects them with the audio source.
  36527. *
  36528. * @param {Array<AudioNode>} [value] - A list of filters.
  36529. * @return {Audio} A reference to this instance.
  36530. */
  36531. setFilters( value ) {
  36532. if ( ! value ) value = [];
  36533. if ( this._connected === true ) {
  36534. this.disconnect();
  36535. this.filters = value.slice();
  36536. this.connect();
  36537. } else {
  36538. this.filters = value.slice();
  36539. }
  36540. return this;
  36541. }
  36542. /**
  36543. * Defines the detuning of oscillation in cents.
  36544. *
  36545. * @param {number} value - The detuning of oscillation in cents.
  36546. * @return {Audio} A reference to this instance.
  36547. */
  36548. setDetune( value ) {
  36549. this.detune = value;
  36550. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36551. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36552. }
  36553. return this;
  36554. }
  36555. /**
  36556. * Returns the detuning of oscillation in cents.
  36557. *
  36558. * @return {number} The detuning of oscillation in cents.
  36559. */
  36560. getDetune() {
  36561. return this.detune;
  36562. }
  36563. /**
  36564. * Returns the first filter in the list of filters.
  36565. *
  36566. * @return {AudioNode|undefined} The first filter in the list of filters.
  36567. */
  36568. getFilter() {
  36569. return this.getFilters()[ 0 ];
  36570. }
  36571. /**
  36572. * Applies a single filter node to the audio.
  36573. *
  36574. * @param {AudioNode} [filter] - The filter to set.
  36575. * @return {Audio} A reference to this instance.
  36576. */
  36577. setFilter( filter ) {
  36578. return this.setFilters( filter ? [ filter ] : [] );
  36579. }
  36580. /**
  36581. * Sets the playback rate.
  36582. *
  36583. * Can only be used with compatible audio sources that allow playback control.
  36584. *
  36585. * @param {number} [value] - The playback rate to set.
  36586. * @return {Audio|undefined} A reference to this instance.
  36587. */
  36588. setPlaybackRate( value ) {
  36589. if ( this.hasPlaybackControl === false ) {
  36590. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36591. return;
  36592. }
  36593. this.playbackRate = value;
  36594. if ( this.isPlaying === true ) {
  36595. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36596. }
  36597. return this;
  36598. }
  36599. /**
  36600. * Returns the current playback rate.
  36601. * @return {number} The playback rate.
  36602. */
  36603. getPlaybackRate() {
  36604. return this.playbackRate;
  36605. }
  36606. /**
  36607. * Automatically called when playback finished.
  36608. */
  36609. onEnded() {
  36610. this.isPlaying = false;
  36611. this._progress = 0;
  36612. }
  36613. /**
  36614. * Returns the loop flag.
  36615. *
  36616. * Can only be used with compatible audio sources that allow playback control.
  36617. *
  36618. * @return {boolean} Whether the audio should loop or not.
  36619. */
  36620. getLoop() {
  36621. if ( this.hasPlaybackControl === false ) {
  36622. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36623. return false;
  36624. }
  36625. return this.loop;
  36626. }
  36627. /**
  36628. * Sets the loop flag.
  36629. *
  36630. * Can only be used with compatible audio sources that allow playback control.
  36631. *
  36632. * @param {boolean} value - Whether the audio should loop or not.
  36633. * @return {Audio|undefined} A reference to this instance.
  36634. */
  36635. setLoop( value ) {
  36636. if ( this.hasPlaybackControl === false ) {
  36637. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36638. return;
  36639. }
  36640. this.loop = value;
  36641. if ( this.isPlaying === true ) {
  36642. this.source.loop = this.loop;
  36643. }
  36644. return this;
  36645. }
  36646. /**
  36647. * Sets the loop start value which defines where in the audio buffer the replay should
  36648. * start, in seconds.
  36649. *
  36650. * @param {number} value - The loop start value.
  36651. * @return {Audio} A reference to this instance.
  36652. */
  36653. setLoopStart( value ) {
  36654. this.loopStart = value;
  36655. return this;
  36656. }
  36657. /**
  36658. * Sets the loop end value which defines where in the audio buffer the replay should
  36659. * stop, in seconds.
  36660. *
  36661. * @param {number} value - The loop end value.
  36662. * @return {Audio} A reference to this instance.
  36663. */
  36664. setLoopEnd( value ) {
  36665. this.loopEnd = value;
  36666. return this;
  36667. }
  36668. /**
  36669. * Returns the volume.
  36670. *
  36671. * @return {number} The volume.
  36672. */
  36673. getVolume() {
  36674. return this.gain.gain.value;
  36675. }
  36676. /**
  36677. * Sets the volume.
  36678. *
  36679. * @param {number} value - The volume to set.
  36680. * @return {Audio} A reference to this instance.
  36681. */
  36682. setVolume( value ) {
  36683. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36684. return this;
  36685. }
  36686. copy( source, recursive ) {
  36687. super.copy( source, recursive );
  36688. if ( source.sourceType !== 'buffer' ) {
  36689. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  36690. return this;
  36691. }
  36692. this.autoplay = source.autoplay;
  36693. this.buffer = source.buffer;
  36694. this.detune = source.detune;
  36695. this.loop = source.loop;
  36696. this.loopStart = source.loopStart;
  36697. this.loopEnd = source.loopEnd;
  36698. this.offset = source.offset;
  36699. this.duration = source.duration;
  36700. this.playbackRate = source.playbackRate;
  36701. this.hasPlaybackControl = source.hasPlaybackControl;
  36702. this.sourceType = source.sourceType;
  36703. this.filters = source.filters.slice();
  36704. return this;
  36705. }
  36706. clone( recursive ) {
  36707. return new this.constructor( this.listener ).copy( this, recursive );
  36708. }
  36709. }
  36710. const _position = /*@__PURE__*/ new Vector3();
  36711. const _quaternion = /*@__PURE__*/ new Quaternion();
  36712. const _scale = /*@__PURE__*/ new Vector3();
  36713. const _orientation = /*@__PURE__*/ new Vector3();
  36714. /**
  36715. * Represents a positional audio object.
  36716. *
  36717. * ```js
  36718. * // create an AudioListener and add it to the camera
  36719. * const listener = new THREE.AudioListener();
  36720. * camera.add( listener );
  36721. *
  36722. * // create the PositionalAudio object (passing in the listener)
  36723. * const sound = new THREE.PositionalAudio( listener );
  36724. *
  36725. * // load a sound and set it as the PositionalAudio object's buffer
  36726. * const audioLoader = new THREE.AudioLoader();
  36727. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36728. * sound.setBuffer( buffer );
  36729. * sound.setRefDistance( 20 );
  36730. * sound.play();
  36731. * });
  36732. *
  36733. * // create an object for the sound to play from
  36734. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36735. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36736. * const mesh = new THREE.Mesh( sphere, material );
  36737. * scene.add( mesh );
  36738. *
  36739. * // finally add the sound to the mesh
  36740. * mesh.add( sound );
  36741. *
  36742. * @augments Audio
  36743. */
  36744. class PositionalAudio extends Audio {
  36745. /**
  36746. * Constructs a positional audio.
  36747. *
  36748. * @param {AudioListener} listener - The global audio listener.
  36749. */
  36750. constructor( listener ) {
  36751. super( listener );
  36752. /**
  36753. * The panner node represents the location, direction, and behavior of an audio
  36754. * source in 3D space.
  36755. *
  36756. * @type {PannerNode}
  36757. * @readonly
  36758. */
  36759. this.panner = this.context.createPanner();
  36760. this.panner.panningModel = 'HRTF';
  36761. this.panner.connect( this.gain );
  36762. }
  36763. connect() {
  36764. super.connect();
  36765. this.panner.connect( this.gain );
  36766. return this;
  36767. }
  36768. disconnect() {
  36769. super.disconnect();
  36770. this.panner.disconnect( this.gain );
  36771. return this;
  36772. }
  36773. getOutput() {
  36774. return this.panner;
  36775. }
  36776. /**
  36777. * Returns the current reference distance.
  36778. *
  36779. * @return {number} The reference distance.
  36780. */
  36781. getRefDistance() {
  36782. return this.panner.refDistance;
  36783. }
  36784. /**
  36785. * Defines the reference distance for reducing volume as the audio source moves
  36786. * further from the listener – i.e. the distance at which the volume reduction
  36787. * starts taking effect.
  36788. *
  36789. * @param {number} value - The reference distance to set.
  36790. * @return {PositionalAudio} A reference to this instance.
  36791. */
  36792. setRefDistance( value ) {
  36793. this.panner.refDistance = value;
  36794. return this;
  36795. }
  36796. /**
  36797. * Returns the current rolloff factor.
  36798. *
  36799. * @return {number} The rolloff factor.
  36800. */
  36801. getRolloffFactor() {
  36802. return this.panner.rolloffFactor;
  36803. }
  36804. /**
  36805. * Defines how quickly the volume is reduced as the source moves away from the listener.
  36806. *
  36807. * @param {number} value - The rolloff factor.
  36808. * @return {PositionalAudio} A reference to this instance.
  36809. */
  36810. setRolloffFactor( value ) {
  36811. this.panner.rolloffFactor = value;
  36812. return this;
  36813. }
  36814. /**
  36815. * Returns the current distance model.
  36816. *
  36817. * @return {('linear'|'inverse'|'exponential')} The distance model.
  36818. */
  36819. getDistanceModel() {
  36820. return this.panner.distanceModel;
  36821. }
  36822. /**
  36823. * Defines which algorithm to use to reduce the volume of the audio source
  36824. * as it moves away from the listener.
  36825. *
  36826. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  36827. * for more details.
  36828. *
  36829. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  36830. * @return {PositionalAudio} A reference to this instance.
  36831. */
  36832. setDistanceModel( value ) {
  36833. this.panner.distanceModel = value;
  36834. return this;
  36835. }
  36836. /**
  36837. * Returns the current max distance.
  36838. *
  36839. * @return {number} The max distance.
  36840. */
  36841. getMaxDistance() {
  36842. return this.panner.maxDistance;
  36843. }
  36844. /**
  36845. * Defines the maximum distance between the audio source and the listener,
  36846. * after which the volume is not reduced any further.
  36847. *
  36848. * This value is used only by the `linear` distance model.
  36849. *
  36850. * @param {number} value - The max distance.
  36851. * @return {PositionalAudio} A reference to this instance.
  36852. */
  36853. setMaxDistance( value ) {
  36854. this.panner.maxDistance = value;
  36855. return this;
  36856. }
  36857. /**
  36858. * Sets the directional cone in which the audio can be listened.
  36859. *
  36860. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  36861. * @param {number} coneOuterAngle - An angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the `coneOuterGain` parameter.
  36862. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  36863. * @return {PositionalAudio} A reference to this instance.
  36864. */
  36865. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  36866. this.panner.coneInnerAngle = coneInnerAngle;
  36867. this.panner.coneOuterAngle = coneOuterAngle;
  36868. this.panner.coneOuterGain = coneOuterGain;
  36869. return this;
  36870. }
  36871. updateMatrixWorld( force ) {
  36872. super.updateMatrixWorld( force );
  36873. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  36874. this.matrixWorld.decompose( _position, _quaternion, _scale );
  36875. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  36876. const panner = this.panner;
  36877. if ( panner.positionX ) {
  36878. // code path for Chrome and Firefox (see #14393)
  36879. const endTime = this.context.currentTime + this.listener.timeDelta;
  36880. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  36881. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  36882. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  36883. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  36884. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  36885. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  36886. } else {
  36887. panner.setPosition( _position.x, _position.y, _position.z );
  36888. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  36889. }
  36890. }
  36891. }
  36892. /**
  36893. * This class can be used to analyse audio data.
  36894. *
  36895. * ```js
  36896. * // create an AudioListener and add it to the camera
  36897. * const listener = new THREE.AudioListener();
  36898. * camera.add( listener );
  36899. *
  36900. * // create an Audio source
  36901. * const sound = new THREE.Audio( listener );
  36902. *
  36903. * // load a sound and set it as the Audio object's buffer
  36904. * const audioLoader = new THREE.AudioLoader();
  36905. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36906. * sound.setBuffer( buffer );
  36907. * sound.setLoop(true);
  36908. * sound.setVolume(0.5);
  36909. * sound.play();
  36910. * });
  36911. *
  36912. * // create an AudioAnalyser, passing in the sound and desired fftSize
  36913. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  36914. *
  36915. * // get the average frequency of the sound
  36916. * const data = analyser.getAverageFrequency();
  36917. * ```
  36918. */
  36919. class AudioAnalyser {
  36920. /**
  36921. * Constructs a new audio analyzer.
  36922. *
  36923. * @param {Audio} audio - The audio to analyze.
  36924. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  36925. */
  36926. constructor( audio, fftSize = 2048 ) {
  36927. /**
  36928. * The global audio listener.
  36929. *
  36930. * @type {AnalyserNode}
  36931. */
  36932. this.analyser = audio.context.createAnalyser();
  36933. this.analyser.fftSize = fftSize;
  36934. /**
  36935. * Holds the analyzed data.
  36936. *
  36937. * @type {Uint8Array}
  36938. */
  36939. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  36940. audio.getOutput().connect( this.analyser );
  36941. }
  36942. /**
  36943. * Returns an array with frequency data of the audio.
  36944. *
  36945. * Each item in the array represents the decibel value for a specific frequency.
  36946. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  36947. * For example, for 48000 sample rate, the last item of the array will represent
  36948. * the decibel value for 24000 Hz.
  36949. *
  36950. * @return {Uint8Array} The frequency data.
  36951. */
  36952. getFrequencyData() {
  36953. this.analyser.getByteFrequencyData( this.data );
  36954. return this.data;
  36955. }
  36956. /**
  36957. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  36958. *
  36959. * @return {number} The average frequency.
  36960. */
  36961. getAverageFrequency() {
  36962. let value = 0;
  36963. const data = this.getFrequencyData();
  36964. for ( let i = 0; i < data.length; i ++ ) {
  36965. value += data[ i ];
  36966. }
  36967. return value / data.length;
  36968. }
  36969. }
  36970. /**
  36971. * Buffered scene graph property that allows weighted accumulation; used internally.
  36972. */
  36973. class PropertyMixer {
  36974. /**
  36975. * Constructs a new property mixer.
  36976. *
  36977. * @param {PropertyBinding} binding - The property binding.
  36978. * @param {string} typeName - The keyframe track type name.
  36979. * @param {number} valueSize - The keyframe track value size.
  36980. */
  36981. constructor( binding, typeName, valueSize ) {
  36982. /**
  36983. * The property binding.
  36984. *
  36985. * @type {PropertyBinding}
  36986. */
  36987. this.binding = binding;
  36988. /**
  36989. * The keyframe track value size.
  36990. *
  36991. * @type {number}
  36992. */
  36993. this.valueSize = valueSize;
  36994. let mixFunction,
  36995. mixFunctionAdditive,
  36996. setIdentity;
  36997. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  36998. //
  36999. // interpolators can use .buffer as their .result
  37000. // the data then goes to 'incoming'
  37001. //
  37002. // 'accu0' and 'accu1' are used frame-interleaved for
  37003. // the cumulative result and are compared to detect
  37004. // changes
  37005. //
  37006. // 'orig' stores the original state of the property
  37007. //
  37008. // 'add' is used for additive cumulative results
  37009. //
  37010. // 'work' is optional and is only present for quaternion types. It is used
  37011. // to store intermediate quaternion multiplication results
  37012. switch ( typeName ) {
  37013. case 'quaternion':
  37014. mixFunction = this._slerp;
  37015. mixFunctionAdditive = this._slerpAdditive;
  37016. setIdentity = this._setAdditiveIdentityQuaternion;
  37017. this.buffer = new Float64Array( valueSize * 6 );
  37018. this._workIndex = 5;
  37019. break;
  37020. case 'string':
  37021. case 'bool':
  37022. mixFunction = this._select;
  37023. // Use the regular mix function and for additive on these types,
  37024. // additive is not relevant for non-numeric types
  37025. mixFunctionAdditive = this._select;
  37026. setIdentity = this._setAdditiveIdentityOther;
  37027. this.buffer = new Array( valueSize * 5 );
  37028. break;
  37029. default:
  37030. mixFunction = this._lerp;
  37031. mixFunctionAdditive = this._lerpAdditive;
  37032. setIdentity = this._setAdditiveIdentityNumeric;
  37033. this.buffer = new Float64Array( valueSize * 5 );
  37034. }
  37035. this._mixBufferRegion = mixFunction;
  37036. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37037. this._setIdentity = setIdentity;
  37038. this._origIndex = 3;
  37039. this._addIndex = 4;
  37040. /**
  37041. * TODO
  37042. *
  37043. * @type {number}
  37044. * @default 0
  37045. */
  37046. this.cumulativeWeight = 0;
  37047. /**
  37048. * TODO
  37049. *
  37050. * @type {number}
  37051. * @default 0
  37052. */
  37053. this.cumulativeWeightAdditive = 0;
  37054. /**
  37055. * TODO
  37056. *
  37057. * @type {number}
  37058. * @default 0
  37059. */
  37060. this.useCount = 0;
  37061. /**
  37062. * TODO
  37063. *
  37064. * @type {number}
  37065. * @default 0
  37066. */
  37067. this.referenceCount = 0;
  37068. }
  37069. /**
  37070. * Accumulates data in the `incoming` region into `accu<i>`.
  37071. *
  37072. * @param {number} accuIndex - The accumulation index.
  37073. * @param {number} weight - The weight.
  37074. */
  37075. accumulate( accuIndex, weight ) {
  37076. // note: happily accumulating nothing when weight = 0, the caller knows
  37077. // the weight and shouldn't have made the call in the first place
  37078. const buffer = this.buffer,
  37079. stride = this.valueSize,
  37080. offset = accuIndex * stride + stride;
  37081. let currentWeight = this.cumulativeWeight;
  37082. if ( currentWeight === 0 ) {
  37083. // accuN := incoming * weight
  37084. for ( let i = 0; i !== stride; ++ i ) {
  37085. buffer[ offset + i ] = buffer[ i ];
  37086. }
  37087. currentWeight = weight;
  37088. } else {
  37089. // accuN := accuN + incoming * weight
  37090. currentWeight += weight;
  37091. const mix = weight / currentWeight;
  37092. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37093. }
  37094. this.cumulativeWeight = currentWeight;
  37095. }
  37096. /**
  37097. * Accumulates data in the `incoming` region into `add`.
  37098. *
  37099. * @param {number} weight - The weight.
  37100. */
  37101. accumulateAdditive( weight ) {
  37102. const buffer = this.buffer,
  37103. stride = this.valueSize,
  37104. offset = stride * this._addIndex;
  37105. if ( this.cumulativeWeightAdditive === 0 ) {
  37106. // add = identity
  37107. this._setIdentity();
  37108. }
  37109. // add := add + incoming * weight
  37110. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37111. this.cumulativeWeightAdditive += weight;
  37112. }
  37113. /**
  37114. * Applies the state of `accu<i>` to the binding when accus differ.
  37115. *
  37116. * @param {number} accuIndex - The accumulation index.
  37117. */
  37118. apply( accuIndex ) {
  37119. const stride = this.valueSize,
  37120. buffer = this.buffer,
  37121. offset = accuIndex * stride + stride,
  37122. weight = this.cumulativeWeight,
  37123. weightAdditive = this.cumulativeWeightAdditive,
  37124. binding = this.binding;
  37125. this.cumulativeWeight = 0;
  37126. this.cumulativeWeightAdditive = 0;
  37127. if ( weight < 1 ) {
  37128. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37129. const originalValueOffset = stride * this._origIndex;
  37130. this._mixBufferRegion(
  37131. buffer, offset, originalValueOffset, 1 - weight, stride );
  37132. }
  37133. if ( weightAdditive > 0 ) {
  37134. // accuN := accuN + additive accuN
  37135. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37136. }
  37137. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37138. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37139. // value has changed -> update scene graph
  37140. binding.setValue( buffer, offset );
  37141. break;
  37142. }
  37143. }
  37144. }
  37145. /**
  37146. * Remembers the state of the bound property and copy it to both accus.
  37147. */
  37148. saveOriginalState() {
  37149. const binding = this.binding;
  37150. const buffer = this.buffer,
  37151. stride = this.valueSize,
  37152. originalValueOffset = stride * this._origIndex;
  37153. binding.getValue( buffer, originalValueOffset );
  37154. // accu[0..1] := orig -- initially detect changes against the original
  37155. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37156. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37157. }
  37158. // Add to identity for additive
  37159. this._setIdentity();
  37160. this.cumulativeWeight = 0;
  37161. this.cumulativeWeightAdditive = 0;
  37162. }
  37163. /**
  37164. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37165. */
  37166. restoreOriginalState() {
  37167. const originalValueOffset = this.valueSize * 3;
  37168. this.binding.setValue( this.buffer, originalValueOffset );
  37169. }
  37170. // internals
  37171. _setAdditiveIdentityNumeric() {
  37172. const startIndex = this._addIndex * this.valueSize;
  37173. const endIndex = startIndex + this.valueSize;
  37174. for ( let i = startIndex; i < endIndex; i ++ ) {
  37175. this.buffer[ i ] = 0;
  37176. }
  37177. }
  37178. _setAdditiveIdentityQuaternion() {
  37179. this._setAdditiveIdentityNumeric();
  37180. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37181. }
  37182. _setAdditiveIdentityOther() {
  37183. const startIndex = this._origIndex * this.valueSize;
  37184. const targetIndex = this._addIndex * this.valueSize;
  37185. for ( let i = 0; i < this.valueSize; i ++ ) {
  37186. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37187. }
  37188. }
  37189. // mix functions
  37190. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37191. if ( t >= 0.5 ) {
  37192. for ( let i = 0; i !== stride; ++ i ) {
  37193. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37194. }
  37195. }
  37196. }
  37197. _slerp( buffer, dstOffset, srcOffset, t ) {
  37198. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37199. }
  37200. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37201. const workOffset = this._workIndex * stride;
  37202. // Store result in intermediate buffer offset
  37203. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37204. // Slerp to the intermediate result
  37205. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37206. }
  37207. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37208. const s = 1 - t;
  37209. for ( let i = 0; i !== stride; ++ i ) {
  37210. const j = dstOffset + i;
  37211. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37212. }
  37213. }
  37214. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37215. for ( let i = 0; i !== stride; ++ i ) {
  37216. const j = dstOffset + i;
  37217. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37218. }
  37219. }
  37220. }
  37221. // Characters [].:/ are reserved for track binding syntax.
  37222. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37223. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37224. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37225. // only latin characters, and the unicode \p{L} is not yet supported. So
  37226. // instead, we exclude reserved characters and match everything else.
  37227. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37228. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37229. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37230. // be matched to parse the rest of the track name.
  37231. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37232. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37233. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37234. // Object on target node, and accessor. May not contain reserved
  37235. // characters. Accessor may contain any character except closing bracket.
  37236. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37237. // Property and accessor. May not contain reserved characters. Accessor may
  37238. // contain any non-bracket characters.
  37239. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37240. const _trackRe = new RegExp( ''
  37241. + '^'
  37242. + _directoryRe
  37243. + _nodeRe
  37244. + _objectRe
  37245. + _propertyRe
  37246. + '$'
  37247. );
  37248. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37249. class Composite {
  37250. constructor( targetGroup, path, optionalParsedPath ) {
  37251. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37252. this._targetGroup = targetGroup;
  37253. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37254. }
  37255. getValue( array, offset ) {
  37256. this.bind(); // bind all binding
  37257. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37258. binding = this._bindings[ firstValidIndex ];
  37259. // and only call .getValue on the first
  37260. if ( binding !== undefined ) binding.getValue( array, offset );
  37261. }
  37262. setValue( array, offset ) {
  37263. const bindings = this._bindings;
  37264. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37265. bindings[ i ].setValue( array, offset );
  37266. }
  37267. }
  37268. bind() {
  37269. const bindings = this._bindings;
  37270. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37271. bindings[ i ].bind();
  37272. }
  37273. }
  37274. unbind() {
  37275. const bindings = this._bindings;
  37276. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37277. bindings[ i ].unbind();
  37278. }
  37279. }
  37280. }
  37281. // Note: This class uses a State pattern on a per-method basis:
  37282. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37283. // prototype version of these methods with one that represents
  37284. // the bound state. When the property is not found, the methods
  37285. // become no-ops.
  37286. /**
  37287. * This holds a reference to a real property in the scene graph; used internally.
  37288. */
  37289. class PropertyBinding {
  37290. /**
  37291. * Constructs a new property binding.
  37292. *
  37293. * @param {Object} rootNode - The root node.
  37294. * @param {string} path - The path.
  37295. * @param {?Object} [parsedPath] - The parsed path.
  37296. */
  37297. constructor( rootNode, path, parsedPath ) {
  37298. /**
  37299. * The object path to the animated property.
  37300. *
  37301. * @type {string}
  37302. */
  37303. this.path = path;
  37304. /**
  37305. * An object holding information about the path.
  37306. *
  37307. * @type {Object}
  37308. */
  37309. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37310. /**
  37311. * The object owns the animated property.
  37312. *
  37313. * @type {?Object}
  37314. */
  37315. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37316. /**
  37317. * The root node.
  37318. *
  37319. * @type {Object3D|Skeleton}
  37320. */
  37321. this.rootNode = rootNode;
  37322. // initial state of these methods that calls 'bind'
  37323. this.getValue = this._getValue_unbound;
  37324. this.setValue = this._setValue_unbound;
  37325. }
  37326. /**
  37327. * Factory method for creating a property binding from the given parameters.
  37328. *
  37329. * @static
  37330. * @param {Object} root - The root node.
  37331. * @param {string} path - The path.
  37332. * @param {?Object} [parsedPath] - The parsed path.
  37333. * @return {PropertyBinding|Composite} The created property binding or composite.
  37334. */
  37335. static create( root, path, parsedPath ) {
  37336. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37337. return new PropertyBinding( root, path, parsedPath );
  37338. } else {
  37339. return new PropertyBinding.Composite( root, path, parsedPath );
  37340. }
  37341. }
  37342. /**
  37343. * Replaces spaces with underscores and removes unsupported characters from
  37344. * node names, to ensure compatibility with parseTrackName().
  37345. *
  37346. * @param {string} name - Node name to be sanitized.
  37347. * @return {string} The sanitized node name.
  37348. */
  37349. static sanitizeNodeName( name ) {
  37350. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37351. }
  37352. /**
  37353. * Parses the given track name (an object path to an animated property) and
  37354. * returns an object with information about the path. Matches strings in the following forms:
  37355. *
  37356. * - nodeName.property
  37357. * - nodeName.property[accessor]
  37358. * - nodeName.material.property[accessor]
  37359. * - uuid.property[accessor]
  37360. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37361. * - parentName/nodeName.property
  37362. * - parentName/parentName/nodeName.property[index]
  37363. * - .bone[Armature.DEF_cog].position
  37364. * - scene:helium_balloon_model:helium_balloon_model.position
  37365. *
  37366. * @static
  37367. * @param {string} trackName - The track name to parse.
  37368. * @return {Object} The parsed track name as an object.
  37369. */
  37370. static parseTrackName( trackName ) {
  37371. const matches = _trackRe.exec( trackName );
  37372. if ( matches === null ) {
  37373. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37374. }
  37375. const results = {
  37376. // directoryName: matches[ 1 ], // (tschw) currently unused
  37377. nodeName: matches[ 2 ],
  37378. objectName: matches[ 3 ],
  37379. objectIndex: matches[ 4 ],
  37380. propertyName: matches[ 5 ], // required
  37381. propertyIndex: matches[ 6 ]
  37382. };
  37383. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37384. if ( lastDot !== undefined && lastDot !== -1 ) {
  37385. const objectName = results.nodeName.substring( lastDot + 1 );
  37386. // Object names must be checked against an allowlist. Otherwise, there
  37387. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37388. // 'bar' could be the objectName, or part of a nodeName (which can
  37389. // include '.' characters).
  37390. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37391. results.nodeName = results.nodeName.substring( 0, lastDot );
  37392. results.objectName = objectName;
  37393. }
  37394. }
  37395. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37396. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37397. }
  37398. return results;
  37399. }
  37400. /**
  37401. * Searches for a node in the hierarchy of the given root object by the given
  37402. * node name.
  37403. *
  37404. * @static
  37405. * @param {Object} root - The root object.
  37406. * @param {string|number} nodeName - The name of the node.
  37407. * @return {?Object} The found node. Returns `null` if no object was found.
  37408. */
  37409. static findNode( root, nodeName ) {
  37410. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37411. return root;
  37412. }
  37413. // search into skeleton bones.
  37414. if ( root.skeleton ) {
  37415. const bone = root.skeleton.getBoneByName( nodeName );
  37416. if ( bone !== undefined ) {
  37417. return bone;
  37418. }
  37419. }
  37420. // search into node subtree.
  37421. if ( root.children ) {
  37422. const searchNodeSubtree = function ( children ) {
  37423. for ( let i = 0; i < children.length; i ++ ) {
  37424. const childNode = children[ i ];
  37425. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37426. return childNode;
  37427. }
  37428. const result = searchNodeSubtree( childNode.children );
  37429. if ( result ) return result;
  37430. }
  37431. return null;
  37432. };
  37433. const subTreeNode = searchNodeSubtree( root.children );
  37434. if ( subTreeNode ) {
  37435. return subTreeNode;
  37436. }
  37437. }
  37438. return null;
  37439. }
  37440. // these are used to "bind" a nonexistent property
  37441. _getValue_unavailable() {}
  37442. _setValue_unavailable() {}
  37443. // Getters
  37444. _getValue_direct( buffer, offset ) {
  37445. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37446. }
  37447. _getValue_array( buffer, offset ) {
  37448. const source = this.resolvedProperty;
  37449. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37450. buffer[ offset ++ ] = source[ i ];
  37451. }
  37452. }
  37453. _getValue_arrayElement( buffer, offset ) {
  37454. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37455. }
  37456. _getValue_toArray( buffer, offset ) {
  37457. this.resolvedProperty.toArray( buffer, offset );
  37458. }
  37459. // Direct
  37460. _setValue_direct( buffer, offset ) {
  37461. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37462. }
  37463. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37464. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37465. this.targetObject.needsUpdate = true;
  37466. }
  37467. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37468. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37469. this.targetObject.matrixWorldNeedsUpdate = true;
  37470. }
  37471. // EntireArray
  37472. _setValue_array( buffer, offset ) {
  37473. const dest = this.resolvedProperty;
  37474. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37475. dest[ i ] = buffer[ offset ++ ];
  37476. }
  37477. }
  37478. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37479. const dest = this.resolvedProperty;
  37480. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37481. dest[ i ] = buffer[ offset ++ ];
  37482. }
  37483. this.targetObject.needsUpdate = true;
  37484. }
  37485. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37486. const dest = this.resolvedProperty;
  37487. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37488. dest[ i ] = buffer[ offset ++ ];
  37489. }
  37490. this.targetObject.matrixWorldNeedsUpdate = true;
  37491. }
  37492. // ArrayElement
  37493. _setValue_arrayElement( buffer, offset ) {
  37494. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37495. }
  37496. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37497. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37498. this.targetObject.needsUpdate = true;
  37499. }
  37500. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37501. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37502. this.targetObject.matrixWorldNeedsUpdate = true;
  37503. }
  37504. // HasToFromArray
  37505. _setValue_fromArray( buffer, offset ) {
  37506. this.resolvedProperty.fromArray( buffer, offset );
  37507. }
  37508. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37509. this.resolvedProperty.fromArray( buffer, offset );
  37510. this.targetObject.needsUpdate = true;
  37511. }
  37512. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37513. this.resolvedProperty.fromArray( buffer, offset );
  37514. this.targetObject.matrixWorldNeedsUpdate = true;
  37515. }
  37516. _getValue_unbound( targetArray, offset ) {
  37517. this.bind();
  37518. this.getValue( targetArray, offset );
  37519. }
  37520. _setValue_unbound( sourceArray, offset ) {
  37521. this.bind();
  37522. this.setValue( sourceArray, offset );
  37523. }
  37524. /**
  37525. * Creates a getter / setter pair for the property tracked by this binding.
  37526. */
  37527. bind() {
  37528. let targetObject = this.node;
  37529. const parsedPath = this.parsedPath;
  37530. const objectName = parsedPath.objectName;
  37531. const propertyName = parsedPath.propertyName;
  37532. let propertyIndex = parsedPath.propertyIndex;
  37533. if ( ! targetObject ) {
  37534. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37535. this.node = targetObject;
  37536. }
  37537. // set fail state so we can just 'return' on error
  37538. this.getValue = this._getValue_unavailable;
  37539. this.setValue = this._setValue_unavailable;
  37540. // ensure there is a value node
  37541. if ( ! targetObject ) {
  37542. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  37543. return;
  37544. }
  37545. if ( objectName ) {
  37546. let objectIndex = parsedPath.objectIndex;
  37547. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37548. switch ( objectName ) {
  37549. case 'materials':
  37550. if ( ! targetObject.material ) {
  37551. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37552. return;
  37553. }
  37554. if ( ! targetObject.material.materials ) {
  37555. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37556. return;
  37557. }
  37558. targetObject = targetObject.material.materials;
  37559. break;
  37560. case 'bones':
  37561. if ( ! targetObject.skeleton ) {
  37562. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37563. return;
  37564. }
  37565. // potential future optimization: skip this if propertyIndex is already an integer
  37566. // and convert the integer string to a true integer.
  37567. targetObject = targetObject.skeleton.bones;
  37568. // support resolving morphTarget names into indices.
  37569. for ( let i = 0; i < targetObject.length; i ++ ) {
  37570. if ( targetObject[ i ].name === objectIndex ) {
  37571. objectIndex = i;
  37572. break;
  37573. }
  37574. }
  37575. break;
  37576. case 'map':
  37577. if ( 'map' in targetObject ) {
  37578. targetObject = targetObject.map;
  37579. break;
  37580. }
  37581. if ( ! targetObject.material ) {
  37582. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37583. return;
  37584. }
  37585. if ( ! targetObject.material.map ) {
  37586. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37587. return;
  37588. }
  37589. targetObject = targetObject.material.map;
  37590. break;
  37591. default:
  37592. if ( targetObject[ objectName ] === undefined ) {
  37593. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  37594. return;
  37595. }
  37596. targetObject = targetObject[ objectName ];
  37597. }
  37598. if ( objectIndex !== undefined ) {
  37599. if ( targetObject[ objectIndex ] === undefined ) {
  37600. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37601. return;
  37602. }
  37603. targetObject = targetObject[ objectIndex ];
  37604. }
  37605. }
  37606. // resolve property
  37607. const nodeProperty = targetObject[ propertyName ];
  37608. if ( nodeProperty === undefined ) {
  37609. const nodeName = parsedPath.nodeName;
  37610. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  37611. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37612. return;
  37613. }
  37614. // determine versioning scheme
  37615. let versioning = this.Versioning.None;
  37616. this.targetObject = targetObject;
  37617. if ( targetObject.isMaterial === true ) {
  37618. versioning = this.Versioning.NeedsUpdate;
  37619. } else if ( targetObject.isObject3D === true ) {
  37620. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37621. }
  37622. // determine how the property gets bound
  37623. let bindingType = this.BindingType.Direct;
  37624. if ( propertyIndex !== undefined ) {
  37625. // access a sub element of the property array (only primitives are supported right now)
  37626. if ( propertyName === 'morphTargetInfluences' ) {
  37627. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37628. // support resolving morphTarget names into indices.
  37629. if ( ! targetObject.geometry ) {
  37630. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37631. return;
  37632. }
  37633. if ( ! targetObject.geometry.morphAttributes ) {
  37634. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37635. return;
  37636. }
  37637. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37638. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37639. }
  37640. }
  37641. bindingType = this.BindingType.ArrayElement;
  37642. this.resolvedProperty = nodeProperty;
  37643. this.propertyIndex = propertyIndex;
  37644. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37645. // must use copy for Object3D.Euler/Quaternion
  37646. bindingType = this.BindingType.HasFromToArray;
  37647. this.resolvedProperty = nodeProperty;
  37648. } else if ( Array.isArray( nodeProperty ) ) {
  37649. bindingType = this.BindingType.EntireArray;
  37650. this.resolvedProperty = nodeProperty;
  37651. } else {
  37652. this.propertyName = propertyName;
  37653. }
  37654. // select getter / setter
  37655. this.getValue = this.GetterByBindingType[ bindingType ];
  37656. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37657. }
  37658. /**
  37659. * Unbinds the property.
  37660. */
  37661. unbind() {
  37662. this.node = null;
  37663. // back to the prototype version of getValue / setValue
  37664. // note: avoiding to mutate the shape of 'this' via 'delete'
  37665. this.getValue = this._getValue_unbound;
  37666. this.setValue = this._setValue_unbound;
  37667. }
  37668. }
  37669. PropertyBinding.Composite = Composite;
  37670. PropertyBinding.prototype.BindingType = {
  37671. Direct: 0,
  37672. EntireArray: 1,
  37673. ArrayElement: 2,
  37674. HasFromToArray: 3
  37675. };
  37676. PropertyBinding.prototype.Versioning = {
  37677. None: 0,
  37678. NeedsUpdate: 1,
  37679. MatrixWorldNeedsUpdate: 2
  37680. };
  37681. PropertyBinding.prototype.GetterByBindingType = [
  37682. PropertyBinding.prototype._getValue_direct,
  37683. PropertyBinding.prototype._getValue_array,
  37684. PropertyBinding.prototype._getValue_arrayElement,
  37685. PropertyBinding.prototype._getValue_toArray,
  37686. ];
  37687. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37688. [
  37689. // Direct
  37690. PropertyBinding.prototype._setValue_direct,
  37691. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37692. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37693. ], [
  37694. // EntireArray
  37695. PropertyBinding.prototype._setValue_array,
  37696. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37697. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37698. ], [
  37699. // ArrayElement
  37700. PropertyBinding.prototype._setValue_arrayElement,
  37701. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37702. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37703. ], [
  37704. // HasToFromArray
  37705. PropertyBinding.prototype._setValue_fromArray,
  37706. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37707. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37708. ]
  37709. ];
  37710. /**
  37711. * A group of objects that receives a shared animation state.
  37712. *
  37713. * Usage:
  37714. *
  37715. * - Add objects you would otherwise pass as 'root' to the
  37716. * constructor or the .clipAction method of AnimationMixer.
  37717. * - Instead pass this object as 'root'.
  37718. * - You can also add and remove objects later when the mixer is running.
  37719. *
  37720. * Note:
  37721. *
  37722. * - Objects of this class appear as one object to the mixer,
  37723. * so cache control of the individual objects must be done on the group.
  37724. *
  37725. * Limitation:
  37726. *
  37727. * - The animated properties must be compatible among the all objects in the group.
  37728. * - A single property can either be controlled through a target group or directly, but not both.
  37729. */
  37730. class AnimationObjectGroup {
  37731. /**
  37732. * Constructs a new animation group.
  37733. *
  37734. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37735. */
  37736. constructor() {
  37737. /**
  37738. * This flag can be used for type testing.
  37739. *
  37740. * @type {boolean}
  37741. * @readonly
  37742. * @default true
  37743. */
  37744. this.isAnimationObjectGroup = true;
  37745. /**
  37746. * The UUID of the 3D object.
  37747. *
  37748. * @type {string}
  37749. * @readonly
  37750. */
  37751. this.uuid = generateUUID();
  37752. // cached objects followed by the active ones
  37753. this._objects = Array.prototype.slice.call( arguments );
  37754. this.nCachedObjects_ = 0; // threshold
  37755. // note: read by PropertyBinding.Composite
  37756. const indices = {};
  37757. this._indicesByUUID = indices; // for bookkeeping
  37758. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37759. indices[ arguments[ i ].uuid ] = i;
  37760. }
  37761. this._paths = []; // inside: string
  37762. this._parsedPaths = []; // inside: { we don't care, here }
  37763. this._bindings = []; // inside: Array< PropertyBinding >
  37764. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  37765. const scope = this;
  37766. this.stats = {
  37767. objects: {
  37768. get total() {
  37769. return scope._objects.length;
  37770. },
  37771. get inUse() {
  37772. return this.total - scope.nCachedObjects_;
  37773. }
  37774. },
  37775. get bindingsPerObject() {
  37776. return scope._bindings.length;
  37777. }
  37778. };
  37779. }
  37780. /**
  37781. * Adds an arbitrary number of objects to this animation group.
  37782. *
  37783. * @param {...Object3D} arguments - The 3D objects to add.
  37784. */
  37785. add() {
  37786. const objects = this._objects,
  37787. indicesByUUID = this._indicesByUUID,
  37788. paths = this._paths,
  37789. parsedPaths = this._parsedPaths,
  37790. bindings = this._bindings,
  37791. nBindings = bindings.length;
  37792. let knownObject = undefined,
  37793. nObjects = objects.length,
  37794. nCachedObjects = this.nCachedObjects_;
  37795. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37796. const object = arguments[ i ],
  37797. uuid = object.uuid;
  37798. let index = indicesByUUID[ uuid ];
  37799. if ( index === undefined ) {
  37800. // unknown object -> add it to the ACTIVE region
  37801. index = nObjects ++;
  37802. indicesByUUID[ uuid ] = index;
  37803. objects.push( object );
  37804. // accounting is done, now do the same for all bindings
  37805. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37806. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  37807. }
  37808. } else if ( index < nCachedObjects ) {
  37809. knownObject = objects[ index ];
  37810. // move existing object to the ACTIVE region
  37811. const firstActiveIndex = -- nCachedObjects,
  37812. lastCachedObject = objects[ firstActiveIndex ];
  37813. indicesByUUID[ lastCachedObject.uuid ] = index;
  37814. objects[ index ] = lastCachedObject;
  37815. indicesByUUID[ uuid ] = firstActiveIndex;
  37816. objects[ firstActiveIndex ] = object;
  37817. // accounting is done, now do the same for all bindings
  37818. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37819. const bindingsForPath = bindings[ j ],
  37820. lastCached = bindingsForPath[ firstActiveIndex ];
  37821. let binding = bindingsForPath[ index ];
  37822. bindingsForPath[ index ] = lastCached;
  37823. if ( binding === undefined ) {
  37824. // since we do not bother to create new bindings
  37825. // for objects that are cached, the binding may
  37826. // or may not exist
  37827. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  37828. }
  37829. bindingsForPath[ firstActiveIndex ] = binding;
  37830. }
  37831. } else if ( objects[ index ] !== knownObject ) {
  37832. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  37833. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  37834. } // else the object is already where we want it to be
  37835. } // for arguments
  37836. this.nCachedObjects_ = nCachedObjects;
  37837. }
  37838. /**
  37839. * Removes an arbitrary number of objects to this animation group
  37840. *
  37841. * @param {...Object3D} arguments - The 3D objects to remove.
  37842. */
  37843. remove() {
  37844. const objects = this._objects,
  37845. indicesByUUID = this._indicesByUUID,
  37846. bindings = this._bindings,
  37847. nBindings = bindings.length;
  37848. let nCachedObjects = this.nCachedObjects_;
  37849. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37850. const object = arguments[ i ],
  37851. uuid = object.uuid,
  37852. index = indicesByUUID[ uuid ];
  37853. if ( index !== undefined && index >= nCachedObjects ) {
  37854. // move existing object into the CACHED region
  37855. const lastCachedIndex = nCachedObjects ++,
  37856. firstActiveObject = objects[ lastCachedIndex ];
  37857. indicesByUUID[ firstActiveObject.uuid ] = index;
  37858. objects[ index ] = firstActiveObject;
  37859. indicesByUUID[ uuid ] = lastCachedIndex;
  37860. objects[ lastCachedIndex ] = object;
  37861. // accounting is done, now do the same for all bindings
  37862. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37863. const bindingsForPath = bindings[ j ],
  37864. firstActive = bindingsForPath[ lastCachedIndex ],
  37865. binding = bindingsForPath[ index ];
  37866. bindingsForPath[ index ] = firstActive;
  37867. bindingsForPath[ lastCachedIndex ] = binding;
  37868. }
  37869. }
  37870. } // for arguments
  37871. this.nCachedObjects_ = nCachedObjects;
  37872. }
  37873. /**
  37874. * Deallocates all memory resources for the passed 3D objects of this animation group.
  37875. *
  37876. * @param {...Object3D} arguments - The 3D objects to uncache.
  37877. */
  37878. uncache() {
  37879. const objects = this._objects,
  37880. indicesByUUID = this._indicesByUUID,
  37881. bindings = this._bindings,
  37882. nBindings = bindings.length;
  37883. let nCachedObjects = this.nCachedObjects_,
  37884. nObjects = objects.length;
  37885. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37886. const object = arguments[ i ],
  37887. uuid = object.uuid,
  37888. index = indicesByUUID[ uuid ];
  37889. if ( index !== undefined ) {
  37890. delete indicesByUUID[ uuid ];
  37891. if ( index < nCachedObjects ) {
  37892. // object is cached, shrink the CACHED region
  37893. const firstActiveIndex = -- nCachedObjects,
  37894. lastCachedObject = objects[ firstActiveIndex ],
  37895. lastIndex = -- nObjects,
  37896. lastObject = objects[ lastIndex ];
  37897. // last cached object takes this object's place
  37898. indicesByUUID[ lastCachedObject.uuid ] = index;
  37899. objects[ index ] = lastCachedObject;
  37900. // last object goes to the activated slot and pop
  37901. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  37902. objects[ firstActiveIndex ] = lastObject;
  37903. objects.pop();
  37904. // accounting is done, now do the same for all bindings
  37905. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37906. const bindingsForPath = bindings[ j ],
  37907. lastCached = bindingsForPath[ firstActiveIndex ],
  37908. last = bindingsForPath[ lastIndex ];
  37909. bindingsForPath[ index ] = lastCached;
  37910. bindingsForPath[ firstActiveIndex ] = last;
  37911. bindingsForPath.pop();
  37912. }
  37913. } else {
  37914. // object is active, just swap with the last and pop
  37915. const lastIndex = -- nObjects,
  37916. lastObject = objects[ lastIndex ];
  37917. if ( lastIndex > 0 ) {
  37918. indicesByUUID[ lastObject.uuid ] = index;
  37919. }
  37920. objects[ index ] = lastObject;
  37921. objects.pop();
  37922. // accounting is done, now do the same for all bindings
  37923. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37924. const bindingsForPath = bindings[ j ];
  37925. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  37926. bindingsForPath.pop();
  37927. }
  37928. } // cached or active
  37929. } // if object is known
  37930. } // for arguments
  37931. this.nCachedObjects_ = nCachedObjects;
  37932. }
  37933. // Internal interface used by befriended PropertyBinding.Composite:
  37934. subscribe_( path, parsedPath ) {
  37935. // returns an array of bindings for the given path that is changed
  37936. // according to the contained objects in the group
  37937. const indicesByPath = this._bindingsIndicesByPath;
  37938. let index = indicesByPath[ path ];
  37939. const bindings = this._bindings;
  37940. if ( index !== undefined ) return bindings[ index ];
  37941. const paths = this._paths,
  37942. parsedPaths = this._parsedPaths,
  37943. objects = this._objects,
  37944. nObjects = objects.length,
  37945. nCachedObjects = this.nCachedObjects_,
  37946. bindingsForPath = new Array( nObjects );
  37947. index = bindings.length;
  37948. indicesByPath[ path ] = index;
  37949. paths.push( path );
  37950. parsedPaths.push( parsedPath );
  37951. bindings.push( bindingsForPath );
  37952. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  37953. const object = objects[ i ];
  37954. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  37955. }
  37956. return bindingsForPath;
  37957. }
  37958. unsubscribe_( path ) {
  37959. // tells the group to forget about a property path and no longer
  37960. // update the array previously obtained with 'subscribe_'
  37961. const indicesByPath = this._bindingsIndicesByPath,
  37962. index = indicesByPath[ path ];
  37963. if ( index !== undefined ) {
  37964. const paths = this._paths,
  37965. parsedPaths = this._parsedPaths,
  37966. bindings = this._bindings,
  37967. lastBindingsIndex = bindings.length - 1,
  37968. lastBindings = bindings[ lastBindingsIndex ],
  37969. lastBindingsPath = path[ lastBindingsIndex ];
  37970. indicesByPath[ lastBindingsPath ] = index;
  37971. bindings[ index ] = lastBindings;
  37972. bindings.pop();
  37973. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  37974. parsedPaths.pop();
  37975. paths[ index ] = paths[ lastBindingsIndex ];
  37976. paths.pop();
  37977. }
  37978. }
  37979. }
  37980. /**
  37981. * An instance of `AnimationAction` schedules the playback of an animation which is
  37982. * stored in {@link AnimationClip}.
  37983. */
  37984. class AnimationAction {
  37985. /**
  37986. * Constructs a new animation action.
  37987. *
  37988. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  37989. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  37990. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  37991. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  37992. */
  37993. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  37994. this._mixer = mixer;
  37995. this._clip = clip;
  37996. this._localRoot = localRoot;
  37997. /**
  37998. * Defines how the animation is blended/combined when two or more animations
  37999. * are simultaneously played.
  38000. *
  38001. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38002. */
  38003. this.blendMode = blendMode;
  38004. const tracks = clip.tracks,
  38005. nTracks = tracks.length,
  38006. interpolants = new Array( nTracks );
  38007. const interpolantSettings = {
  38008. endingStart: ZeroCurvatureEnding,
  38009. endingEnd: ZeroCurvatureEnding
  38010. };
  38011. for ( let i = 0; i !== nTracks; ++ i ) {
  38012. const interpolant = tracks[ i ].createInterpolant( null );
  38013. interpolants[ i ] = interpolant;
  38014. interpolant.settings = interpolantSettings;
  38015. }
  38016. this._interpolantSettings = interpolantSettings;
  38017. this._interpolants = interpolants; // bound by the mixer
  38018. // inside: PropertyMixer (managed by the mixer)
  38019. this._propertyBindings = new Array( nTracks );
  38020. this._cacheIndex = null; // for the memory manager
  38021. this._byClipCacheIndex = null; // for the memory manager
  38022. this._timeScaleInterpolant = null;
  38023. this._weightInterpolant = null;
  38024. /**
  38025. * The loop mode, set via {@link AnimationAction#setLoop}.
  38026. *
  38027. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38028. * @default LoopRepeat
  38029. */
  38030. this.loop = LoopRepeat;
  38031. this._loopCount = -1;
  38032. // global mixer time when the action is to be started
  38033. // it's set back to 'null' upon start of the action
  38034. this._startTime = null;
  38035. /**
  38036. * The local time of this action (in seconds, starting with `0`).
  38037. *
  38038. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38039. * loop state).
  38040. *
  38041. * @type {number}
  38042. * @default Infinity
  38043. */
  38044. this.time = 0;
  38045. /**
  38046. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38047. * animation to pause. Negative values cause the animation to play backwards.
  38048. *
  38049. * @type {number}
  38050. * @default 1
  38051. */
  38052. this.timeScale = 1;
  38053. this._effectiveTimeScale = 1;
  38054. /**
  38055. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38056. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38057. * several actions.
  38058. *
  38059. * @type {number}
  38060. * @default 1
  38061. */
  38062. this.weight = 1;
  38063. this._effectiveWeight = 1;
  38064. /**
  38065. * The number of repetitions of the performed clip over the course of this action.
  38066. * Can be set via {@link AnimationAction#setLoop}.
  38067. *
  38068. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38069. * `THREE:LoopOnce`.
  38070. *
  38071. * @type {number}
  38072. * @default Infinity
  38073. */
  38074. this.repetitions = Infinity;
  38075. /**
  38076. * If set to `true`, the playback of the action is paused.
  38077. *
  38078. * @type {boolean}
  38079. * @default false
  38080. */
  38081. this.paused = false;
  38082. /**
  38083. * If set to `false`, the action is disabled so it has no impact.
  38084. *
  38085. * When the action is re-enabled, the animation continues from its current
  38086. * time (setting `enabled` to `false` doesn't reset the action).
  38087. *
  38088. * @type {boolean}
  38089. * @default true
  38090. */
  38091. this.enabled = true;
  38092. /**
  38093. * If set to true the animation will automatically be paused on its last frame.
  38094. *
  38095. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38096. * to `false` when the last loop of the action has finished, so that this action has
  38097. * no further impact.
  38098. *
  38099. * Note: This member has no impact if the action is interrupted (it
  38100. * has only an effect if its last loop has really finished).
  38101. *
  38102. * @type {boolean}
  38103. * @default false
  38104. */
  38105. this.clampWhenFinished = false;
  38106. /**
  38107. * Enables smooth interpolation without separate clips for start, loop and end.
  38108. *
  38109. * @type {boolean}
  38110. * @default true
  38111. */
  38112. this.zeroSlopeAtStart = true;
  38113. /**
  38114. * Enables smooth interpolation without separate clips for start, loop and end.
  38115. *
  38116. * @type {boolean}
  38117. * @default true
  38118. */
  38119. this.zeroSlopeAtEnd = true;
  38120. }
  38121. /**
  38122. * Starts the playback of the animation.
  38123. *
  38124. * @return {AnimationAction} A reference to this animation action.
  38125. */
  38126. play() {
  38127. this._mixer._activateAction( this );
  38128. return this;
  38129. }
  38130. /**
  38131. * Stops the playback of the animation.
  38132. *
  38133. * @return {AnimationAction} A reference to this animation action.
  38134. */
  38135. stop() {
  38136. this._mixer._deactivateAction( this );
  38137. return this.reset();
  38138. }
  38139. /**
  38140. * Resets the playback of the animation.
  38141. *
  38142. * @return {AnimationAction} A reference to this animation action.
  38143. */
  38144. reset() {
  38145. this.paused = false;
  38146. this.enabled = true;
  38147. this.time = 0; // restart clip
  38148. this._loopCount = -1;// forget previous loops
  38149. this._startTime = null;// forget scheduling
  38150. return this.stopFading().stopWarping();
  38151. }
  38152. /**
  38153. * Returns `true` if the animation is running.
  38154. *
  38155. * @return {boolean} Whether the animation is running or not.
  38156. */
  38157. isRunning() {
  38158. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38159. this._startTime === null && this._mixer._isActiveAction( this );
  38160. }
  38161. /**
  38162. * Returns `true` when {@link AnimationAction#play} has been called.
  38163. *
  38164. * @return {boolean} Whether the animation is scheduled or not.
  38165. */
  38166. isScheduled() {
  38167. return this._mixer._isActiveAction( this );
  38168. }
  38169. /**
  38170. * Defines the time when the animation should start.
  38171. *
  38172. * @param {number} time - The start time in seconds.
  38173. * @return {AnimationAction} A reference to this animation action.
  38174. */
  38175. startAt( time ) {
  38176. this._startTime = time;
  38177. return this;
  38178. }
  38179. /**
  38180. * Configures the loop settings for this action.
  38181. *
  38182. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38183. * @param {number} repetitions - The number of repetitions.
  38184. * @return {AnimationAction} A reference to this animation action.
  38185. */
  38186. setLoop( mode, repetitions ) {
  38187. this.loop = mode;
  38188. this.repetitions = repetitions;
  38189. return this;
  38190. }
  38191. /**
  38192. * Sets the effective weight of this action.
  38193. *
  38194. * An action has no effect and thus an effective weight of zero when the
  38195. * action is disabled.
  38196. *
  38197. * @param {number} weight - The weight to set.
  38198. * @return {AnimationAction} A reference to this animation action.
  38199. */
  38200. setEffectiveWeight( weight ) {
  38201. this.weight = weight;
  38202. // note: same logic as when updated at runtime
  38203. this._effectiveWeight = this.enabled ? weight : 0;
  38204. return this.stopFading();
  38205. }
  38206. /**
  38207. * Returns the effective weight of this action.
  38208. *
  38209. * @return {number} The effective weight.
  38210. */
  38211. getEffectiveWeight() {
  38212. return this._effectiveWeight;
  38213. }
  38214. /**
  38215. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38216. * within the passed time interval.
  38217. *
  38218. * @param {number} duration - The duration of the fade.
  38219. * @return {AnimationAction} A reference to this animation action.
  38220. */
  38221. fadeIn( duration ) {
  38222. return this._scheduleFading( duration, 0, 1 );
  38223. }
  38224. /**
  38225. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38226. * within the passed time interval.
  38227. *
  38228. * @param {number} duration - The duration of the fade.
  38229. * @return {AnimationAction} A reference to this animation action.
  38230. */
  38231. fadeOut( duration ) {
  38232. return this._scheduleFading( duration, 1, 0 );
  38233. }
  38234. /**
  38235. * Causes this action to fade in and the given action to fade out,
  38236. * within the passed time interval.
  38237. *
  38238. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38239. * @param {number} duration - The duration of the fade.
  38240. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38241. * @return {AnimationAction} A reference to this animation action.
  38242. */
  38243. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38244. fadeOutAction.fadeOut( duration );
  38245. this.fadeIn( duration );
  38246. if ( warp === true ) {
  38247. const fadeInDuration = this._clip.duration,
  38248. fadeOutDuration = fadeOutAction._clip.duration,
  38249. startEndRatio = fadeOutDuration / fadeInDuration,
  38250. endStartRatio = fadeInDuration / fadeOutDuration;
  38251. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38252. this.warp( endStartRatio, 1.0, duration );
  38253. }
  38254. return this;
  38255. }
  38256. /**
  38257. * Causes this action to fade out and the given action to fade in,
  38258. * within the passed time interval.
  38259. *
  38260. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38261. * @param {number} duration - The duration of the fade.
  38262. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38263. * @return {AnimationAction} A reference to this animation action.
  38264. */
  38265. crossFadeTo( fadeInAction, duration, warp = false ) {
  38266. return fadeInAction.crossFadeFrom( this, duration, warp );
  38267. }
  38268. /**
  38269. * Stops any fading which is applied to this action.
  38270. *
  38271. * @return {AnimationAction} A reference to this animation action.
  38272. */
  38273. stopFading() {
  38274. const weightInterpolant = this._weightInterpolant;
  38275. if ( weightInterpolant !== null ) {
  38276. this._weightInterpolant = null;
  38277. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38278. }
  38279. return this;
  38280. }
  38281. /**
  38282. * Sets the effective time scale of this action.
  38283. *
  38284. * An action has no effect and thus an effective time scale of zero when the
  38285. * action is paused.
  38286. *
  38287. * @param {number} timeScale - The time scale to set.
  38288. * @return {AnimationAction} A reference to this animation action.
  38289. */
  38290. setEffectiveTimeScale( timeScale ) {
  38291. this.timeScale = timeScale;
  38292. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38293. return this.stopWarping();
  38294. }
  38295. /**
  38296. * Returns the effective time scale of this action.
  38297. *
  38298. * @return {number} The effective time scale.
  38299. */
  38300. getEffectiveTimeScale() {
  38301. return this._effectiveTimeScale;
  38302. }
  38303. /**
  38304. * Sets the duration for a single loop of this action.
  38305. *
  38306. * @param {number} duration - The duration to set.
  38307. * @return {AnimationAction} A reference to this animation action.
  38308. */
  38309. setDuration( duration ) {
  38310. this.timeScale = this._clip.duration / duration;
  38311. return this.stopWarping();
  38312. }
  38313. /**
  38314. * Synchronizes this action with the passed other action.
  38315. *
  38316. * @param {AnimationAction} action - The action to sync with.
  38317. * @return {AnimationAction} A reference to this animation action.
  38318. */
  38319. syncWith( action ) {
  38320. this.time = action.time;
  38321. this.timeScale = action.timeScale;
  38322. return this.stopWarping();
  38323. }
  38324. /**
  38325. * Decelerates this animation's speed to `0` within the passed time interval.
  38326. *
  38327. * @param {number} duration - The duration.
  38328. * @return {AnimationAction} A reference to this animation action.
  38329. */
  38330. halt( duration ) {
  38331. return this.warp( this._effectiveTimeScale, 0, duration );
  38332. }
  38333. /**
  38334. * Changes the playback speed, within the passed time interval, by modifying
  38335. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38336. * `endTimeScale`.
  38337. *
  38338. * @param {number} startTimeScale - The start time scale.
  38339. * @param {number} endTimeScale - The end time scale.
  38340. * @param {number} duration - The duration.
  38341. * @return {AnimationAction} A reference to this animation action.
  38342. */
  38343. warp( startTimeScale, endTimeScale, duration ) {
  38344. const mixer = this._mixer,
  38345. now = mixer.time,
  38346. timeScale = this.timeScale;
  38347. let interpolant = this._timeScaleInterpolant;
  38348. if ( interpolant === null ) {
  38349. interpolant = mixer._lendControlInterpolant();
  38350. this._timeScaleInterpolant = interpolant;
  38351. }
  38352. const times = interpolant.parameterPositions,
  38353. values = interpolant.sampleValues;
  38354. times[ 0 ] = now;
  38355. times[ 1 ] = now + duration;
  38356. values[ 0 ] = startTimeScale / timeScale;
  38357. values[ 1 ] = endTimeScale / timeScale;
  38358. return this;
  38359. }
  38360. /**
  38361. * Stops any scheduled warping which is applied to this action.
  38362. *
  38363. * @return {AnimationAction} A reference to this animation action.
  38364. */
  38365. stopWarping() {
  38366. const timeScaleInterpolant = this._timeScaleInterpolant;
  38367. if ( timeScaleInterpolant !== null ) {
  38368. this._timeScaleInterpolant = null;
  38369. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38370. }
  38371. return this;
  38372. }
  38373. /**
  38374. * Returns the animation mixer of this animation action.
  38375. *
  38376. * @return {AnimationMixer} The animation mixer.
  38377. */
  38378. getMixer() {
  38379. return this._mixer;
  38380. }
  38381. /**
  38382. * Returns the animation clip of this animation action.
  38383. *
  38384. * @return {AnimationClip} The animation clip.
  38385. */
  38386. getClip() {
  38387. return this._clip;
  38388. }
  38389. /**
  38390. * Returns the root object of this animation action.
  38391. *
  38392. * @return {Object3D} The root object.
  38393. */
  38394. getRoot() {
  38395. return this._localRoot || this._mixer._root;
  38396. }
  38397. // Interna
  38398. _update( time, deltaTime, timeDirection, accuIndex ) {
  38399. // called by the mixer
  38400. if ( ! this.enabled ) {
  38401. // call ._updateWeight() to update ._effectiveWeight
  38402. this._updateWeight( time );
  38403. return;
  38404. }
  38405. const startTime = this._startTime;
  38406. if ( startTime !== null ) {
  38407. // check for scheduled start of action
  38408. const timeRunning = ( time - startTime ) * timeDirection;
  38409. if ( timeRunning < 0 || timeDirection === 0 ) {
  38410. deltaTime = 0;
  38411. } else {
  38412. this._startTime = null; // unschedule
  38413. deltaTime = timeDirection * timeRunning;
  38414. }
  38415. }
  38416. // apply time scale and advance time
  38417. deltaTime *= this._updateTimeScale( time );
  38418. const clipTime = this._updateTime( deltaTime );
  38419. // note: _updateTime may disable the action resulting in
  38420. // an effective weight of 0
  38421. const weight = this._updateWeight( time );
  38422. if ( weight > 0 ) {
  38423. const interpolants = this._interpolants;
  38424. const propertyMixers = this._propertyBindings;
  38425. switch ( this.blendMode ) {
  38426. case AdditiveAnimationBlendMode:
  38427. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38428. interpolants[ j ].evaluate( clipTime );
  38429. propertyMixers[ j ].accumulateAdditive( weight );
  38430. }
  38431. break;
  38432. case NormalAnimationBlendMode:
  38433. default:
  38434. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38435. interpolants[ j ].evaluate( clipTime );
  38436. propertyMixers[ j ].accumulate( accuIndex, weight );
  38437. }
  38438. }
  38439. }
  38440. }
  38441. _updateWeight( time ) {
  38442. let weight = 0;
  38443. if ( this.enabled ) {
  38444. weight = this.weight;
  38445. const interpolant = this._weightInterpolant;
  38446. if ( interpolant !== null ) {
  38447. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38448. weight *= interpolantValue;
  38449. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38450. this.stopFading();
  38451. if ( interpolantValue === 0 ) {
  38452. // faded out, disable
  38453. this.enabled = false;
  38454. }
  38455. }
  38456. }
  38457. }
  38458. this._effectiveWeight = weight;
  38459. return weight;
  38460. }
  38461. _updateTimeScale( time ) {
  38462. let timeScale = 0;
  38463. if ( ! this.paused ) {
  38464. timeScale = this.timeScale;
  38465. const interpolant = this._timeScaleInterpolant;
  38466. if ( interpolant !== null ) {
  38467. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38468. timeScale *= interpolantValue;
  38469. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38470. this.stopWarping();
  38471. if ( timeScale === 0 ) {
  38472. // motion has halted, pause
  38473. this.paused = true;
  38474. } else {
  38475. // warp done - apply final time scale
  38476. this.timeScale = timeScale;
  38477. }
  38478. }
  38479. }
  38480. }
  38481. this._effectiveTimeScale = timeScale;
  38482. return timeScale;
  38483. }
  38484. _updateTime( deltaTime ) {
  38485. const duration = this._clip.duration;
  38486. const loop = this.loop;
  38487. let time = this.time + deltaTime;
  38488. let loopCount = this._loopCount;
  38489. const pingPong = ( loop === LoopPingPong );
  38490. if ( deltaTime === 0 ) {
  38491. if ( loopCount === -1 ) return time;
  38492. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38493. }
  38494. if ( loop === LoopOnce ) {
  38495. if ( loopCount === -1 ) {
  38496. // just started
  38497. this._loopCount = 0;
  38498. this._setEndings( true, true, false );
  38499. }
  38500. handle_stop: {
  38501. if ( time >= duration ) {
  38502. time = duration;
  38503. } else if ( time < 0 ) {
  38504. time = 0;
  38505. } else {
  38506. this.time = time;
  38507. break handle_stop;
  38508. }
  38509. if ( this.clampWhenFinished ) this.paused = true;
  38510. else this.enabled = false;
  38511. this.time = time;
  38512. this._mixer.dispatchEvent( {
  38513. type: 'finished', action: this,
  38514. direction: deltaTime < 0 ? -1 : 1
  38515. } );
  38516. }
  38517. } else { // repetitive Repeat or PingPong
  38518. if ( loopCount === -1 ) {
  38519. // just started
  38520. if ( deltaTime >= 0 ) {
  38521. loopCount = 0;
  38522. this._setEndings( true, this.repetitions === 0, pingPong );
  38523. } else {
  38524. // when looping in reverse direction, the initial
  38525. // transition through zero counts as a repetition,
  38526. // so leave loopCount at -1
  38527. this._setEndings( this.repetitions === 0, true, pingPong );
  38528. }
  38529. }
  38530. if ( time >= duration || time < 0 ) {
  38531. // wrap around
  38532. const loopDelta = Math.floor( time / duration ); // signed
  38533. time -= duration * loopDelta;
  38534. loopCount += Math.abs( loopDelta );
  38535. const pending = this.repetitions - loopCount;
  38536. if ( pending <= 0 ) {
  38537. // have to stop (switch state, clamp time, fire event)
  38538. if ( this.clampWhenFinished ) this.paused = true;
  38539. else this.enabled = false;
  38540. time = deltaTime > 0 ? duration : 0;
  38541. this.time = time;
  38542. this._mixer.dispatchEvent( {
  38543. type: 'finished', action: this,
  38544. direction: deltaTime > 0 ? 1 : -1
  38545. } );
  38546. } else {
  38547. // keep running
  38548. if ( pending === 1 ) {
  38549. // entering the last round
  38550. const atStart = deltaTime < 0;
  38551. this._setEndings( atStart, ! atStart, pingPong );
  38552. } else {
  38553. this._setEndings( false, false, pingPong );
  38554. }
  38555. this._loopCount = loopCount;
  38556. this.time = time;
  38557. this._mixer.dispatchEvent( {
  38558. type: 'loop', action: this, loopDelta: loopDelta
  38559. } );
  38560. }
  38561. } else {
  38562. this.time = time;
  38563. }
  38564. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38565. // invert time for the "pong round"
  38566. return duration - time;
  38567. }
  38568. }
  38569. return time;
  38570. }
  38571. _setEndings( atStart, atEnd, pingPong ) {
  38572. const settings = this._interpolantSettings;
  38573. if ( pingPong ) {
  38574. settings.endingStart = ZeroSlopeEnding;
  38575. settings.endingEnd = ZeroSlopeEnding;
  38576. } else {
  38577. // assuming for LoopOnce atStart == atEnd == true
  38578. if ( atStart ) {
  38579. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38580. } else {
  38581. settings.endingStart = WrapAroundEnding;
  38582. }
  38583. if ( atEnd ) {
  38584. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38585. } else {
  38586. settings.endingEnd = WrapAroundEnding;
  38587. }
  38588. }
  38589. }
  38590. _scheduleFading( duration, weightNow, weightThen ) {
  38591. const mixer = this._mixer, now = mixer.time;
  38592. let interpolant = this._weightInterpolant;
  38593. if ( interpolant === null ) {
  38594. interpolant = mixer._lendControlInterpolant();
  38595. this._weightInterpolant = interpolant;
  38596. }
  38597. const times = interpolant.parameterPositions,
  38598. values = interpolant.sampleValues;
  38599. times[ 0 ] = now;
  38600. values[ 0 ] = weightNow;
  38601. times[ 1 ] = now + duration;
  38602. values[ 1 ] = weightThen;
  38603. return this;
  38604. }
  38605. }
  38606. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38607. /**
  38608. * `AnimationMixer` is a player for animations on a particular object in
  38609. * the scene. When multiple objects in the scene are animated independently,
  38610. * one `AnimationMixer` may be used for each object.
  38611. */
  38612. class AnimationMixer extends EventDispatcher {
  38613. /**
  38614. * Constructs a new animation mixer.
  38615. *
  38616. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38617. */
  38618. constructor( root ) {
  38619. super();
  38620. this._root = root;
  38621. this._initMemoryManager();
  38622. this._accuIndex = 0;
  38623. /**
  38624. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38625. *
  38626. * @type {number}
  38627. * @default 0
  38628. */
  38629. this.time = 0;
  38630. /**
  38631. * A scaling factor for the global time.
  38632. *
  38633. * Note: Setting this member to `0` and later back to `1` is a
  38634. * possibility to pause/unpause all actions that are controlled by this
  38635. * mixer.
  38636. *
  38637. * @type {number}
  38638. * @default 1
  38639. */
  38640. this.timeScale = 1.0;
  38641. }
  38642. _bindAction( action, prototypeAction ) {
  38643. const root = action._localRoot || this._root,
  38644. tracks = action._clip.tracks,
  38645. nTracks = tracks.length,
  38646. bindings = action._propertyBindings,
  38647. interpolants = action._interpolants,
  38648. rootUuid = root.uuid,
  38649. bindingsByRoot = this._bindingsByRootAndName;
  38650. let bindingsByName = bindingsByRoot[ rootUuid ];
  38651. if ( bindingsByName === undefined ) {
  38652. bindingsByName = {};
  38653. bindingsByRoot[ rootUuid ] = bindingsByName;
  38654. }
  38655. for ( let i = 0; i !== nTracks; ++ i ) {
  38656. const track = tracks[ i ],
  38657. trackName = track.name;
  38658. let binding = bindingsByName[ trackName ];
  38659. if ( binding !== undefined ) {
  38660. ++ binding.referenceCount;
  38661. bindings[ i ] = binding;
  38662. } else {
  38663. binding = bindings[ i ];
  38664. if ( binding !== undefined ) {
  38665. // existing binding, make sure the cache knows
  38666. if ( binding._cacheIndex === null ) {
  38667. ++ binding.referenceCount;
  38668. this._addInactiveBinding( binding, rootUuid, trackName );
  38669. }
  38670. continue;
  38671. }
  38672. const path = prototypeAction && prototypeAction.
  38673. _propertyBindings[ i ].binding.parsedPath;
  38674. binding = new PropertyMixer(
  38675. PropertyBinding.create( root, trackName, path ),
  38676. track.ValueTypeName, track.getValueSize() );
  38677. ++ binding.referenceCount;
  38678. this._addInactiveBinding( binding, rootUuid, trackName );
  38679. bindings[ i ] = binding;
  38680. }
  38681. interpolants[ i ].resultBuffer = binding.buffer;
  38682. }
  38683. }
  38684. _activateAction( action ) {
  38685. if ( ! this._isActiveAction( action ) ) {
  38686. if ( action._cacheIndex === null ) {
  38687. // this action has been forgotten by the cache, but the user
  38688. // appears to be still using it -> rebind
  38689. const rootUuid = ( action._localRoot || this._root ).uuid,
  38690. clipUuid = action._clip.uuid,
  38691. actionsForClip = this._actionsByClip[ clipUuid ];
  38692. this._bindAction( action,
  38693. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38694. this._addInactiveAction( action, clipUuid, rootUuid );
  38695. }
  38696. const bindings = action._propertyBindings;
  38697. // increment reference counts / sort out state
  38698. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38699. const binding = bindings[ i ];
  38700. if ( binding.useCount ++ === 0 ) {
  38701. this._lendBinding( binding );
  38702. binding.saveOriginalState();
  38703. }
  38704. }
  38705. this._lendAction( action );
  38706. }
  38707. }
  38708. _deactivateAction( action ) {
  38709. if ( this._isActiveAction( action ) ) {
  38710. const bindings = action._propertyBindings;
  38711. // decrement reference counts / sort out state
  38712. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38713. const binding = bindings[ i ];
  38714. if ( -- binding.useCount === 0 ) {
  38715. binding.restoreOriginalState();
  38716. this._takeBackBinding( binding );
  38717. }
  38718. }
  38719. this._takeBackAction( action );
  38720. }
  38721. }
  38722. // Memory manager
  38723. _initMemoryManager() {
  38724. this._actions = []; // 'nActiveActions' followed by inactive ones
  38725. this._nActiveActions = 0;
  38726. this._actionsByClip = {};
  38727. // inside:
  38728. // {
  38729. // knownActions: Array< AnimationAction > - used as prototypes
  38730. // actionByRoot: AnimationAction - lookup
  38731. // }
  38732. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38733. this._nActiveBindings = 0;
  38734. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38735. this._controlInterpolants = []; // same game as above
  38736. this._nActiveControlInterpolants = 0;
  38737. const scope = this;
  38738. this.stats = {
  38739. actions: {
  38740. get total() {
  38741. return scope._actions.length;
  38742. },
  38743. get inUse() {
  38744. return scope._nActiveActions;
  38745. }
  38746. },
  38747. bindings: {
  38748. get total() {
  38749. return scope._bindings.length;
  38750. },
  38751. get inUse() {
  38752. return scope._nActiveBindings;
  38753. }
  38754. },
  38755. controlInterpolants: {
  38756. get total() {
  38757. return scope._controlInterpolants.length;
  38758. },
  38759. get inUse() {
  38760. return scope._nActiveControlInterpolants;
  38761. }
  38762. }
  38763. };
  38764. }
  38765. // Memory management for AnimationAction objects
  38766. _isActiveAction( action ) {
  38767. const index = action._cacheIndex;
  38768. return index !== null && index < this._nActiveActions;
  38769. }
  38770. _addInactiveAction( action, clipUuid, rootUuid ) {
  38771. const actions = this._actions,
  38772. actionsByClip = this._actionsByClip;
  38773. let actionsForClip = actionsByClip[ clipUuid ];
  38774. if ( actionsForClip === undefined ) {
  38775. actionsForClip = {
  38776. knownActions: [ action ],
  38777. actionByRoot: {}
  38778. };
  38779. action._byClipCacheIndex = 0;
  38780. actionsByClip[ clipUuid ] = actionsForClip;
  38781. } else {
  38782. const knownActions = actionsForClip.knownActions;
  38783. action._byClipCacheIndex = knownActions.length;
  38784. knownActions.push( action );
  38785. }
  38786. action._cacheIndex = actions.length;
  38787. actions.push( action );
  38788. actionsForClip.actionByRoot[ rootUuid ] = action;
  38789. }
  38790. _removeInactiveAction( action ) {
  38791. const actions = this._actions,
  38792. lastInactiveAction = actions[ actions.length - 1 ],
  38793. cacheIndex = action._cacheIndex;
  38794. lastInactiveAction._cacheIndex = cacheIndex;
  38795. actions[ cacheIndex ] = lastInactiveAction;
  38796. actions.pop();
  38797. action._cacheIndex = null;
  38798. const clipUuid = action._clip.uuid,
  38799. actionsByClip = this._actionsByClip,
  38800. actionsForClip = actionsByClip[ clipUuid ],
  38801. knownActionsForClip = actionsForClip.knownActions,
  38802. lastKnownAction =
  38803. knownActionsForClip[ knownActionsForClip.length - 1 ],
  38804. byClipCacheIndex = action._byClipCacheIndex;
  38805. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  38806. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  38807. knownActionsForClip.pop();
  38808. action._byClipCacheIndex = null;
  38809. const actionByRoot = actionsForClip.actionByRoot,
  38810. rootUuid = ( action._localRoot || this._root ).uuid;
  38811. delete actionByRoot[ rootUuid ];
  38812. if ( knownActionsForClip.length === 0 ) {
  38813. delete actionsByClip[ clipUuid ];
  38814. }
  38815. this._removeInactiveBindingsForAction( action );
  38816. }
  38817. _removeInactiveBindingsForAction( action ) {
  38818. const bindings = action._propertyBindings;
  38819. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38820. const binding = bindings[ i ];
  38821. if ( -- binding.referenceCount === 0 ) {
  38822. this._removeInactiveBinding( binding );
  38823. }
  38824. }
  38825. }
  38826. _lendAction( action ) {
  38827. // [ active actions | inactive actions ]
  38828. // [ active actions >| inactive actions ]
  38829. // s a
  38830. // <-swap->
  38831. // a s
  38832. const actions = this._actions,
  38833. prevIndex = action._cacheIndex,
  38834. lastActiveIndex = this._nActiveActions ++,
  38835. firstInactiveAction = actions[ lastActiveIndex ];
  38836. action._cacheIndex = lastActiveIndex;
  38837. actions[ lastActiveIndex ] = action;
  38838. firstInactiveAction._cacheIndex = prevIndex;
  38839. actions[ prevIndex ] = firstInactiveAction;
  38840. }
  38841. _takeBackAction( action ) {
  38842. // [ active actions | inactive actions ]
  38843. // [ active actions |< inactive actions ]
  38844. // a s
  38845. // <-swap->
  38846. // s a
  38847. const actions = this._actions,
  38848. prevIndex = action._cacheIndex,
  38849. firstInactiveIndex = -- this._nActiveActions,
  38850. lastActiveAction = actions[ firstInactiveIndex ];
  38851. action._cacheIndex = firstInactiveIndex;
  38852. actions[ firstInactiveIndex ] = action;
  38853. lastActiveAction._cacheIndex = prevIndex;
  38854. actions[ prevIndex ] = lastActiveAction;
  38855. }
  38856. // Memory management for PropertyMixer objects
  38857. _addInactiveBinding( binding, rootUuid, trackName ) {
  38858. const bindingsByRoot = this._bindingsByRootAndName,
  38859. bindings = this._bindings;
  38860. let bindingByName = bindingsByRoot[ rootUuid ];
  38861. if ( bindingByName === undefined ) {
  38862. bindingByName = {};
  38863. bindingsByRoot[ rootUuid ] = bindingByName;
  38864. }
  38865. bindingByName[ trackName ] = binding;
  38866. binding._cacheIndex = bindings.length;
  38867. bindings.push( binding );
  38868. }
  38869. _removeInactiveBinding( binding ) {
  38870. const bindings = this._bindings,
  38871. propBinding = binding.binding,
  38872. rootUuid = propBinding.rootNode.uuid,
  38873. trackName = propBinding.path,
  38874. bindingsByRoot = this._bindingsByRootAndName,
  38875. bindingByName = bindingsByRoot[ rootUuid ],
  38876. lastInactiveBinding = bindings[ bindings.length - 1 ],
  38877. cacheIndex = binding._cacheIndex;
  38878. lastInactiveBinding._cacheIndex = cacheIndex;
  38879. bindings[ cacheIndex ] = lastInactiveBinding;
  38880. bindings.pop();
  38881. delete bindingByName[ trackName ];
  38882. if ( Object.keys( bindingByName ).length === 0 ) {
  38883. delete bindingsByRoot[ rootUuid ];
  38884. }
  38885. }
  38886. _lendBinding( binding ) {
  38887. const bindings = this._bindings,
  38888. prevIndex = binding._cacheIndex,
  38889. lastActiveIndex = this._nActiveBindings ++,
  38890. firstInactiveBinding = bindings[ lastActiveIndex ];
  38891. binding._cacheIndex = lastActiveIndex;
  38892. bindings[ lastActiveIndex ] = binding;
  38893. firstInactiveBinding._cacheIndex = prevIndex;
  38894. bindings[ prevIndex ] = firstInactiveBinding;
  38895. }
  38896. _takeBackBinding( binding ) {
  38897. const bindings = this._bindings,
  38898. prevIndex = binding._cacheIndex,
  38899. firstInactiveIndex = -- this._nActiveBindings,
  38900. lastActiveBinding = bindings[ firstInactiveIndex ];
  38901. binding._cacheIndex = firstInactiveIndex;
  38902. bindings[ firstInactiveIndex ] = binding;
  38903. lastActiveBinding._cacheIndex = prevIndex;
  38904. bindings[ prevIndex ] = lastActiveBinding;
  38905. }
  38906. // Memory management of Interpolants for weight and time scale
  38907. _lendControlInterpolant() {
  38908. const interpolants = this._controlInterpolants,
  38909. lastActiveIndex = this._nActiveControlInterpolants ++;
  38910. let interpolant = interpolants[ lastActiveIndex ];
  38911. if ( interpolant === undefined ) {
  38912. interpolant = new LinearInterpolant(
  38913. new Float32Array( 2 ), new Float32Array( 2 ),
  38914. 1, _controlInterpolantsResultBuffer );
  38915. interpolant.__cacheIndex = lastActiveIndex;
  38916. interpolants[ lastActiveIndex ] = interpolant;
  38917. }
  38918. return interpolant;
  38919. }
  38920. _takeBackControlInterpolant( interpolant ) {
  38921. const interpolants = this._controlInterpolants,
  38922. prevIndex = interpolant.__cacheIndex,
  38923. firstInactiveIndex = -- this._nActiveControlInterpolants,
  38924. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  38925. interpolant.__cacheIndex = firstInactiveIndex;
  38926. interpolants[ firstInactiveIndex ] = interpolant;
  38927. lastActiveInterpolant.__cacheIndex = prevIndex;
  38928. interpolants[ prevIndex ] = lastActiveInterpolant;
  38929. }
  38930. /**
  38931. * Returns an instance of {@link AnimationAction} for the passed clip.
  38932. *
  38933. * If an action fitting the clip and root parameters doesn't yet exist, it
  38934. * will be created by this method. Calling this method several times with the
  38935. * same clip and root parameters always returns the same action.
  38936. *
  38937. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38938. * @param {Object3D} [optionalRoot] - An alternative root object.
  38939. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38940. * @return {?AnimationAction} The animation action.
  38941. */
  38942. clipAction( clip, optionalRoot, blendMode ) {
  38943. const root = optionalRoot || this._root,
  38944. rootUuid = root.uuid;
  38945. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  38946. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  38947. const actionsForClip = this._actionsByClip[ clipUuid ];
  38948. let prototypeAction = null;
  38949. if ( blendMode === undefined ) {
  38950. if ( clipObject !== null ) {
  38951. blendMode = clipObject.blendMode;
  38952. } else {
  38953. blendMode = NormalAnimationBlendMode;
  38954. }
  38955. }
  38956. if ( actionsForClip !== undefined ) {
  38957. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  38958. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  38959. return existingAction;
  38960. }
  38961. // we know the clip, so we don't have to parse all
  38962. // the bindings again but can just copy
  38963. prototypeAction = actionsForClip.knownActions[ 0 ];
  38964. // also, take the clip from the prototype action
  38965. if ( clipObject === null )
  38966. clipObject = prototypeAction._clip;
  38967. }
  38968. // clip must be known when specified via string
  38969. if ( clipObject === null ) return null;
  38970. // allocate all resources required to run it
  38971. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  38972. this._bindAction( newAction, prototypeAction );
  38973. // and make the action known to the memory manager
  38974. this._addInactiveAction( newAction, clipUuid, rootUuid );
  38975. return newAction;
  38976. }
  38977. /**
  38978. * Returns an existing animation action for the passed clip.
  38979. *
  38980. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38981. * @param {Object3D} [optionalRoot] - An alternative root object.
  38982. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  38983. */
  38984. existingAction( clip, optionalRoot ) {
  38985. const root = optionalRoot || this._root,
  38986. rootUuid = root.uuid,
  38987. clipObject = typeof clip === 'string' ?
  38988. AnimationClip.findByName( root, clip ) : clip,
  38989. clipUuid = clipObject ? clipObject.uuid : clip,
  38990. actionsForClip = this._actionsByClip[ clipUuid ];
  38991. if ( actionsForClip !== undefined ) {
  38992. return actionsForClip.actionByRoot[ rootUuid ] || null;
  38993. }
  38994. return null;
  38995. }
  38996. /**
  38997. * Deactivates all previously scheduled actions on this mixer.
  38998. *
  38999. * @return {AnimationMixer} A reference to thi animation mixer.
  39000. */
  39001. stopAllAction() {
  39002. const actions = this._actions,
  39003. nActions = this._nActiveActions;
  39004. for ( let i = nActions - 1; i >= 0; -- i ) {
  39005. actions[ i ].stop();
  39006. }
  39007. return this;
  39008. }
  39009. /**
  39010. * Advances the global mixer time and updates the animation.
  39011. *
  39012. * This is usually done in the render loop by passing the delta
  39013. * time from {@link Clock} or {@link Timer}.
  39014. *
  39015. * @param {number} deltaTime - The delta time in seconds.
  39016. * @return {AnimationMixer} A reference to thi animation mixer.
  39017. */
  39018. update( deltaTime ) {
  39019. deltaTime *= this.timeScale;
  39020. const actions = this._actions,
  39021. nActions = this._nActiveActions,
  39022. time = this.time += deltaTime,
  39023. timeDirection = Math.sign( deltaTime ),
  39024. accuIndex = this._accuIndex ^= 1;
  39025. // run active actions
  39026. for ( let i = 0; i !== nActions; ++ i ) {
  39027. const action = actions[ i ];
  39028. action._update( time, deltaTime, timeDirection, accuIndex );
  39029. }
  39030. // update scene graph
  39031. const bindings = this._bindings,
  39032. nBindings = this._nActiveBindings;
  39033. for ( let i = 0; i !== nBindings; ++ i ) {
  39034. bindings[ i ].apply( accuIndex );
  39035. }
  39036. return this;
  39037. }
  39038. /**
  39039. * Sets the global mixer to a specific time and updates the animation accordingly.
  39040. *
  39041. * This is useful when you need to jump to an exact time in an animation. The
  39042. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39043. *
  39044. * @param {number} time - The time to set in seconds.
  39045. * @return {AnimationMixer} A reference to thi animation mixer.
  39046. */
  39047. setTime( time ) {
  39048. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39049. for ( let i = 0; i < this._actions.length; i ++ ) {
  39050. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39051. }
  39052. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39053. }
  39054. /**
  39055. * Returns this mixer's root object.
  39056. *
  39057. * @return {Object3D} The mixer's root object.
  39058. */
  39059. getRoot() {
  39060. return this._root;
  39061. }
  39062. /**
  39063. * Deallocates all memory resources for a clip. Before using this method make
  39064. * sure to call {@link AnimationAction#stop} for all related actions.
  39065. *
  39066. * @param {AnimationClip} clip - The clip to uncache.
  39067. */
  39068. uncacheClip( clip ) {
  39069. const actions = this._actions,
  39070. clipUuid = clip.uuid,
  39071. actionsByClip = this._actionsByClip,
  39072. actionsForClip = actionsByClip[ clipUuid ];
  39073. if ( actionsForClip !== undefined ) {
  39074. // note: just calling _removeInactiveAction would mess up the
  39075. // iteration state and also require updating the state we can
  39076. // just throw away
  39077. const actionsToRemove = actionsForClip.knownActions;
  39078. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39079. const action = actionsToRemove[ i ];
  39080. this._deactivateAction( action );
  39081. const cacheIndex = action._cacheIndex,
  39082. lastInactiveAction = actions[ actions.length - 1 ];
  39083. action._cacheIndex = null;
  39084. action._byClipCacheIndex = null;
  39085. lastInactiveAction._cacheIndex = cacheIndex;
  39086. actions[ cacheIndex ] = lastInactiveAction;
  39087. actions.pop();
  39088. this._removeInactiveBindingsForAction( action );
  39089. }
  39090. delete actionsByClip[ clipUuid ];
  39091. }
  39092. }
  39093. /**
  39094. * Deallocates all memory resources for a root object. Before using this
  39095. * method make sure to call {@link AnimationAction#stop} for all related
  39096. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39097. * mixer operates on a single root.
  39098. *
  39099. * @param {Object3D} root - The root object to uncache.
  39100. */
  39101. uncacheRoot( root ) {
  39102. const rootUuid = root.uuid,
  39103. actionsByClip = this._actionsByClip;
  39104. for ( const clipUuid in actionsByClip ) {
  39105. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39106. action = actionByRoot[ rootUuid ];
  39107. if ( action !== undefined ) {
  39108. this._deactivateAction( action );
  39109. this._removeInactiveAction( action );
  39110. }
  39111. }
  39112. const bindingsByRoot = this._bindingsByRootAndName,
  39113. bindingByName = bindingsByRoot[ rootUuid ];
  39114. if ( bindingByName !== undefined ) {
  39115. for ( const trackName in bindingByName ) {
  39116. const binding = bindingByName[ trackName ];
  39117. binding.restoreOriginalState();
  39118. this._removeInactiveBinding( binding );
  39119. }
  39120. }
  39121. }
  39122. /**
  39123. * Deallocates all memory resources for an action. The action is identified by the
  39124. * given clip and an optional root object. Before using this method make
  39125. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39126. *
  39127. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39128. * @param {Object3D} [optionalRoot] - An alternative root object.
  39129. */
  39130. uncacheAction( clip, optionalRoot ) {
  39131. const action = this.existingAction( clip, optionalRoot );
  39132. if ( action !== null ) {
  39133. this._deactivateAction( action );
  39134. this._removeInactiveAction( action );
  39135. }
  39136. }
  39137. }
  39138. /**
  39139. * Represents a 3D render target.
  39140. *
  39141. * @augments RenderTarget
  39142. */
  39143. class RenderTarget3D extends RenderTarget {
  39144. /**
  39145. * Constructs a new 3D render target.
  39146. *
  39147. * @param {number} [width=1] - The width of the render target.
  39148. * @param {number} [height=1] - The height of the render target.
  39149. * @param {number} [depth=1] - The height of the render target.
  39150. * @param {RenderTarget~Options} [options] - The configuration object.
  39151. */
  39152. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39153. super( width, height, options );
  39154. /**
  39155. * This flag can be used for type testing.
  39156. *
  39157. * @type {boolean}
  39158. * @readonly
  39159. * @default true
  39160. */
  39161. this.isRenderTarget3D = true;
  39162. this.depth = depth;
  39163. /**
  39164. * Overwritten with a different texture type.
  39165. *
  39166. * @type {Data3DTexture}
  39167. */
  39168. this.texture = new Data3DTexture( null, width, height, depth );
  39169. this._setTextureOptions( options );
  39170. this.texture.isRenderTargetTexture = true;
  39171. }
  39172. }
  39173. /**
  39174. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39175. *
  39176. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39177. * ```js
  39178. * uniforms: {
  39179. * time: { value: 1.0 },
  39180. * resolution: new Uniform( new Vector2() )
  39181. * };
  39182. * ```
  39183. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39184. * in {@link WebGLRenderer}.
  39185. */
  39186. class Uniform {
  39187. /**
  39188. * Constructs a new uniform.
  39189. *
  39190. * @param {any} value - The uniform value.
  39191. */
  39192. constructor( value ) {
  39193. /**
  39194. * The uniform value.
  39195. *
  39196. * @type {any}
  39197. */
  39198. this.value = value;
  39199. }
  39200. /**
  39201. * Returns a new uniform with copied values from this instance.
  39202. * If the value has a `clone()` method, the value is cloned as well.
  39203. *
  39204. * @return {Uniform} A clone of this instance.
  39205. */
  39206. clone() {
  39207. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39208. }
  39209. }
  39210. let _id = 0;
  39211. /**
  39212. * A class for managing multiple uniforms in a single group. The renderer will process
  39213. * such a definition as a single UBO.
  39214. *
  39215. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39216. * in {@link WebGLRenderer}.
  39217. *
  39218. * @augments EventDispatcher
  39219. */
  39220. class UniformsGroup extends EventDispatcher {
  39221. /**
  39222. * Constructs a new uniforms group.
  39223. */
  39224. constructor() {
  39225. super();
  39226. /**
  39227. * This flag can be used for type testing.
  39228. *
  39229. * @type {boolean}
  39230. * @readonly
  39231. * @default true
  39232. */
  39233. this.isUniformsGroup = true;
  39234. /**
  39235. * The ID of the 3D object.
  39236. *
  39237. * @name UniformsGroup#id
  39238. * @type {number}
  39239. * @readonly
  39240. */
  39241. Object.defineProperty( this, 'id', { value: _id ++ } );
  39242. /**
  39243. * The name of the uniforms group.
  39244. *
  39245. * @type {string}
  39246. */
  39247. this.name = '';
  39248. /**
  39249. * The buffer usage.
  39250. *
  39251. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39252. * @default StaticDrawUsage
  39253. */
  39254. this.usage = StaticDrawUsage;
  39255. /**
  39256. * An array holding the uniforms.
  39257. *
  39258. * @type {Array<Uniform>}
  39259. */
  39260. this.uniforms = [];
  39261. }
  39262. /**
  39263. * Adds the given uniform to this uniforms group.
  39264. *
  39265. * @param {Uniform} uniform - The uniform to add.
  39266. * @return {UniformsGroup} A reference to this uniforms group.
  39267. */
  39268. add( uniform ) {
  39269. this.uniforms.push( uniform );
  39270. return this;
  39271. }
  39272. /**
  39273. * Removes the given uniform from this uniforms group.
  39274. *
  39275. * @param {Uniform} uniform - The uniform to remove.
  39276. * @return {UniformsGroup} A reference to this uniforms group.
  39277. */
  39278. remove( uniform ) {
  39279. const index = this.uniforms.indexOf( uniform );
  39280. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39281. return this;
  39282. }
  39283. /**
  39284. * Sets the name of this uniforms group.
  39285. *
  39286. * @param {string} name - The name to set.
  39287. * @return {UniformsGroup} A reference to this uniforms group.
  39288. */
  39289. setName( name ) {
  39290. this.name = name;
  39291. return this;
  39292. }
  39293. /**
  39294. * Sets the usage of this uniforms group.
  39295. *
  39296. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39297. * @return {UniformsGroup} A reference to this uniforms group.
  39298. */
  39299. setUsage( value ) {
  39300. this.usage = value;
  39301. return this;
  39302. }
  39303. /**
  39304. * Frees the GPU-related resources allocated by this instance. Call this
  39305. * method whenever this instance is no longer used in your app.
  39306. *
  39307. * @fires Texture#dispose
  39308. */
  39309. dispose() {
  39310. this.dispatchEvent( { type: 'dispose' } );
  39311. }
  39312. /**
  39313. * Copies the values of the given uniforms group to this instance.
  39314. *
  39315. * @param {UniformsGroup} source - The uniforms group to copy.
  39316. * @return {UniformsGroup} A reference to this uniforms group.
  39317. */
  39318. copy( source ) {
  39319. this.name = source.name;
  39320. this.usage = source.usage;
  39321. const uniformsSource = source.uniforms;
  39322. this.uniforms.length = 0;
  39323. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39324. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39325. for ( let j = 0; j < uniforms.length; j ++ ) {
  39326. this.uniforms.push( uniforms[ j ].clone() );
  39327. }
  39328. }
  39329. return this;
  39330. }
  39331. /**
  39332. * Returns a new uniforms group with copied values from this instance.
  39333. *
  39334. * @return {UniformsGroup} A clone of this instance.
  39335. */
  39336. clone() {
  39337. return new this.constructor().copy( this );
  39338. }
  39339. }
  39340. /**
  39341. * An instanced version of an interleaved buffer.
  39342. *
  39343. * @augments InterleavedBuffer
  39344. */
  39345. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39346. /**
  39347. * Constructs a new instanced interleaved buffer.
  39348. *
  39349. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39350. * @param {number} stride - The number of typed-array elements per vertex.
  39351. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39352. */
  39353. constructor( array, stride, meshPerAttribute = 1 ) {
  39354. super( array, stride );
  39355. /**
  39356. * This flag can be used for type testing.
  39357. *
  39358. * @type {boolean}
  39359. * @readonly
  39360. * @default true
  39361. */
  39362. this.isInstancedInterleavedBuffer = true;
  39363. /**
  39364. * Defines how often a value of this buffer attribute should be repeated,
  39365. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39366. *
  39367. * @type {number}
  39368. * @default 1
  39369. */
  39370. this.meshPerAttribute = meshPerAttribute;
  39371. }
  39372. copy( source ) {
  39373. super.copy( source );
  39374. this.meshPerAttribute = source.meshPerAttribute;
  39375. return this;
  39376. }
  39377. clone( data ) {
  39378. const ib = super.clone( data );
  39379. ib.meshPerAttribute = this.meshPerAttribute;
  39380. return ib;
  39381. }
  39382. toJSON( data ) {
  39383. const json = super.toJSON( data );
  39384. json.isInstancedInterleavedBuffer = true;
  39385. json.meshPerAttribute = this.meshPerAttribute;
  39386. return json;
  39387. }
  39388. }
  39389. /**
  39390. * An alternative version of a buffer attribute with more control over the VBO.
  39391. *
  39392. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39393. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39394. *
  39395. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39396. * or even produces the VBOs in question.
  39397. *
  39398. * Notice that this class can only be used with {@link WebGLRenderer}.
  39399. */
  39400. class GLBufferAttribute {
  39401. /**
  39402. * Constructs a new GL buffer attribute.
  39403. *
  39404. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39405. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39406. * @param {number} itemSize - The item size.
  39407. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39408. * @param {number} count - The expected number of vertices in VBO.
  39409. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39410. */
  39411. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39412. /**
  39413. * This flag can be used for type testing.
  39414. *
  39415. * @type {boolean}
  39416. * @readonly
  39417. * @default true
  39418. */
  39419. this.isGLBufferAttribute = true;
  39420. /**
  39421. * The name of the buffer attribute.
  39422. *
  39423. * @type {string}
  39424. */
  39425. this.name = '';
  39426. /**
  39427. * The native WebGL buffer.
  39428. *
  39429. * @type {WebGLBuffer}
  39430. */
  39431. this.buffer = buffer;
  39432. /**
  39433. * The native data type.
  39434. *
  39435. * @type {number}
  39436. */
  39437. this.type = type;
  39438. /**
  39439. * The item size, see {@link BufferAttribute#itemSize}.
  39440. *
  39441. * @type {number}
  39442. */
  39443. this.itemSize = itemSize;
  39444. /**
  39445. * The corresponding size (in bytes) for the given `type` parameter.
  39446. *
  39447. * @type {number}
  39448. */
  39449. this.elementSize = elementSize;
  39450. /**
  39451. * The expected number of vertices in VBO.
  39452. *
  39453. * @type {number}
  39454. */
  39455. this.count = count;
  39456. /**
  39457. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39458. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39459. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39460. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39461. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39462. *
  39463. * @type {boolean}
  39464. */
  39465. this.normalized = normalized;
  39466. /**
  39467. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39468. *
  39469. * @type {number}
  39470. */
  39471. this.version = 0;
  39472. }
  39473. /**
  39474. * Flag to indicate that this attribute has changed and should be re-sent to
  39475. * the GPU. Set this to `true` when you modify the value of the array.
  39476. *
  39477. * @type {number}
  39478. * @default false
  39479. * @param {boolean} value
  39480. */
  39481. set needsUpdate( value ) {
  39482. if ( value === true ) this.version ++;
  39483. }
  39484. /**
  39485. * Sets the given native WebGL buffer.
  39486. *
  39487. * @param {WebGLBuffer} buffer - The buffer to set.
  39488. * @return {BufferAttribute} A reference to this instance.
  39489. */
  39490. setBuffer( buffer ) {
  39491. this.buffer = buffer;
  39492. return this;
  39493. }
  39494. /**
  39495. * Sets the given native data type and element size.
  39496. *
  39497. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39498. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39499. * @return {BufferAttribute} A reference to this instance.
  39500. */
  39501. setType( type, elementSize ) {
  39502. this.type = type;
  39503. this.elementSize = elementSize;
  39504. return this;
  39505. }
  39506. /**
  39507. * Sets the item size.
  39508. *
  39509. * @param {number} itemSize - The item size.
  39510. * @return {BufferAttribute} A reference to this instance.
  39511. */
  39512. setItemSize( itemSize ) {
  39513. this.itemSize = itemSize;
  39514. return this;
  39515. }
  39516. /**
  39517. * Sets the count (the expected number of vertices in VBO).
  39518. *
  39519. * @param {number} count - The count.
  39520. * @return {BufferAttribute} A reference to this instance.
  39521. */
  39522. setCount( count ) {
  39523. this.count = count;
  39524. return this;
  39525. }
  39526. }
  39527. const _matrix = /*@__PURE__*/ new Matrix4();
  39528. /**
  39529. * This class is designed to assist with raycasting. Raycasting is used for
  39530. * mouse picking (working out what objects in the 3d space the mouse is over)
  39531. * amongst other things.
  39532. */
  39533. class Raycaster {
  39534. /**
  39535. * Constructs a new raycaster.
  39536. *
  39537. * @param {Vector3} origin - The origin vector where the ray casts from.
  39538. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39539. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39540. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39541. */
  39542. constructor( origin, direction, near = 0, far = Infinity ) {
  39543. /**
  39544. * The ray used for raycasting.
  39545. *
  39546. * @type {Ray}
  39547. */
  39548. this.ray = new Ray( origin, direction );
  39549. /**
  39550. * All results returned are further away than near. Near can't be negative.
  39551. *
  39552. * @type {number}
  39553. * @default 0
  39554. */
  39555. this.near = near;
  39556. /**
  39557. * All results returned are further away than near. Near can't be negative.
  39558. *
  39559. * @type {number}
  39560. * @default Infinity
  39561. */
  39562. this.far = far;
  39563. /**
  39564. * The camera to use when raycasting against view-dependent objects such as
  39565. * billboarded objects like sprites. This field can be set manually or
  39566. * is set when calling `setFromCamera()`.
  39567. *
  39568. * @type {?Camera}
  39569. * @default null
  39570. */
  39571. this.camera = null;
  39572. /**
  39573. * Allows to selectively ignore 3D objects when performing intersection tests.
  39574. * The following code example ensures that only 3D objects on layer `1` will be
  39575. * honored by raycaster.
  39576. * ```js
  39577. * raycaster.layers.set( 1 );
  39578. * object.layers.enable( 1 );
  39579. * ```
  39580. *
  39581. * @type {Layers}
  39582. */
  39583. this.layers = new Layers();
  39584. /**
  39585. * A parameter object that configures the raycasting. It has the structure:
  39586. *
  39587. * ```
  39588. * {
  39589. * Mesh: {},
  39590. * Line: { threshold: 1 },
  39591. * LOD: {},
  39592. * Points: { threshold: 1 },
  39593. * Sprite: {}
  39594. * }
  39595. * ```
  39596. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39597. *
  39598. * @type {Object}
  39599. */
  39600. this.params = {
  39601. Mesh: {},
  39602. Line: { threshold: 1 },
  39603. LOD: {},
  39604. Points: { threshold: 1 },
  39605. Sprite: {}
  39606. };
  39607. }
  39608. /**
  39609. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39610. *
  39611. * @param {Vector3} origin - The origin vector where the ray casts from.
  39612. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39613. */
  39614. set( origin, direction ) {
  39615. // direction is assumed to be normalized (for accurate distance calculations)
  39616. this.ray.set( origin, direction );
  39617. }
  39618. /**
  39619. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39620. *
  39621. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39622. * X and Y components should be between `-1` and `1`.
  39623. * @param {Camera} camera - The camera from which the ray should originate.
  39624. */
  39625. setFromCamera( coords, camera ) {
  39626. if ( camera.isPerspectiveCamera ) {
  39627. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39628. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39629. this.camera = camera;
  39630. } else if ( camera.isOrthographicCamera ) {
  39631. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39632. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39633. this.camera = camera;
  39634. } else {
  39635. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  39636. }
  39637. }
  39638. /**
  39639. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39640. *
  39641. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39642. * @return {Raycaster} A reference to this raycaster.
  39643. */
  39644. setFromXRController( controller ) {
  39645. _matrix.identity().extractRotation( controller.matrixWorld );
  39646. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39647. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39648. return this;
  39649. }
  39650. /**
  39651. * The intersection point of a raycaster intersection test.
  39652. * @typedef {Object} Raycaster~Intersection
  39653. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39654. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39655. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39656. * @property {Vector3} point - The intersection point, in world coordinates.
  39657. * @property {Object} face - The face that has been intersected.
  39658. * @property {number} faceIndex - The face index.
  39659. * @property {Object3D} object - The 3D object that has been intersected.
  39660. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39661. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39662. * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
  39663. * @property {number} instanceId - The index number of the instance where the ray
  39664. * intersects the {@link InstancedMesh}.
  39665. */
  39666. /**
  39667. * Checks all intersection between the ray and the object with or without the
  39668. * descendants. Intersections are returned sorted by distance, closest first.
  39669. *
  39670. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39671. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39672. * differently to ray casting than lines or points.
  39673. *
  39674. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39675. * to be detected; intersections of the ray passing through the back of a face will not
  39676. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39677. * to `THREE.DoubleSide`.
  39678. *
  39679. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39680. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39681. * Otherwise it only checks intersection with the object.
  39682. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39683. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39684. */
  39685. intersectObject( object, recursive = true, intersects = [] ) {
  39686. intersect( object, this, intersects, recursive );
  39687. intersects.sort( ascSort );
  39688. return intersects;
  39689. }
  39690. /**
  39691. * Checks all intersection between the ray and the objects with or without
  39692. * the descendants. Intersections are returned sorted by distance, closest first.
  39693. *
  39694. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39695. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39696. * Otherwise it only checks intersection with the object.
  39697. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39698. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39699. */
  39700. intersectObjects( objects, recursive = true, intersects = [] ) {
  39701. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39702. intersect( objects[ i ], this, intersects, recursive );
  39703. }
  39704. intersects.sort( ascSort );
  39705. return intersects;
  39706. }
  39707. }
  39708. function ascSort( a, b ) {
  39709. return a.distance - b.distance;
  39710. }
  39711. function intersect( object, raycaster, intersects, recursive ) {
  39712. let propagate = true;
  39713. if ( object.layers.test( raycaster.layers ) ) {
  39714. const result = object.raycast( raycaster, intersects );
  39715. if ( result === false ) propagate = false;
  39716. }
  39717. if ( propagate === true && recursive === true ) {
  39718. const children = object.children;
  39719. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39720. intersect( children[ i ], raycaster, intersects, true );
  39721. }
  39722. }
  39723. }
  39724. /**
  39725. * This class is an alternative to {@link Clock} with a different API design and behavior.
  39726. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  39727. *
  39728. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  39729. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  39730. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  39731. * is inactive (e.g. tab switched or browser hidden).
  39732. *
  39733. * ```js
  39734. * const timer = new Timer();
  39735. * timer.connect( document ); // use Page Visibility API
  39736. * ```
  39737. */
  39738. class Timer {
  39739. /**
  39740. * Constructs a new timer.
  39741. */
  39742. constructor() {
  39743. this._previousTime = 0;
  39744. this._currentTime = 0;
  39745. this._startTime = performance.now();
  39746. this._delta = 0;
  39747. this._elapsed = 0;
  39748. this._timescale = 1;
  39749. this._document = null;
  39750. this._pageVisibilityHandler = null;
  39751. }
  39752. /**
  39753. * Connect the timer to the given document.Calling this method is not mandatory to
  39754. * use the timer but enables the usage of the Page Visibility API to avoid large time
  39755. * delta values.
  39756. *
  39757. * @param {Document} document - The document.
  39758. */
  39759. connect( document ) {
  39760. this._document = document;
  39761. // use Page Visibility API to avoid large time delta values
  39762. if ( document.hidden !== undefined ) {
  39763. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  39764. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  39765. }
  39766. }
  39767. /**
  39768. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  39769. */
  39770. disconnect() {
  39771. if ( this._pageVisibilityHandler !== null ) {
  39772. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  39773. this._pageVisibilityHandler = null;
  39774. }
  39775. this._document = null;
  39776. }
  39777. /**
  39778. * Returns the time delta in seconds.
  39779. *
  39780. * @return {number} The time delta in second.
  39781. */
  39782. getDelta() {
  39783. return this._delta / 1000;
  39784. }
  39785. /**
  39786. * Returns the elapsed time in seconds.
  39787. *
  39788. * @return {number} The elapsed time in second.
  39789. */
  39790. getElapsed() {
  39791. return this._elapsed / 1000;
  39792. }
  39793. /**
  39794. * Returns the timescale.
  39795. *
  39796. * @return {number} The timescale.
  39797. */
  39798. getTimescale() {
  39799. return this._timescale;
  39800. }
  39801. /**
  39802. * Sets the given timescale which scale the time delta computation
  39803. * in `update()`.
  39804. *
  39805. * @param {number} timescale - The timescale to set.
  39806. * @return {Timer} A reference to this timer.
  39807. */
  39808. setTimescale( timescale ) {
  39809. this._timescale = timescale;
  39810. return this;
  39811. }
  39812. /**
  39813. * Resets the time computation for the current simulation step.
  39814. *
  39815. * @return {Timer} A reference to this timer.
  39816. */
  39817. reset() {
  39818. this._currentTime = performance.now() - this._startTime;
  39819. return this;
  39820. }
  39821. /**
  39822. * Can be used to free all internal resources. Usually called when
  39823. * the timer instance isn't required anymore.
  39824. */
  39825. dispose() {
  39826. this.disconnect();
  39827. }
  39828. /**
  39829. * Updates the internal state of the timer. This method should be called
  39830. * once per simulation step and before you perform queries against the timer
  39831. * (e.g. via `getDelta()`).
  39832. *
  39833. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  39834. * from the `requestAnimationFrame` callback argument. If not provided, the current
  39835. * time will be determined with `performance.now`.
  39836. * @return {Timer} A reference to this timer.
  39837. */
  39838. update( timestamp ) {
  39839. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  39840. this._delta = 0;
  39841. } else {
  39842. this._previousTime = this._currentTime;
  39843. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  39844. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  39845. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  39846. }
  39847. return this;
  39848. }
  39849. }
  39850. function handleVisibilityChange() {
  39851. if ( this._document.hidden === false ) this.reset();
  39852. }
  39853. /**
  39854. * This class can be used to represent points in 3D space as
  39855. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  39856. */
  39857. class Spherical {
  39858. /**
  39859. * Constructs a new spherical.
  39860. *
  39861. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39862. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  39863. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  39864. */
  39865. constructor( radius = 1, phi = 0, theta = 0 ) {
  39866. /**
  39867. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39868. *
  39869. * @type {number}
  39870. * @default 1
  39871. */
  39872. this.radius = radius;
  39873. /**
  39874. * The polar angle in radians from the y (up) axis.
  39875. *
  39876. * @type {number}
  39877. * @default 0
  39878. */
  39879. this.phi = phi;
  39880. /**
  39881. * The equator/azimuthal angle in radians around the y (up) axis.
  39882. *
  39883. * @type {number}
  39884. * @default 0
  39885. */
  39886. this.theta = theta;
  39887. }
  39888. /**
  39889. * Sets the spherical components by copying the given values.
  39890. *
  39891. * @param {number} radius - The radius.
  39892. * @param {number} phi - The polar angle.
  39893. * @param {number} theta - The azimuthal angle.
  39894. * @return {Spherical} A reference to this spherical.
  39895. */
  39896. set( radius, phi, theta ) {
  39897. this.radius = radius;
  39898. this.phi = phi;
  39899. this.theta = theta;
  39900. return this;
  39901. }
  39902. /**
  39903. * Copies the values of the given spherical to this instance.
  39904. *
  39905. * @param {Spherical} other - The spherical to copy.
  39906. * @return {Spherical} A reference to this spherical.
  39907. */
  39908. copy( other ) {
  39909. this.radius = other.radius;
  39910. this.phi = other.phi;
  39911. this.theta = other.theta;
  39912. return this;
  39913. }
  39914. /**
  39915. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  39916. * `0.000001`.
  39917. *
  39918. * @return {Spherical} A reference to this spherical.
  39919. */
  39920. makeSafe() {
  39921. const EPS = 0.000001;
  39922. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  39923. return this;
  39924. }
  39925. /**
  39926. * Sets the spherical components from the given vector which is assumed to hold
  39927. * Cartesian coordinates.
  39928. *
  39929. * @param {Vector3} v - The vector to set.
  39930. * @return {Spherical} A reference to this spherical.
  39931. */
  39932. setFromVector3( v ) {
  39933. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39934. }
  39935. /**
  39936. * Sets the spherical components from the given Cartesian coordinates.
  39937. *
  39938. * @param {number} x - The x value.
  39939. * @param {number} y - The y value.
  39940. * @param {number} z - The z value.
  39941. * @return {Spherical} A reference to this spherical.
  39942. */
  39943. setFromCartesianCoords( x, y, z ) {
  39944. this.radius = Math.sqrt( x * x + y * y + z * z );
  39945. if ( this.radius === 0 ) {
  39946. this.theta = 0;
  39947. this.phi = 0;
  39948. } else {
  39949. this.theta = Math.atan2( x, z );
  39950. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  39951. }
  39952. return this;
  39953. }
  39954. /**
  39955. * Returns a new spherical with copied values from this instance.
  39956. *
  39957. * @return {Spherical} A clone of this instance.
  39958. */
  39959. clone() {
  39960. return new this.constructor().copy( this );
  39961. }
  39962. }
  39963. /**
  39964. * This class can be used to represent points in 3D space as
  39965. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  39966. */
  39967. class Cylindrical {
  39968. /**
  39969. * Constructs a new cylindrical.
  39970. *
  39971. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  39972. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39973. * @param {number} [y=0] - The height above the x-z plane.
  39974. */
  39975. constructor( radius = 1, theta = 0, y = 0 ) {
  39976. /**
  39977. * The distance from the origin to a point in the x-z plane.
  39978. *
  39979. * @type {number}
  39980. * @default 1
  39981. */
  39982. this.radius = radius;
  39983. /**
  39984. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39985. *
  39986. * @type {number}
  39987. * @default 0
  39988. */
  39989. this.theta = theta;
  39990. /**
  39991. * The height above the x-z plane.
  39992. *
  39993. * @type {number}
  39994. * @default 0
  39995. */
  39996. this.y = y;
  39997. }
  39998. /**
  39999. * Sets the cylindrical components by copying the given values.
  40000. *
  40001. * @param {number} radius - The radius.
  40002. * @param {number} theta - The theta angle.
  40003. * @param {number} y - The height value.
  40004. * @return {Cylindrical} A reference to this cylindrical.
  40005. */
  40006. set( radius, theta, y ) {
  40007. this.radius = radius;
  40008. this.theta = theta;
  40009. this.y = y;
  40010. return this;
  40011. }
  40012. /**
  40013. * Copies the values of the given cylindrical to this instance.
  40014. *
  40015. * @param {Cylindrical} other - The cylindrical to copy.
  40016. * @return {Cylindrical} A reference to this cylindrical.
  40017. */
  40018. copy( other ) {
  40019. this.radius = other.radius;
  40020. this.theta = other.theta;
  40021. this.y = other.y;
  40022. return this;
  40023. }
  40024. /**
  40025. * Sets the cylindrical components from the given vector which is assumed to hold
  40026. * Cartesian coordinates.
  40027. *
  40028. * @param {Vector3} v - The vector to set.
  40029. * @return {Cylindrical} A reference to this cylindrical.
  40030. */
  40031. setFromVector3( v ) {
  40032. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40033. }
  40034. /**
  40035. * Sets the cylindrical components from the given Cartesian coordinates.
  40036. *
  40037. * @param {number} x - The x value.
  40038. * @param {number} y - The x value.
  40039. * @param {number} z - The x value.
  40040. * @return {Cylindrical} A reference to this cylindrical.
  40041. */
  40042. setFromCartesianCoords( x, y, z ) {
  40043. this.radius = Math.sqrt( x * x + z * z );
  40044. this.theta = Math.atan2( x, z );
  40045. this.y = y;
  40046. return this;
  40047. }
  40048. /**
  40049. * Returns a new cylindrical with copied values from this instance.
  40050. *
  40051. * @return {Cylindrical} A clone of this instance.
  40052. */
  40053. clone() {
  40054. return new this.constructor().copy( this );
  40055. }
  40056. }
  40057. /**
  40058. * Represents a 2x2 matrix.
  40059. *
  40060. * A Note on Row-Major and Column-Major Ordering:
  40061. *
  40062. * The constructor and {@link Matrix2#set} method take arguments in
  40063. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  40064. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40065. * This means that calling:
  40066. * ```js
  40067. * const m = new THREE.Matrix2();
  40068. * m.set( 11, 12,
  40069. * 21, 22 );
  40070. * ```
  40071. * will result in the elements array containing:
  40072. * ```js
  40073. * m.elements = [ 11, 21,
  40074. * 12, 22 ];
  40075. * ```
  40076. * and internally all calculations are performed using column-major ordering.
  40077. * However, as the actual ordering makes no difference mathematically and
  40078. * most people are used to thinking about matrices in row-major order, the
  40079. * three.js documentation shows matrices in row-major order. Just bear in
  40080. * mind that if you are reading the source code, you'll have to take the
  40081. * transpose of any matrices outlined here to make sense of the calculations.
  40082. */
  40083. class Matrix2 {
  40084. /**
  40085. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40086. * in row-major order. If no arguments are provided, the constructor
  40087. * initializes the matrix as an identity matrix.
  40088. *
  40089. * @param {number} [n11] - 1-1 matrix element.
  40090. * @param {number} [n12] - 1-2 matrix element.
  40091. * @param {number} [n21] - 2-1 matrix element.
  40092. * @param {number} [n22] - 2-2 matrix element.
  40093. */
  40094. constructor( n11, n12, n21, n22 ) {
  40095. /**
  40096. * This flag can be used for type testing.
  40097. *
  40098. * @type {boolean}
  40099. * @readonly
  40100. * @default true
  40101. */
  40102. Matrix2.prototype.isMatrix2 = true;
  40103. /**
  40104. * A column-major list of matrix values.
  40105. *
  40106. * @type {Array<number>}
  40107. */
  40108. this.elements = [
  40109. 1, 0,
  40110. 0, 1,
  40111. ];
  40112. if ( n11 !== undefined ) {
  40113. this.set( n11, n12, n21, n22 );
  40114. }
  40115. }
  40116. /**
  40117. * Sets this matrix to the 2x2 identity matrix.
  40118. *
  40119. * @return {Matrix2} A reference to this matrix.
  40120. */
  40121. identity() {
  40122. this.set(
  40123. 1, 0,
  40124. 0, 1,
  40125. );
  40126. return this;
  40127. }
  40128. /**
  40129. * Sets the elements of the matrix from the given array.
  40130. *
  40131. * @param {Array<number>} array - The matrix elements in column-major order.
  40132. * @param {number} [offset=0] - Index of the first element in the array.
  40133. * @return {Matrix2} A reference to this matrix.
  40134. */
  40135. fromArray( array, offset = 0 ) {
  40136. for ( let i = 0; i < 4; i ++ ) {
  40137. this.elements[ i ] = array[ i + offset ];
  40138. }
  40139. return this;
  40140. }
  40141. /**
  40142. * Sets the elements of the matrix.The arguments are supposed to be
  40143. * in row-major order.
  40144. *
  40145. * @param {number} n11 - 1-1 matrix element.
  40146. * @param {number} n12 - 1-2 matrix element.
  40147. * @param {number} n21 - 2-1 matrix element.
  40148. * @param {number} n22 - 2-2 matrix element.
  40149. * @return {Matrix2} A reference to this matrix.
  40150. */
  40151. set( n11, n12, n21, n22 ) {
  40152. const te = this.elements;
  40153. te[ 0 ] = n11; te[ 2 ] = n12;
  40154. te[ 1 ] = n21; te[ 3 ] = n22;
  40155. return this;
  40156. }
  40157. }
  40158. const _vector$4 = /*@__PURE__*/ new Vector2();
  40159. /**
  40160. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40161. */
  40162. class Box2 {
  40163. /**
  40164. * Constructs a new bounding box.
  40165. *
  40166. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40167. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40168. */
  40169. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40170. /**
  40171. * This flag can be used for type testing.
  40172. *
  40173. * @type {boolean}
  40174. * @readonly
  40175. * @default true
  40176. */
  40177. this.isBox2 = true;
  40178. /**
  40179. * The lower boundary of the box.
  40180. *
  40181. * @type {Vector2}
  40182. */
  40183. this.min = min;
  40184. /**
  40185. * The upper boundary of the box.
  40186. *
  40187. * @type {Vector2}
  40188. */
  40189. this.max = max;
  40190. }
  40191. /**
  40192. * Sets the lower and upper boundaries of this box.
  40193. * Please note that this method only copies the values from the given objects.
  40194. *
  40195. * @param {Vector2} min - The lower boundary of the box.
  40196. * @param {Vector2} max - The upper boundary of the box.
  40197. * @return {Box2} A reference to this bounding box.
  40198. */
  40199. set( min, max ) {
  40200. this.min.copy( min );
  40201. this.max.copy( max );
  40202. return this;
  40203. }
  40204. /**
  40205. * Sets the upper and lower bounds of this box so it encloses the position data
  40206. * in the given array.
  40207. *
  40208. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40209. * @return {Box2} A reference to this bounding box.
  40210. */
  40211. setFromPoints( points ) {
  40212. this.makeEmpty();
  40213. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40214. this.expandByPoint( points[ i ] );
  40215. }
  40216. return this;
  40217. }
  40218. /**
  40219. * Centers this box on the given center vector and sets this box's width, height and
  40220. * depth to the given size values.
  40221. *
  40222. * @param {Vector2} center - The center of the box.
  40223. * @param {Vector2} size - The x and y dimensions of the box.
  40224. * @return {Box2} A reference to this bounding box.
  40225. */
  40226. setFromCenterAndSize( center, size ) {
  40227. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40228. this.min.copy( center ).sub( halfSize );
  40229. this.max.copy( center ).add( halfSize );
  40230. return this;
  40231. }
  40232. /**
  40233. * Returns a new box with copied values from this instance.
  40234. *
  40235. * @return {Box2} A clone of this instance.
  40236. */
  40237. clone() {
  40238. return new this.constructor().copy( this );
  40239. }
  40240. /**
  40241. * Copies the values of the given box to this instance.
  40242. *
  40243. * @param {Box2} box - The box to copy.
  40244. * @return {Box2} A reference to this bounding box.
  40245. */
  40246. copy( box ) {
  40247. this.min.copy( box.min );
  40248. this.max.copy( box.max );
  40249. return this;
  40250. }
  40251. /**
  40252. * Makes this box empty which means in encloses a zero space in 2D.
  40253. *
  40254. * @return {Box2} A reference to this bounding box.
  40255. */
  40256. makeEmpty() {
  40257. this.min.x = this.min.y = + Infinity;
  40258. this.max.x = this.max.y = - Infinity;
  40259. return this;
  40260. }
  40261. /**
  40262. * Returns true if this box includes zero points within its bounds.
  40263. * Note that a box with equal lower and upper bounds still includes one
  40264. * point, the one both bounds share.
  40265. *
  40266. * @return {boolean} Whether this box is empty or not.
  40267. */
  40268. isEmpty() {
  40269. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40270. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40271. }
  40272. /**
  40273. * Returns the center point of this box.
  40274. *
  40275. * @param {Vector2} target - The target vector that is used to store the method's result.
  40276. * @return {Vector2} The center point.
  40277. */
  40278. getCenter( target ) {
  40279. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40280. }
  40281. /**
  40282. * Returns the dimensions of this box.
  40283. *
  40284. * @param {Vector2} target - The target vector that is used to store the method's result.
  40285. * @return {Vector2} The size.
  40286. */
  40287. getSize( target ) {
  40288. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40289. }
  40290. /**
  40291. * Expands the boundaries of this box to include the given point.
  40292. *
  40293. * @param {Vector2} point - The point that should be included by the bounding box.
  40294. * @return {Box2} A reference to this bounding box.
  40295. */
  40296. expandByPoint( point ) {
  40297. this.min.min( point );
  40298. this.max.max( point );
  40299. return this;
  40300. }
  40301. /**
  40302. * Expands this box equilaterally by the given vector. The width of this
  40303. * box will be expanded by the x component of the vector in both
  40304. * directions. The height of this box will be expanded by the y component of
  40305. * the vector in both directions.
  40306. *
  40307. * @param {Vector2} vector - The vector that should expand the bounding box.
  40308. * @return {Box2} A reference to this bounding box.
  40309. */
  40310. expandByVector( vector ) {
  40311. this.min.sub( vector );
  40312. this.max.add( vector );
  40313. return this;
  40314. }
  40315. /**
  40316. * Expands each dimension of the box by the given scalar. If negative, the
  40317. * dimensions of the box will be contracted.
  40318. *
  40319. * @param {number} scalar - The scalar value that should expand the bounding box.
  40320. * @return {Box2} A reference to this bounding box.
  40321. */
  40322. expandByScalar( scalar ) {
  40323. this.min.addScalar( - scalar );
  40324. this.max.addScalar( scalar );
  40325. return this;
  40326. }
  40327. /**
  40328. * Returns `true` if the given point lies within or on the boundaries of this box.
  40329. *
  40330. * @param {Vector2} point - The point to test.
  40331. * @return {boolean} Whether the bounding box contains the given point or not.
  40332. */
  40333. containsPoint( point ) {
  40334. return point.x >= this.min.x && point.x <= this.max.x &&
  40335. point.y >= this.min.y && point.y <= this.max.y;
  40336. }
  40337. /**
  40338. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40339. * If this box and the given one are identical, this function also returns `true`.
  40340. *
  40341. * @param {Box2} box - The bounding box to test.
  40342. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40343. */
  40344. containsBox( box ) {
  40345. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40346. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40347. }
  40348. /**
  40349. * Returns a point as a proportion of this box's width and height.
  40350. *
  40351. * @param {Vector2} point - A point in 2D space.
  40352. * @param {Vector2} target - The target vector that is used to store the method's result.
  40353. * @return {Vector2} A point as a proportion of this box's width and height.
  40354. */
  40355. getParameter( point, target ) {
  40356. // This can potentially have a divide by zero if the box
  40357. // has a size dimension of 0.
  40358. return target.set(
  40359. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40360. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40361. );
  40362. }
  40363. /**
  40364. * Returns `true` if the given bounding box intersects with this bounding box.
  40365. *
  40366. * @param {Box2} box - The bounding box to test.
  40367. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40368. */
  40369. intersectsBox( box ) {
  40370. // using 4 splitting planes to rule out intersections
  40371. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40372. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40373. }
  40374. /**
  40375. * Clamps the given point within the bounds of this box.
  40376. *
  40377. * @param {Vector2} point - The point to clamp.
  40378. * @param {Vector2} target - The target vector that is used to store the method's result.
  40379. * @return {Vector2} The clamped point.
  40380. */
  40381. clampPoint( point, target ) {
  40382. return target.copy( point ).clamp( this.min, this.max );
  40383. }
  40384. /**
  40385. * Returns the euclidean distance from any edge of this box to the specified point. If
  40386. * the given point lies inside of this box, the distance will be `0`.
  40387. *
  40388. * @param {Vector2} point - The point to compute the distance to.
  40389. * @return {number} The euclidean distance.
  40390. */
  40391. distanceToPoint( point ) {
  40392. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40393. }
  40394. /**
  40395. * Computes the intersection of this bounding box and the given one, setting the upper
  40396. * bound of this box to the lesser of the two boxes' upper bounds and the
  40397. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40398. * there's no overlap, makes this box empty.
  40399. *
  40400. * @param {Box2} box - The bounding box to intersect with.
  40401. * @return {Box2} A reference to this bounding box.
  40402. */
  40403. intersect( box ) {
  40404. this.min.max( box.min );
  40405. this.max.min( box.max );
  40406. if ( this.isEmpty() ) this.makeEmpty();
  40407. return this;
  40408. }
  40409. /**
  40410. * Computes the union of this box and another and the given one, setting the upper
  40411. * bound of this box to the greater of the two boxes' upper bounds and the
  40412. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40413. *
  40414. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40415. * @return {Box2} A reference to this bounding box.
  40416. */
  40417. union( box ) {
  40418. this.min.min( box.min );
  40419. this.max.max( box.max );
  40420. return this;
  40421. }
  40422. /**
  40423. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40424. * effectively moving it in 2D space.
  40425. *
  40426. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40427. * @return {Box2} A reference to this bounding box.
  40428. */
  40429. translate( offset ) {
  40430. this.min.add( offset );
  40431. this.max.add( offset );
  40432. return this;
  40433. }
  40434. /**
  40435. * Returns `true` if this bounding box is equal with the given one.
  40436. *
  40437. * @param {Box2} box - The box to test for equality.
  40438. * @return {boolean} Whether this bounding box is equal with the given one.
  40439. */
  40440. equals( box ) {
  40441. return box.min.equals( this.min ) && box.max.equals( this.max );
  40442. }
  40443. }
  40444. const _startP = /*@__PURE__*/ new Vector3();
  40445. const _startEnd = /*@__PURE__*/ new Vector3();
  40446. const _d1 = /*@__PURE__*/ new Vector3();
  40447. const _d2 = /*@__PURE__*/ new Vector3();
  40448. const _r = /*@__PURE__*/ new Vector3();
  40449. const _c1 = /*@__PURE__*/ new Vector3();
  40450. const _c2 = /*@__PURE__*/ new Vector3();
  40451. /**
  40452. * An analytical line segment in 3D space represented by a start and end point.
  40453. */
  40454. class Line3 {
  40455. /**
  40456. * Constructs a new line segment.
  40457. *
  40458. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40459. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40460. */
  40461. constructor( start = new Vector3(), end = new Vector3() ) {
  40462. /**
  40463. * Start of the line segment.
  40464. *
  40465. * @type {Vector3}
  40466. */
  40467. this.start = start;
  40468. /**
  40469. * End of the line segment.
  40470. *
  40471. * @type {Vector3}
  40472. */
  40473. this.end = end;
  40474. }
  40475. /**
  40476. * Sets the start and end values by copying the given vectors.
  40477. *
  40478. * @param {Vector3} start - The start point.
  40479. * @param {Vector3} end - The end point.
  40480. * @return {Line3} A reference to this line segment.
  40481. */
  40482. set( start, end ) {
  40483. this.start.copy( start );
  40484. this.end.copy( end );
  40485. return this;
  40486. }
  40487. /**
  40488. * Copies the values of the given line segment to this instance.
  40489. *
  40490. * @param {Line3} line - The line segment to copy.
  40491. * @return {Line3} A reference to this line segment.
  40492. */
  40493. copy( line ) {
  40494. this.start.copy( line.start );
  40495. this.end.copy( line.end );
  40496. return this;
  40497. }
  40498. /**
  40499. * Returns the center of the line segment.
  40500. *
  40501. * @param {Vector3} target - The target vector that is used to store the method's result.
  40502. * @return {Vector3} The center point.
  40503. */
  40504. getCenter( target ) {
  40505. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40506. }
  40507. /**
  40508. * Returns the delta vector of the line segment's start and end point.
  40509. *
  40510. * @param {Vector3} target - The target vector that is used to store the method's result.
  40511. * @return {Vector3} The delta vector.
  40512. */
  40513. delta( target ) {
  40514. return target.subVectors( this.end, this.start );
  40515. }
  40516. /**
  40517. * Returns the squared Euclidean distance between the line' start and end point.
  40518. *
  40519. * @return {number} The squared Euclidean distance.
  40520. */
  40521. distanceSq() {
  40522. return this.start.distanceToSquared( this.end );
  40523. }
  40524. /**
  40525. * Returns the Euclidean distance between the line' start and end point.
  40526. *
  40527. * @return {number} The Euclidean distance.
  40528. */
  40529. distance() {
  40530. return this.start.distanceTo( this.end );
  40531. }
  40532. /**
  40533. * Returns a vector at a certain position along the line segment.
  40534. *
  40535. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40536. * @param {Vector3} target - The target vector that is used to store the method's result.
  40537. * @return {Vector3} The delta vector.
  40538. */
  40539. at( t, target ) {
  40540. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40541. }
  40542. /**
  40543. * Returns a point parameter based on the closest point as projected on the line segment.
  40544. *
  40545. * @param {Vector3} point - The point for which to return a point parameter.
  40546. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40547. * @return {number} The point parameter.
  40548. */
  40549. closestPointToPointParameter( point, clampToLine ) {
  40550. _startP.subVectors( point, this.start );
  40551. _startEnd.subVectors( this.end, this.start );
  40552. const startEnd2 = _startEnd.dot( _startEnd );
  40553. const startEnd_startP = _startEnd.dot( _startP );
  40554. let t = startEnd_startP / startEnd2;
  40555. if ( clampToLine ) {
  40556. t = clamp( t, 0, 1 );
  40557. }
  40558. return t;
  40559. }
  40560. /**
  40561. * Returns the closest point on the line for a given point.
  40562. *
  40563. * @param {Vector3} point - The point to compute the closest point on the line for.
  40564. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40565. * @param {Vector3} target - The target vector that is used to store the method's result.
  40566. * @return {Vector3} The closest point on the line.
  40567. */
  40568. closestPointToPoint( point, clampToLine, target ) {
  40569. const t = this.closestPointToPointParameter( point, clampToLine );
  40570. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40571. }
  40572. /**
  40573. * Returns the closest squared distance between this line segment and the given one.
  40574. *
  40575. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40576. * @param {Vector3} [c1] - The closest point on this line segment.
  40577. * @param {Vector3} [c2] - The closest point on the given line segment.
  40578. * @return {number} The squared distance between this line segment and the given one.
  40579. */
  40580. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40581. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40582. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40583. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40584. // distance between between S1(s) and S2(t)
  40585. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40586. let s, t;
  40587. const p1 = this.start;
  40588. const p2 = line.start;
  40589. const q1 = this.end;
  40590. const q2 = line.end;
  40591. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40592. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40593. _r.subVectors( p1, p2 );
  40594. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40595. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40596. const f = _d2.dot( _r );
  40597. // Check if either or both segments degenerate into points
  40598. if ( a <= EPSILON && e <= EPSILON ) {
  40599. // Both segments degenerate into points
  40600. c1.copy( p1 );
  40601. c2.copy( p2 );
  40602. c1.sub( c2 );
  40603. return c1.dot( c1 );
  40604. }
  40605. if ( a <= EPSILON ) {
  40606. // First segment degenerates into a point
  40607. s = 0;
  40608. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40609. t = clamp( t, 0, 1 );
  40610. } else {
  40611. const c = _d1.dot( _r );
  40612. if ( e <= EPSILON ) {
  40613. // Second segment degenerates into a point
  40614. t = 0;
  40615. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40616. } else {
  40617. // The general nondegenerate case starts here
  40618. const b = _d1.dot( _d2 );
  40619. const denom = a * e - b * b; // Always nonnegative
  40620. // If segments not parallel, compute closest point on L1 to L2 and
  40621. // clamp to segment S1. Else pick arbitrary s (here 0)
  40622. if ( denom !== 0 ) {
  40623. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40624. } else {
  40625. s = 0;
  40626. }
  40627. // Compute point on L2 closest to S1(s) using
  40628. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40629. t = ( b * s + f ) / e;
  40630. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40631. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40632. // and clamp s to [0, 1]
  40633. if ( t < 0 ) {
  40634. t = 0.;
  40635. s = clamp( - c / a, 0, 1 );
  40636. } else if ( t > 1 ) {
  40637. t = 1;
  40638. s = clamp( ( b - c ) / a, 0, 1 );
  40639. }
  40640. }
  40641. }
  40642. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40643. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40644. c1.sub( c2 );
  40645. return c1.dot( c1 );
  40646. }
  40647. /**
  40648. * Applies a 4x4 transformation matrix to this line segment.
  40649. *
  40650. * @param {Matrix4} matrix - The transformation matrix.
  40651. * @return {Line3} A reference to this line segment.
  40652. */
  40653. applyMatrix4( matrix ) {
  40654. this.start.applyMatrix4( matrix );
  40655. this.end.applyMatrix4( matrix );
  40656. return this;
  40657. }
  40658. /**
  40659. * Returns `true` if this line segment is equal with the given one.
  40660. *
  40661. * @param {Line3} line - The line segment to test for equality.
  40662. * @return {boolean} Whether this line segment is equal with the given one.
  40663. */
  40664. equals( line ) {
  40665. return line.start.equals( this.start ) && line.end.equals( this.end );
  40666. }
  40667. /**
  40668. * Returns a new line segment with copied values from this instance.
  40669. *
  40670. * @return {Line3} A clone of this instance.
  40671. */
  40672. clone() {
  40673. return new this.constructor().copy( this );
  40674. }
  40675. }
  40676. const _vector$3 = /*@__PURE__*/ new Vector3();
  40677. /**
  40678. * This displays a cone shaped helper object for a {@link SpotLight}.
  40679. *
  40680. * ```js
  40681. * const spotLight = new THREE.SpotLight( 0xffffff );
  40682. * spotLight.position.set( 10, 10, 10 );
  40683. * scene.add( spotLight );
  40684. *
  40685. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40686. * scene.add( spotLightHelper );
  40687. * ```
  40688. *
  40689. * @augments Object3D
  40690. */
  40691. class SpotLightHelper extends Object3D {
  40692. /**
  40693. * Constructs a new spot light helper.
  40694. *
  40695. * @param {HemisphereLight} light - The light to be visualized.
  40696. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40697. * the color of the light.
  40698. */
  40699. constructor( light, color ) {
  40700. super();
  40701. /**
  40702. * The light being visualized.
  40703. *
  40704. * @type {SpotLight}
  40705. */
  40706. this.light = light;
  40707. this.matrixAutoUpdate = false;
  40708. /**
  40709. * The color parameter passed in the constructor.
  40710. * If not set, the helper will take the color of the light.
  40711. *
  40712. * @type {number|Color|string}
  40713. */
  40714. this.color = color;
  40715. this.type = 'SpotLightHelper';
  40716. const geometry = new BufferGeometry();
  40717. const positions = [
  40718. 0, 0, 0, 0, 0, 1,
  40719. 0, 0, 0, 1, 0, 1,
  40720. 0, 0, 0, -1, 0, 1,
  40721. 0, 0, 0, 0, 1, 1,
  40722. 0, 0, 0, 0, -1, 1
  40723. ];
  40724. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40725. const p1 = ( i / l ) * Math.PI * 2;
  40726. const p2 = ( j / l ) * Math.PI * 2;
  40727. positions.push(
  40728. Math.cos( p1 ), Math.sin( p1 ), 1,
  40729. Math.cos( p2 ), Math.sin( p2 ), 1
  40730. );
  40731. }
  40732. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40733. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40734. this.cone = new LineSegments( geometry, material );
  40735. this.add( this.cone );
  40736. this.update();
  40737. }
  40738. /**
  40739. * Frees the GPU-related resources allocated by this instance. Call this
  40740. * method whenever this instance is no longer used in your app.
  40741. */
  40742. dispose() {
  40743. this.cone.geometry.dispose();
  40744. this.cone.material.dispose();
  40745. }
  40746. /**
  40747. * Updates the helper to match the position and direction of the
  40748. * light being visualized.
  40749. */
  40750. update() {
  40751. this.light.updateWorldMatrix( true, false );
  40752. this.light.target.updateWorldMatrix( true, false );
  40753. // update the local matrix based on the parent and light target transforms
  40754. if ( this.parent ) {
  40755. this.parent.updateWorldMatrix( true );
  40756. this.matrix
  40757. .copy( this.parent.matrixWorld )
  40758. .invert()
  40759. .multiply( this.light.matrixWorld );
  40760. } else {
  40761. this.matrix.copy( this.light.matrixWorld );
  40762. }
  40763. this.matrixWorld.copy( this.light.matrixWorld );
  40764. const coneLength = this.light.distance ? this.light.distance : 1000;
  40765. const coneWidth = coneLength * Math.tan( this.light.angle );
  40766. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  40767. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  40768. this.cone.lookAt( _vector$3 );
  40769. if ( this.color !== undefined ) {
  40770. this.cone.material.color.set( this.color );
  40771. } else {
  40772. this.cone.material.color.copy( this.light.color );
  40773. }
  40774. }
  40775. }
  40776. const _vector$2 = /*@__PURE__*/ new Vector3();
  40777. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  40778. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  40779. /**
  40780. * A helper object to assist with visualizing a {@link Skeleton}.
  40781. *
  40782. * ```js
  40783. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  40784. * scene.add( helper );
  40785. * ```
  40786. *
  40787. * @augments LineSegments
  40788. */
  40789. class SkeletonHelper extends LineSegments {
  40790. /**
  40791. * Constructs a new skeleton helper.
  40792. *
  40793. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  40794. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  40795. */
  40796. constructor( object ) {
  40797. const bones = getBoneList( object );
  40798. const geometry = new BufferGeometry();
  40799. const vertices = [];
  40800. const colors = [];
  40801. for ( let i = 0; i < bones.length; i ++ ) {
  40802. const bone = bones[ i ];
  40803. if ( bone.parent && bone.parent.isBone ) {
  40804. vertices.push( 0, 0, 0 );
  40805. vertices.push( 0, 0, 0 );
  40806. colors.push( 0, 0, 0 );
  40807. colors.push( 0, 0, 0 );
  40808. }
  40809. }
  40810. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40811. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40812. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  40813. super( geometry, material );
  40814. /**
  40815. * This flag can be used for type testing.
  40816. *
  40817. * @type {boolean}
  40818. * @readonly
  40819. * @default true
  40820. */
  40821. this.isSkeletonHelper = true;
  40822. this.type = 'SkeletonHelper';
  40823. /**
  40824. * The object being visualized.
  40825. *
  40826. * @type {Object3D}
  40827. */
  40828. this.root = object;
  40829. /**
  40830. * The list of bones that the helper visualizes.
  40831. *
  40832. * @type {Array<Bone>}
  40833. */
  40834. this.bones = bones;
  40835. this.matrix = object.matrixWorld;
  40836. this.matrixAutoUpdate = false;
  40837. // colors
  40838. const color1 = new Color( 0x0000ff );
  40839. const color2 = new Color( 0x00ff00 );
  40840. this.setColors( color1, color2 );
  40841. }
  40842. updateMatrixWorld( force ) {
  40843. const bones = this.bones;
  40844. const geometry = this.geometry;
  40845. const position = geometry.getAttribute( 'position' );
  40846. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  40847. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  40848. const bone = bones[ i ];
  40849. if ( bone.parent && bone.parent.isBone ) {
  40850. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  40851. _vector$2.setFromMatrixPosition( _boneMatrix );
  40852. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  40853. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  40854. _vector$2.setFromMatrixPosition( _boneMatrix );
  40855. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  40856. j += 2;
  40857. }
  40858. }
  40859. geometry.getAttribute( 'position' ).needsUpdate = true;
  40860. super.updateMatrixWorld( force );
  40861. }
  40862. /**
  40863. * Defines the colors of the helper.
  40864. *
  40865. * @param {Color} color1 - The first line color for each bone.
  40866. * @param {Color} color2 - The second line color for each bone.
  40867. * @return {SkeletonHelper} A reference to this helper.
  40868. */
  40869. setColors( color1, color2 ) {
  40870. const geometry = this.geometry;
  40871. const colorAttribute = geometry.getAttribute( 'color' );
  40872. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  40873. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  40874. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  40875. }
  40876. colorAttribute.needsUpdate = true;
  40877. return this;
  40878. }
  40879. /**
  40880. * Frees the GPU-related resources allocated by this instance. Call this
  40881. * method whenever this instance is no longer used in your app.
  40882. */
  40883. dispose() {
  40884. this.geometry.dispose();
  40885. this.material.dispose();
  40886. }
  40887. }
  40888. function getBoneList( object ) {
  40889. const boneList = [];
  40890. if ( object.isBone === true ) {
  40891. boneList.push( object );
  40892. }
  40893. for ( let i = 0; i < object.children.length; i ++ ) {
  40894. boneList.push( ...getBoneList( object.children[ i ] ) );
  40895. }
  40896. return boneList;
  40897. }
  40898. /**
  40899. * This displays a helper object consisting of a spherical mesh for
  40900. * visualizing an instance of {@link PointLight}.
  40901. *
  40902. * ```js
  40903. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  40904. * pointLight.position.set( 10, 10, 10 );
  40905. * scene.add( pointLight );
  40906. *
  40907. * const sphereSize = 1;
  40908. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  40909. * scene.add( pointLightHelper );
  40910. * ```
  40911. *
  40912. * @augments Mesh
  40913. */
  40914. class PointLightHelper extends Mesh {
  40915. /**
  40916. * Constructs a new point light helper.
  40917. *
  40918. * @param {PointLight} light - The light to be visualized.
  40919. * @param {number} [sphereSize=1] - The size of the sphere helper.
  40920. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40921. * the color of the light.
  40922. */
  40923. constructor( light, sphereSize, color ) {
  40924. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  40925. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40926. super( geometry, material );
  40927. /**
  40928. * The light being visualized.
  40929. *
  40930. * @type {HemisphereLight}
  40931. */
  40932. this.light = light;
  40933. /**
  40934. * The color parameter passed in the constructor.
  40935. * If not set, the helper will take the color of the light.
  40936. *
  40937. * @type {number|Color|string}
  40938. */
  40939. this.color = color;
  40940. this.type = 'PointLightHelper';
  40941. this.matrix = this.light.matrixWorld;
  40942. this.matrixAutoUpdate = false;
  40943. this.update();
  40944. /*
  40945. // TODO: delete this comment?
  40946. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  40947. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  40948. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  40949. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  40950. const d = light.distance;
  40951. if ( d === 0.0 ) {
  40952. this.lightDistance.visible = false;
  40953. } else {
  40954. this.lightDistance.scale.set( d, d, d );
  40955. }
  40956. this.add( this.lightDistance );
  40957. */
  40958. }
  40959. /**
  40960. * Frees the GPU-related resources allocated by this instance. Call this
  40961. * method whenever this instance is no longer used in your app.
  40962. */
  40963. dispose() {
  40964. this.geometry.dispose();
  40965. this.material.dispose();
  40966. }
  40967. /**
  40968. * Updates the helper to match the position of the
  40969. * light being visualized.
  40970. */
  40971. update() {
  40972. this.light.updateWorldMatrix( true, false );
  40973. if ( this.color !== undefined ) {
  40974. this.material.color.set( this.color );
  40975. } else {
  40976. this.material.color.copy( this.light.color );
  40977. }
  40978. /*
  40979. const d = this.light.distance;
  40980. if ( d === 0.0 ) {
  40981. this.lightDistance.visible = false;
  40982. } else {
  40983. this.lightDistance.visible = true;
  40984. this.lightDistance.scale.set( d, d, d );
  40985. }
  40986. */
  40987. }
  40988. }
  40989. const _vector$1 = /*@__PURE__*/ new Vector3();
  40990. const _color1 = /*@__PURE__*/ new Color();
  40991. const _color2 = /*@__PURE__*/ new Color();
  40992. /**
  40993. * Creates a visual aid consisting of a spherical mesh for a
  40994. * given {@link HemisphereLight}.
  40995. *
  40996. * ```js
  40997. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  40998. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  40999. * scene.add( helper );
  41000. * ```
  41001. *
  41002. * @augments Object3D
  41003. */
  41004. class HemisphereLightHelper extends Object3D {
  41005. /**
  41006. * Constructs a new hemisphere light helper.
  41007. *
  41008. * @param {HemisphereLight} light - The light to be visualized.
  41009. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41010. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41011. * the color of the light.
  41012. */
  41013. constructor( light, size, color ) {
  41014. super();
  41015. /**
  41016. * The light being visualized.
  41017. *
  41018. * @type {HemisphereLight}
  41019. */
  41020. this.light = light;
  41021. this.matrix = light.matrixWorld;
  41022. this.matrixAutoUpdate = false;
  41023. /**
  41024. * The color parameter passed in the constructor.
  41025. * If not set, the helper will take the color of the light.
  41026. *
  41027. * @type {number|Color|string}
  41028. */
  41029. this.color = color;
  41030. this.type = 'HemisphereLightHelper';
  41031. const geometry = new OctahedronGeometry( size );
  41032. geometry.rotateY( Math.PI * 0.5 );
  41033. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41034. if ( this.color === undefined ) this.material.vertexColors = true;
  41035. const position = geometry.getAttribute( 'position' );
  41036. const colors = new Float32Array( position.count * 3 );
  41037. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41038. this.add( new Mesh( geometry, this.material ) );
  41039. this.update();
  41040. }
  41041. /**
  41042. * Frees the GPU-related resources allocated by this instance. Call this
  41043. * method whenever this instance is no longer used in your app.
  41044. */
  41045. dispose() {
  41046. this.children[ 0 ].geometry.dispose();
  41047. this.children[ 0 ].material.dispose();
  41048. }
  41049. /**
  41050. * Updates the helper to match the position and direction of the
  41051. * light being visualized.
  41052. */
  41053. update() {
  41054. const mesh = this.children[ 0 ];
  41055. if ( this.color !== undefined ) {
  41056. this.material.color.set( this.color );
  41057. } else {
  41058. const colors = mesh.geometry.getAttribute( 'color' );
  41059. _color1.copy( this.light.color );
  41060. _color2.copy( this.light.groundColor );
  41061. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41062. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41063. colors.setXYZ( i, color.r, color.g, color.b );
  41064. }
  41065. colors.needsUpdate = true;
  41066. }
  41067. this.light.updateWorldMatrix( true, false );
  41068. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41069. }
  41070. }
  41071. /**
  41072. * The helper is an object to define grids. Grids are two-dimensional
  41073. * arrays of lines.
  41074. *
  41075. * ```js
  41076. * const size = 10;
  41077. * const divisions = 10;
  41078. *
  41079. * const gridHelper = new THREE.GridHelper( size, divisions );
  41080. * scene.add( gridHelper );
  41081. * ```
  41082. *
  41083. * @augments LineSegments
  41084. */
  41085. class GridHelper extends LineSegments {
  41086. /**
  41087. * Constructs a new grid helper.
  41088. *
  41089. * @param {number} [size=10] - The size of the grid.
  41090. * @param {number} [divisions=10] - The number of divisions across the grid.
  41091. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41092. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41093. */
  41094. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41095. color1 = new Color( color1 );
  41096. color2 = new Color( color2 );
  41097. const center = divisions / 2;
  41098. const step = size / divisions;
  41099. const halfSize = size / 2;
  41100. const vertices = [], colors = [];
  41101. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41102. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41103. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41104. const color = i === center ? color1 : color2;
  41105. color.toArray( colors, j ); j += 3;
  41106. color.toArray( colors, j ); j += 3;
  41107. color.toArray( colors, j ); j += 3;
  41108. color.toArray( colors, j ); j += 3;
  41109. }
  41110. const geometry = new BufferGeometry();
  41111. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41112. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41113. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41114. super( geometry, material );
  41115. this.type = 'GridHelper';
  41116. }
  41117. /**
  41118. * Frees the GPU-related resources allocated by this instance. Call this
  41119. * method whenever this instance is no longer used in your app.
  41120. */
  41121. dispose() {
  41122. this.geometry.dispose();
  41123. this.material.dispose();
  41124. }
  41125. }
  41126. /**
  41127. * This helper is an object to define polar grids. Grids are
  41128. * two-dimensional arrays of lines.
  41129. *
  41130. * ```js
  41131. * const radius = 10;
  41132. * const sectors = 16;
  41133. * const rings = 8;
  41134. * const divisions = 64;
  41135. *
  41136. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41137. * scene.add( helper );
  41138. * ```
  41139. *
  41140. * @augments LineSegments
  41141. */
  41142. class PolarGridHelper extends LineSegments {
  41143. /**
  41144. * Constructs a new polar grid helper.
  41145. *
  41146. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41147. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41148. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41149. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41150. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41151. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41152. */
  41153. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41154. color1 = new Color( color1 );
  41155. color2 = new Color( color2 );
  41156. const vertices = [];
  41157. const colors = [];
  41158. // create the sectors
  41159. if ( sectors > 1 ) {
  41160. for ( let i = 0; i < sectors; i ++ ) {
  41161. const v = ( i / sectors ) * ( Math.PI * 2 );
  41162. const x = Math.sin( v ) * radius;
  41163. const z = Math.cos( v ) * radius;
  41164. vertices.push( 0, 0, 0 );
  41165. vertices.push( x, 0, z );
  41166. const color = ( i & 1 ) ? color1 : color2;
  41167. colors.push( color.r, color.g, color.b );
  41168. colors.push( color.r, color.g, color.b );
  41169. }
  41170. }
  41171. // create the rings
  41172. for ( let i = 0; i < rings; i ++ ) {
  41173. const color = ( i & 1 ) ? color1 : color2;
  41174. const r = radius - ( radius / rings * i );
  41175. for ( let j = 0; j < divisions; j ++ ) {
  41176. // first vertex
  41177. let v = ( j / divisions ) * ( Math.PI * 2 );
  41178. let x = Math.sin( v ) * r;
  41179. let z = Math.cos( v ) * r;
  41180. vertices.push( x, 0, z );
  41181. colors.push( color.r, color.g, color.b );
  41182. // second vertex
  41183. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41184. x = Math.sin( v ) * r;
  41185. z = Math.cos( v ) * r;
  41186. vertices.push( x, 0, z );
  41187. colors.push( color.r, color.g, color.b );
  41188. }
  41189. }
  41190. const geometry = new BufferGeometry();
  41191. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41192. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41193. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41194. super( geometry, material );
  41195. this.type = 'PolarGridHelper';
  41196. }
  41197. /**
  41198. * Frees the GPU-related resources allocated by this instance. Call this
  41199. * method whenever this instance is no longer used in your app.
  41200. */
  41201. dispose() {
  41202. this.geometry.dispose();
  41203. this.material.dispose();
  41204. }
  41205. }
  41206. const _v1 = /*@__PURE__*/ new Vector3();
  41207. const _v2 = /*@__PURE__*/ new Vector3();
  41208. const _v3 = /*@__PURE__*/ new Vector3();
  41209. /**
  41210. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41211. * effect on the scene. This consists of plane and a line representing the
  41212. * light's position and direction.
  41213. *
  41214. * ```js
  41215. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41216. * scene.add( light );
  41217. *
  41218. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41219. * scene.add( helper );
  41220. * ```
  41221. *
  41222. * @augments Object3D
  41223. */
  41224. class DirectionalLightHelper extends Object3D {
  41225. /**
  41226. * Constructs a new directional light helper.
  41227. *
  41228. * @param {DirectionalLight} light - The light to be visualized.
  41229. * @param {number} [size=1] - The dimensions of the plane.
  41230. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41231. * the color of the light.
  41232. */
  41233. constructor( light, size, color ) {
  41234. super();
  41235. /**
  41236. * The light being visualized.
  41237. *
  41238. * @type {DirectionalLight}
  41239. */
  41240. this.light = light;
  41241. this.matrix = light.matrixWorld;
  41242. this.matrixAutoUpdate = false;
  41243. /**
  41244. * The color parameter passed in the constructor.
  41245. * If not set, the helper will take the color of the light.
  41246. *
  41247. * @type {number|Color|string}
  41248. */
  41249. this.color = color;
  41250. this.type = 'DirectionalLightHelper';
  41251. if ( size === undefined ) size = 1;
  41252. let geometry = new BufferGeometry();
  41253. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41254. - size, size, 0,
  41255. size, size, 0,
  41256. size, - size, 0,
  41257. - size, - size, 0,
  41258. - size, size, 0
  41259. ], 3 ) );
  41260. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41261. /**
  41262. * Contains the line showing the location of the directional light.
  41263. *
  41264. * @type {Line}
  41265. */
  41266. this.lightPlane = new Line( geometry, material );
  41267. this.add( this.lightPlane );
  41268. geometry = new BufferGeometry();
  41269. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41270. /**
  41271. * Represents the target line of the directional light.
  41272. *
  41273. * @type {Line}
  41274. */
  41275. this.targetLine = new Line( geometry, material );
  41276. this.add( this.targetLine );
  41277. this.update();
  41278. }
  41279. /**
  41280. * Frees the GPU-related resources allocated by this instance. Call this
  41281. * method whenever this instance is no longer used in your app.
  41282. */
  41283. dispose() {
  41284. this.lightPlane.geometry.dispose();
  41285. this.lightPlane.material.dispose();
  41286. this.targetLine.geometry.dispose();
  41287. this.targetLine.material.dispose();
  41288. }
  41289. /**
  41290. * Updates the helper to match the position and direction of the
  41291. * light being visualized.
  41292. */
  41293. update() {
  41294. this.light.updateWorldMatrix( true, false );
  41295. this.light.target.updateWorldMatrix( true, false );
  41296. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41297. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41298. _v3.subVectors( _v2, _v1 );
  41299. this.lightPlane.lookAt( _v2 );
  41300. if ( this.color !== undefined ) {
  41301. this.lightPlane.material.color.set( this.color );
  41302. this.targetLine.material.color.set( this.color );
  41303. } else {
  41304. this.lightPlane.material.color.copy( this.light.color );
  41305. this.targetLine.material.color.copy( this.light.color );
  41306. }
  41307. this.targetLine.lookAt( _v2 );
  41308. this.targetLine.scale.z = _v3.length();
  41309. }
  41310. }
  41311. const _vector = /*@__PURE__*/ new Vector3();
  41312. const _camera = /*@__PURE__*/ new Camera();
  41313. /**
  41314. * This helps with visualizing what a camera contains in its frustum. It
  41315. * visualizes the frustum of a camera using a line segments.
  41316. *
  41317. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  41318. *
  41319. * `CameraHelper` must be a child of the scene.
  41320. *
  41321. * ```js
  41322. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41323. * const helper = new THREE.CameraHelper( camera );
  41324. * scene.add( helper );
  41325. * ```
  41326. *
  41327. * @augments LineSegments
  41328. */
  41329. class CameraHelper extends LineSegments {
  41330. /**
  41331. * Constructs a new arrow helper.
  41332. *
  41333. * @param {Camera} camera - The camera to visualize.
  41334. */
  41335. constructor( camera ) {
  41336. const geometry = new BufferGeometry();
  41337. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41338. const vertices = [];
  41339. const colors = [];
  41340. const pointMap = {};
  41341. // near
  41342. addLine( 'n1', 'n2' );
  41343. addLine( 'n2', 'n4' );
  41344. addLine( 'n4', 'n3' );
  41345. addLine( 'n3', 'n1' );
  41346. // far
  41347. addLine( 'f1', 'f2' );
  41348. addLine( 'f2', 'f4' );
  41349. addLine( 'f4', 'f3' );
  41350. addLine( 'f3', 'f1' );
  41351. // sides
  41352. addLine( 'n1', 'f1' );
  41353. addLine( 'n2', 'f2' );
  41354. addLine( 'n3', 'f3' );
  41355. addLine( 'n4', 'f4' );
  41356. // cone
  41357. addLine( 'p', 'n1' );
  41358. addLine( 'p', 'n2' );
  41359. addLine( 'p', 'n3' );
  41360. addLine( 'p', 'n4' );
  41361. // up
  41362. addLine( 'u1', 'u2' );
  41363. addLine( 'u2', 'u3' );
  41364. addLine( 'u3', 'u1' );
  41365. // target
  41366. addLine( 'c', 't' );
  41367. addLine( 'p', 'c' );
  41368. // cross
  41369. addLine( 'cn1', 'cn2' );
  41370. addLine( 'cn3', 'cn4' );
  41371. addLine( 'cf1', 'cf2' );
  41372. addLine( 'cf3', 'cf4' );
  41373. function addLine( a, b ) {
  41374. addPoint( a );
  41375. addPoint( b );
  41376. }
  41377. function addPoint( id ) {
  41378. vertices.push( 0, 0, 0 );
  41379. colors.push( 0, 0, 0 );
  41380. if ( pointMap[ id ] === undefined ) {
  41381. pointMap[ id ] = [];
  41382. }
  41383. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41384. }
  41385. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41386. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41387. super( geometry, material );
  41388. this.type = 'CameraHelper';
  41389. /**
  41390. * The camera being visualized.
  41391. *
  41392. * @type {Camera}
  41393. */
  41394. this.camera = camera;
  41395. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41396. this.matrix = camera.matrixWorld;
  41397. this.matrixAutoUpdate = false;
  41398. /**
  41399. * This contains the points used to visualize the camera.
  41400. *
  41401. * @type {Object<string,Array<number>>}
  41402. */
  41403. this.pointMap = pointMap;
  41404. this.update();
  41405. // colors
  41406. const colorFrustum = new Color( 0xffaa00 );
  41407. const colorCone = new Color( 0xff0000 );
  41408. const colorUp = new Color( 0x00aaff );
  41409. const colorTarget = new Color( 0xffffff );
  41410. const colorCross = new Color( 0x333333 );
  41411. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41412. }
  41413. /**
  41414. * Defines the colors of the helper.
  41415. *
  41416. * @param {Color} frustum - The frustum line color.
  41417. * @param {Color} cone - The cone line color.
  41418. * @param {Color} up - The up line color.
  41419. * @param {Color} target - The target line color.
  41420. * @param {Color} cross - The cross line color.
  41421. * @return {CameraHelper} A reference to this helper.
  41422. */
  41423. setColors( frustum, cone, up, target, cross ) {
  41424. const geometry = this.geometry;
  41425. const colorAttribute = geometry.getAttribute( 'color' );
  41426. // near
  41427. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41428. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41429. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41430. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41431. // far
  41432. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41433. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41434. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41435. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41436. // sides
  41437. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41438. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41439. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41440. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41441. // cone
  41442. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41443. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41444. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41445. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41446. // up
  41447. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41448. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41449. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41450. // target
  41451. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41452. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41453. // cross
  41454. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41455. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41456. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41457. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41458. colorAttribute.needsUpdate = true;
  41459. return this;
  41460. }
  41461. /**
  41462. * Updates the helper based on the projection matrix of the camera.
  41463. */
  41464. update() {
  41465. const geometry = this.geometry;
  41466. const pointMap = this.pointMap;
  41467. const w = 1, h = 1;
  41468. let nearZ, farZ;
  41469. // we need just camera projection matrix inverse
  41470. // world matrix must be identity
  41471. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41472. // Adjust z values based on coordinate system
  41473. if ( this.camera.reversedDepth === true ) {
  41474. nearZ = 1;
  41475. farZ = 0;
  41476. } else {
  41477. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41478. nearZ = -1;
  41479. farZ = 1;
  41480. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41481. nearZ = 0;
  41482. farZ = 1;
  41483. } else {
  41484. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41485. }
  41486. }
  41487. // center / target
  41488. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41489. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41490. // near
  41491. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41492. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41493. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41494. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41495. // far
  41496. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41497. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41498. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41499. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41500. // up
  41501. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41502. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41503. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41504. // cross
  41505. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41506. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41507. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41508. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41509. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41510. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41511. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41512. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41513. geometry.getAttribute( 'position' ).needsUpdate = true;
  41514. }
  41515. /**
  41516. * Frees the GPU-related resources allocated by this instance. Call this
  41517. * method whenever this instance is no longer used in your app.
  41518. */
  41519. dispose() {
  41520. this.geometry.dispose();
  41521. this.material.dispose();
  41522. }
  41523. }
  41524. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41525. _vector.set( x, y, z ).unproject( camera );
  41526. const points = pointMap[ point ];
  41527. if ( points !== undefined ) {
  41528. const position = geometry.getAttribute( 'position' );
  41529. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41530. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41531. }
  41532. }
  41533. }
  41534. const _box = /*@__PURE__*/ new Box3();
  41535. /**
  41536. * Helper object to graphically show the world-axis-aligned bounding box
  41537. * around an object. The actual bounding box is handled with {@link Box3},
  41538. * this is just a visual helper for debugging. It can be automatically
  41539. * resized with {@link BoxHelper#update} when the object it's created from
  41540. * is transformed. Note that the object must have a geometry for this to work,
  41541. * so it won't work with sprites.
  41542. *
  41543. * ```js
  41544. * const sphere = new THREE.SphereGeometry();
  41545. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41546. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41547. * scene.add( box );
  41548. * ```
  41549. *
  41550. * @augments LineSegments
  41551. */
  41552. class BoxHelper extends LineSegments {
  41553. /**
  41554. * Constructs a new box helper.
  41555. *
  41556. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41557. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41558. */
  41559. constructor( object, color = 0xffff00 ) {
  41560. const 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 ] );
  41561. const positions = new Float32Array( 8 * 3 );
  41562. const geometry = new BufferGeometry();
  41563. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41564. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41565. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41566. /**
  41567. * The 3D object being visualized.
  41568. *
  41569. * @type {Object3D}
  41570. */
  41571. this.object = object;
  41572. this.type = 'BoxHelper';
  41573. this.matrixAutoUpdate = false;
  41574. this.update();
  41575. }
  41576. /**
  41577. * Updates the helper's geometry to match the dimensions of the object,
  41578. * including any children.
  41579. */
  41580. update() {
  41581. if ( this.object !== undefined ) {
  41582. _box.setFromObject( this.object );
  41583. }
  41584. if ( _box.isEmpty() ) return;
  41585. const min = _box.min;
  41586. const max = _box.max;
  41587. /*
  41588. 5____4
  41589. 1/___0/|
  41590. | 6__|_7
  41591. 2/___3/
  41592. 0: max.x, max.y, max.z
  41593. 1: min.x, max.y, max.z
  41594. 2: min.x, min.y, max.z
  41595. 3: max.x, min.y, max.z
  41596. 4: max.x, max.y, min.z
  41597. 5: min.x, max.y, min.z
  41598. 6: min.x, min.y, min.z
  41599. 7: max.x, min.y, min.z
  41600. */
  41601. const position = this.geometry.attributes.position;
  41602. const array = position.array;
  41603. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41604. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41605. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41606. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41607. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41608. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41609. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41610. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41611. position.needsUpdate = true;
  41612. this.geometry.computeBoundingSphere();
  41613. }
  41614. /**
  41615. * Updates the wireframe box for the passed object.
  41616. *
  41617. * @param {Object3D} object - The 3D object to create the helper for.
  41618. * @return {BoxHelper} A reference to this instance.
  41619. */
  41620. setFromObject( object ) {
  41621. this.object = object;
  41622. this.update();
  41623. return this;
  41624. }
  41625. copy( source, recursive ) {
  41626. super.copy( source, recursive );
  41627. this.object = source.object;
  41628. return this;
  41629. }
  41630. /**
  41631. * Frees the GPU-related resources allocated by this instance. Call this
  41632. * method whenever this instance is no longer used in your app.
  41633. */
  41634. dispose() {
  41635. this.geometry.dispose();
  41636. this.material.dispose();
  41637. }
  41638. }
  41639. /**
  41640. * A helper object to visualize an instance of {@link Box3}.
  41641. *
  41642. * ```js
  41643. * const box = new THREE.Box3();
  41644. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41645. *
  41646. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41647. * scene.add( helper )
  41648. * ```
  41649. *
  41650. * @augments LineSegments
  41651. */
  41652. class Box3Helper extends LineSegments {
  41653. /**
  41654. * Constructs a new box3 helper.
  41655. *
  41656. * @param {Box3} box - The box to visualize.
  41657. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41658. */
  41659. constructor( box, color = 0xffff00 ) {
  41660. const 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 ] );
  41661. const positions = [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1 ];
  41662. const geometry = new BufferGeometry();
  41663. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41664. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41665. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41666. /**
  41667. * The box being visualized.
  41668. *
  41669. * @type {Box3}
  41670. */
  41671. this.box = box;
  41672. this.type = 'Box3Helper';
  41673. this.geometry.computeBoundingSphere();
  41674. }
  41675. updateMatrixWorld( force ) {
  41676. const box = this.box;
  41677. if ( box.isEmpty() ) return;
  41678. box.getCenter( this.position );
  41679. box.getSize( this.scale );
  41680. this.scale.multiplyScalar( 0.5 );
  41681. super.updateMatrixWorld( force );
  41682. }
  41683. /**
  41684. * Frees the GPU-related resources allocated by this instance. Call this
  41685. * method whenever this instance is no longer used in your app.
  41686. */
  41687. dispose() {
  41688. this.geometry.dispose();
  41689. this.material.dispose();
  41690. }
  41691. }
  41692. /**
  41693. * A helper object to visualize an instance of {@link Plane}.
  41694. *
  41695. * ```js
  41696. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41697. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41698. * scene.add( helper );
  41699. * ```
  41700. *
  41701. * @augments Line
  41702. */
  41703. class PlaneHelper extends Line {
  41704. /**
  41705. * Constructs a new plane helper.
  41706. *
  41707. * @param {Plane} plane - The plane to be visualized.
  41708. * @param {number} [size=1] - The side length of plane helper.
  41709. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41710. */
  41711. constructor( plane, size = 1, hex = 0xffff00 ) {
  41712. const color = hex;
  41713. const positions = [ 1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0 ];
  41714. const geometry = new BufferGeometry();
  41715. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41716. geometry.computeBoundingSphere();
  41717. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41718. this.type = 'PlaneHelper';
  41719. /**
  41720. * The plane being visualized.
  41721. *
  41722. * @type {Plane}
  41723. */
  41724. this.plane = plane;
  41725. /**
  41726. * The side length of plane helper.
  41727. *
  41728. * @type {number}
  41729. * @default 1
  41730. */
  41731. this.size = size;
  41732. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41733. const geometry2 = new BufferGeometry();
  41734. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41735. geometry2.computeBoundingSphere();
  41736. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  41737. }
  41738. updateMatrixWorld( force ) {
  41739. this.position.set( 0, 0, 0 );
  41740. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  41741. this.lookAt( this.plane.normal );
  41742. this.translateZ( - this.plane.constant );
  41743. super.updateMatrixWorld( force );
  41744. }
  41745. /**
  41746. * Updates the helper to match the position and direction of the
  41747. * light being visualized.
  41748. */
  41749. dispose() {
  41750. this.geometry.dispose();
  41751. this.material.dispose();
  41752. this.children[ 0 ].geometry.dispose();
  41753. this.children[ 0 ].material.dispose();
  41754. }
  41755. }
  41756. const _axis = /*@__PURE__*/ new Vector3();
  41757. let _lineGeometry, _coneGeometry;
  41758. /**
  41759. * An 3D arrow object for visualizing directions.
  41760. *
  41761. * ```js
  41762. * const dir = new THREE.Vector3( 1, 2, 0 );
  41763. *
  41764. * //normalize the direction vector (convert to vector of length 1)
  41765. * dir.normalize();
  41766. *
  41767. * const origin = new THREE.Vector3( 0, 0, 0 );
  41768. * const length = 1;
  41769. * const hex = 0xffff00;
  41770. *
  41771. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  41772. * scene.add( arrowHelper );
  41773. * ```
  41774. *
  41775. * @augments Object3D
  41776. */
  41777. class ArrowHelper extends Object3D {
  41778. /**
  41779. * Constructs a new arrow helper.
  41780. *
  41781. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  41782. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  41783. * @param {number} [length=1] - Length of the arrow in world units.
  41784. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  41785. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41786. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41787. */
  41788. constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  41789. super();
  41790. this.type = 'ArrowHelper';
  41791. if ( _lineGeometry === undefined ) {
  41792. _lineGeometry = new BufferGeometry();
  41793. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  41794. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  41795. _coneGeometry.translate( 0, -0.5, 0 );
  41796. }
  41797. this.position.copy( origin );
  41798. /**
  41799. * The line part of the arrow helper.
  41800. *
  41801. * @type {Line}
  41802. */
  41803. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41804. this.line.matrixAutoUpdate = false;
  41805. this.add( this.line );
  41806. /**
  41807. * The cone part of the arrow helper.
  41808. *
  41809. * @type {Mesh}
  41810. */
  41811. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  41812. this.cone.matrixAutoUpdate = false;
  41813. this.add( this.cone );
  41814. this.setDirection( dir );
  41815. this.setLength( length, headLength, headWidth );
  41816. }
  41817. /**
  41818. * Sets the direction of the helper.
  41819. *
  41820. * @param {Vector3} dir - The normalized direction vector.
  41821. */
  41822. setDirection( dir ) {
  41823. // dir is assumed to be normalized
  41824. if ( dir.y > 0.99999 ) {
  41825. this.quaternion.set( 0, 0, 0, 1 );
  41826. } else if ( dir.y < -0.99999 ) {
  41827. this.quaternion.set( 1, 0, 0, 0 );
  41828. } else {
  41829. _axis.set( dir.z, 0, - dir.x ).normalize();
  41830. const radians = Math.acos( dir.y );
  41831. this.quaternion.setFromAxisAngle( _axis, radians );
  41832. }
  41833. }
  41834. /**
  41835. * Sets the length of the helper.
  41836. *
  41837. * @param {number} length - Length of the arrow in world units.
  41838. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41839. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41840. */
  41841. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  41842. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  41843. this.line.updateMatrix();
  41844. this.cone.scale.set( headWidth, headLength, headWidth );
  41845. this.cone.position.y = length;
  41846. this.cone.updateMatrix();
  41847. }
  41848. /**
  41849. * Sets the color of the helper.
  41850. *
  41851. * @param {number|Color|string} color - The color to set.
  41852. */
  41853. setColor( color ) {
  41854. this.line.material.color.set( color );
  41855. this.cone.material.color.set( color );
  41856. }
  41857. copy( source ) {
  41858. super.copy( source, false );
  41859. this.line.copy( source.line );
  41860. this.cone.copy( source.cone );
  41861. return this;
  41862. }
  41863. /**
  41864. * Frees the GPU-related resources allocated by this instance. Call this
  41865. * method whenever this instance is no longer used in your app.
  41866. */
  41867. dispose() {
  41868. this.line.geometry.dispose();
  41869. this.line.material.dispose();
  41870. this.cone.geometry.dispose();
  41871. this.cone.material.dispose();
  41872. }
  41873. }
  41874. /**
  41875. * An axis object to visualize the 3 axes in a simple way.
  41876. * The X axis is red. The Y axis is green. The Z axis is blue.
  41877. *
  41878. * ```js
  41879. * const axesHelper = new THREE.AxesHelper( 5 );
  41880. * scene.add( axesHelper );
  41881. * ```
  41882. *
  41883. * @augments LineSegments
  41884. */
  41885. class AxesHelper extends LineSegments {
  41886. /**
  41887. * Constructs a new axes helper.
  41888. *
  41889. * @param {number} [size=1] - Size of the lines representing the axes.
  41890. */
  41891. constructor( size = 1 ) {
  41892. const vertices = [
  41893. 0, 0, 0, size, 0, 0,
  41894. 0, 0, 0, 0, size, 0,
  41895. 0, 0, 0, 0, 0, size
  41896. ];
  41897. const colors = [
  41898. 1, 0, 0, 1, 0.6, 0,
  41899. 0, 1, 0, 0.6, 1, 0,
  41900. 0, 0, 1, 0, 0.6, 1
  41901. ];
  41902. const geometry = new BufferGeometry();
  41903. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41904. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41905. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41906. super( geometry, material );
  41907. this.type = 'AxesHelper';
  41908. }
  41909. /**
  41910. * Defines the colors of the axes helper.
  41911. *
  41912. * @param {number|Color|string} xAxisColor - The color for the x axis.
  41913. * @param {number|Color|string} yAxisColor - The color for the y axis.
  41914. * @param {number|Color|string} zAxisColor - The color for the z axis.
  41915. * @return {AxesHelper} A reference to this axes helper.
  41916. */
  41917. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  41918. const color = new Color();
  41919. const array = this.geometry.attributes.color.array;
  41920. color.set( xAxisColor );
  41921. color.toArray( array, 0 );
  41922. color.toArray( array, 3 );
  41923. color.set( yAxisColor );
  41924. color.toArray( array, 6 );
  41925. color.toArray( array, 9 );
  41926. color.set( zAxisColor );
  41927. color.toArray( array, 12 );
  41928. color.toArray( array, 15 );
  41929. this.geometry.attributes.color.needsUpdate = true;
  41930. return this;
  41931. }
  41932. /**
  41933. * Frees the GPU-related resources allocated by this instance. Call this
  41934. * method whenever this instance is no longer used in your app.
  41935. */
  41936. dispose() {
  41937. this.geometry.dispose();
  41938. this.material.dispose();
  41939. }
  41940. }
  41941. /**
  41942. * This class is used to convert a series of paths to an array of
  41943. * shapes. It is specifically used in context of fonts and SVG.
  41944. */
  41945. class ShapePath {
  41946. /**
  41947. * Constructs a new shape path.
  41948. */
  41949. constructor() {
  41950. this.type = 'ShapePath';
  41951. /**
  41952. * The color of the shape.
  41953. *
  41954. * @type {Color}
  41955. */
  41956. this.color = new Color();
  41957. /**
  41958. * The paths that have been generated for this shape.
  41959. *
  41960. * @type {Array<Path>}
  41961. * @default null
  41962. */
  41963. this.subPaths = [];
  41964. /**
  41965. * The current path that is being generated.
  41966. *
  41967. * @type {?Path}
  41968. * @default null
  41969. */
  41970. this.currentPath = null;
  41971. }
  41972. /**
  41973. * Creates a new path and moves it current point to the given one.
  41974. *
  41975. * @param {number} x - The x coordinate.
  41976. * @param {number} y - The y coordinate.
  41977. * @return {ShapePath} A reference to this shape path.
  41978. */
  41979. moveTo( x, y ) {
  41980. this.currentPath = new Path();
  41981. this.subPaths.push( this.currentPath );
  41982. this.currentPath.moveTo( x, y );
  41983. return this;
  41984. }
  41985. /**
  41986. * Adds an instance of {@link LineCurve} to the path by connecting
  41987. * the current point with the given one.
  41988. *
  41989. * @param {number} x - The x coordinate of the end point.
  41990. * @param {number} y - The y coordinate of the end point.
  41991. * @return {ShapePath} A reference to this shape path.
  41992. */
  41993. lineTo( x, y ) {
  41994. this.currentPath.lineTo( x, y );
  41995. return this;
  41996. }
  41997. /**
  41998. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  41999. * the current point with the given one.
  42000. *
  42001. * @param {number} aCPx - The x coordinate of the control point.
  42002. * @param {number} aCPy - The y coordinate of the control point.
  42003. * @param {number} aX - The x coordinate of the end point.
  42004. * @param {number} aY - The y coordinate of the end point.
  42005. * @return {ShapePath} A reference to this shape path.
  42006. */
  42007. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42008. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42009. return this;
  42010. }
  42011. /**
  42012. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42013. * the current point with the given one.
  42014. *
  42015. * @param {number} aCP1x - The x coordinate of the first control point.
  42016. * @param {number} aCP1y - The y coordinate of the first control point.
  42017. * @param {number} aCP2x - The x coordinate of the second control point.
  42018. * @param {number} aCP2y - The y coordinate of the second control point.
  42019. * @param {number} aX - The x coordinate of the end point.
  42020. * @param {number} aY - The y coordinate of the end point.
  42021. * @return {ShapePath} A reference to this shape path.
  42022. */
  42023. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42024. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42025. return this;
  42026. }
  42027. /**
  42028. * Adds an instance of {@link SplineCurve} to the path by connecting
  42029. * the current point with the given list of points.
  42030. *
  42031. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42032. * @return {ShapePath} A reference to this shape path.
  42033. */
  42034. splineThru( pts ) {
  42035. this.currentPath.splineThru( pts );
  42036. return this;
  42037. }
  42038. /**
  42039. * Converts the paths into an array of shapes.
  42040. *
  42041. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42042. * If this flag is set to `true`, then those are flipped.
  42043. * @return {Array<Shape>} An array of shapes.
  42044. */
  42045. toShapes( isCCW ) {
  42046. function toShapesNoHoles( inSubpaths ) {
  42047. const shapes = [];
  42048. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42049. const tmpPath = inSubpaths[ i ];
  42050. const tmpShape = new Shape();
  42051. tmpShape.curves = tmpPath.curves;
  42052. shapes.push( tmpShape );
  42053. }
  42054. return shapes;
  42055. }
  42056. function isPointInsidePolygon( inPt, inPolygon ) {
  42057. const polyLen = inPolygon.length;
  42058. // inPt on polygon contour => immediate success or
  42059. // toggling of inside/outside at every single! intersection point of an edge
  42060. // with the horizontal line through inPt, left of inPt
  42061. // not counting lowerY endpoints of edges and whole edges on that line
  42062. let inside = false;
  42063. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42064. let edgeLowPt = inPolygon[ p ];
  42065. let edgeHighPt = inPolygon[ q ];
  42066. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42067. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42068. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42069. // not parallel
  42070. if ( edgeDy < 0 ) {
  42071. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42072. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42073. }
  42074. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42075. if ( inPt.y === edgeLowPt.y ) {
  42076. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42077. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42078. } else {
  42079. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42080. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42081. if ( perpEdge < 0 ) continue;
  42082. inside = ! inside; // true intersection left of inPt
  42083. }
  42084. } else {
  42085. // parallel or collinear
  42086. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42087. // edge lies on the same horizontal line as inPt
  42088. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42089. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42090. // continue;
  42091. }
  42092. }
  42093. return inside;
  42094. }
  42095. const isClockWise = ShapeUtils.isClockWise;
  42096. const subPaths = this.subPaths;
  42097. if ( subPaths.length === 0 ) return [];
  42098. let solid, tmpPath, tmpShape;
  42099. const shapes = [];
  42100. if ( subPaths.length === 1 ) {
  42101. tmpPath = subPaths[ 0 ];
  42102. tmpShape = new Shape();
  42103. tmpShape.curves = tmpPath.curves;
  42104. shapes.push( tmpShape );
  42105. return shapes;
  42106. }
  42107. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42108. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42109. // console.log("Holes first", holesFirst);
  42110. const betterShapeHoles = [];
  42111. const newShapes = [];
  42112. let newShapeHoles = [];
  42113. let mainIdx = 0;
  42114. let tmpPoints;
  42115. newShapes[ mainIdx ] = undefined;
  42116. newShapeHoles[ mainIdx ] = [];
  42117. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42118. tmpPath = subPaths[ i ];
  42119. tmpPoints = tmpPath.getPoints();
  42120. solid = isClockWise( tmpPoints );
  42121. solid = isCCW ? ! solid : solid;
  42122. if ( solid ) {
  42123. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42124. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42125. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42126. if ( holesFirst ) mainIdx ++;
  42127. newShapeHoles[ mainIdx ] = [];
  42128. //console.log('cw', i);
  42129. } else {
  42130. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42131. //console.log('ccw', i);
  42132. }
  42133. }
  42134. // only Holes? -> probably all Shapes with wrong orientation
  42135. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42136. if ( newShapes.length > 1 ) {
  42137. let ambiguous = false;
  42138. let toChange = 0;
  42139. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42140. betterShapeHoles[ sIdx ] = [];
  42141. }
  42142. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42143. const sho = newShapeHoles[ sIdx ];
  42144. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42145. const ho = sho[ hIdx ];
  42146. let hole_unassigned = true;
  42147. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42148. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42149. if ( sIdx !== s2Idx ) toChange ++;
  42150. if ( hole_unassigned ) {
  42151. hole_unassigned = false;
  42152. betterShapeHoles[ s2Idx ].push( ho );
  42153. } else {
  42154. ambiguous = true;
  42155. }
  42156. }
  42157. }
  42158. if ( hole_unassigned ) {
  42159. betterShapeHoles[ sIdx ].push( ho );
  42160. }
  42161. }
  42162. }
  42163. if ( toChange > 0 && ambiguous === false ) {
  42164. newShapeHoles = betterShapeHoles;
  42165. }
  42166. }
  42167. let tmpHoles;
  42168. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42169. tmpShape = newShapes[ i ].s;
  42170. shapes.push( tmpShape );
  42171. tmpHoles = newShapeHoles[ i ];
  42172. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42173. tmpShape.holes.push( tmpHoles[ j ].h );
  42174. }
  42175. }
  42176. //console.log("shape", shapes);
  42177. return shapes;
  42178. }
  42179. }
  42180. /**
  42181. * Abstract base class for controls.
  42182. *
  42183. * @abstract
  42184. * @augments EventDispatcher
  42185. */
  42186. class Controls extends EventDispatcher {
  42187. /**
  42188. * Constructs a new controls instance.
  42189. *
  42190. * @param {Object3D} object - The object that is managed by the controls.
  42191. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  42192. */
  42193. constructor( object, domElement = null ) {
  42194. super();
  42195. /**
  42196. * The object that is managed by the controls.
  42197. *
  42198. * @type {Object3D}
  42199. */
  42200. this.object = object;
  42201. /**
  42202. * The HTML element used for event listeners.
  42203. *
  42204. * @type {?HTMLDOMElement}
  42205. * @default null
  42206. */
  42207. this.domElement = domElement;
  42208. /**
  42209. * Whether the controls responds to user input or not.
  42210. *
  42211. * @type {boolean}
  42212. * @default true
  42213. */
  42214. this.enabled = true;
  42215. /**
  42216. * The internal state of the controls.
  42217. *
  42218. * @type {number}
  42219. * @default -1
  42220. */
  42221. this.state = -1;
  42222. /**
  42223. * This object defines the keyboard input of the controls.
  42224. *
  42225. * @type {Object}
  42226. */
  42227. this.keys = {};
  42228. /**
  42229. * This object defines what type of actions are assigned to the available mouse buttons.
  42230. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42231. *
  42232. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42233. */
  42234. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42235. /**
  42236. * This object defines what type of actions are assigned to what kind of touch interaction.
  42237. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42238. *
  42239. * @type {{ONE: ?number, TWO: ?number}}
  42240. */
  42241. this.touches = { ONE: null, TWO: null };
  42242. }
  42243. /**
  42244. * Connects the controls to the DOM. This method has so called "side effects" since
  42245. * it adds the module's event listeners to the DOM.
  42246. *
  42247. * @param {HTMLDOMElement} element - The DOM element to connect to.
  42248. */
  42249. connect( element ) {
  42250. if ( element === undefined ) {
  42251. console.warn( 'THREE.Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42252. return;
  42253. }
  42254. if ( this.domElement !== null ) this.disconnect();
  42255. this.domElement = element;
  42256. }
  42257. /**
  42258. * Disconnects the controls from the DOM.
  42259. */
  42260. disconnect() {}
  42261. /**
  42262. * Call this method if you no longer want use to the controls. It frees all internal
  42263. * resources and removes all event listeners.
  42264. */
  42265. dispose() {}
  42266. /**
  42267. * Controls should implement this method if they have to update their internal state
  42268. * per simulation step.
  42269. *
  42270. * @param {number} [delta] - The time delta in seconds.
  42271. */
  42272. update( /* delta */ ) {}
  42273. }
  42274. /**
  42275. * Scales the texture as large as possible within its surface without cropping
  42276. * or stretching the texture. The method preserves the original aspect ratio of
  42277. * the texture. Akin to CSS `object-fit: contain`
  42278. *
  42279. * @param {Texture} texture - The texture.
  42280. * @param {number} aspect - The texture's aspect ratio.
  42281. * @return {Texture} The updated texture.
  42282. */
  42283. function contain( texture, aspect ) {
  42284. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42285. if ( imageAspect > aspect ) {
  42286. texture.repeat.x = 1;
  42287. texture.repeat.y = imageAspect / aspect;
  42288. texture.offset.x = 0;
  42289. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42290. } else {
  42291. texture.repeat.x = aspect / imageAspect;
  42292. texture.repeat.y = 1;
  42293. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42294. texture.offset.y = 0;
  42295. }
  42296. return texture;
  42297. }
  42298. /**
  42299. * Scales the texture to the smallest possible size to fill the surface, leaving
  42300. * no empty space. The method preserves the original aspect ratio of the texture.
  42301. * Akin to CSS `object-fit: cover`.
  42302. *
  42303. * @param {Texture} texture - The texture.
  42304. * @param {number} aspect - The texture's aspect ratio.
  42305. * @return {Texture} The updated texture.
  42306. */
  42307. function cover( texture, aspect ) {
  42308. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42309. if ( imageAspect > aspect ) {
  42310. texture.repeat.x = aspect / imageAspect;
  42311. texture.repeat.y = 1;
  42312. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42313. texture.offset.y = 0;
  42314. } else {
  42315. texture.repeat.x = 1;
  42316. texture.repeat.y = imageAspect / aspect;
  42317. texture.offset.x = 0;
  42318. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42319. }
  42320. return texture;
  42321. }
  42322. /**
  42323. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42324. *
  42325. * @param {Texture} texture - The texture.
  42326. * @return {Texture} The updated texture.
  42327. */
  42328. function fill( texture ) {
  42329. texture.repeat.x = 1;
  42330. texture.repeat.y = 1;
  42331. texture.offset.x = 0;
  42332. texture.offset.y = 0;
  42333. return texture;
  42334. }
  42335. /**
  42336. * Determines how many bytes must be used to represent the texture.
  42337. *
  42338. * @param {number} width - The width of the texture.
  42339. * @param {number} height - The height of the texture.
  42340. * @param {number} format - The texture's format.
  42341. * @param {number} type - The texture's type.
  42342. * @return {number} The byte length.
  42343. */
  42344. function getByteLength( width, height, format, type ) {
  42345. const typeByteLength = getTextureTypeByteLength( type );
  42346. switch ( format ) {
  42347. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42348. case AlphaFormat:
  42349. return width * height;
  42350. case RedFormat:
  42351. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42352. case RedIntegerFormat:
  42353. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42354. case RGFormat:
  42355. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42356. case RGIntegerFormat:
  42357. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42358. case RGBFormat:
  42359. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42360. case RGBAFormat:
  42361. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42362. case RGBAIntegerFormat:
  42363. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42364. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42365. case RGB_S3TC_DXT1_Format:
  42366. case RGBA_S3TC_DXT1_Format:
  42367. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42368. case RGBA_S3TC_DXT3_Format:
  42369. case RGBA_S3TC_DXT5_Format:
  42370. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42371. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42372. case RGB_PVRTC_2BPPV1_Format:
  42373. case RGBA_PVRTC_2BPPV1_Format:
  42374. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42375. case RGB_PVRTC_4BPPV1_Format:
  42376. case RGBA_PVRTC_4BPPV1_Format:
  42377. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42378. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42379. case RGB_ETC1_Format:
  42380. case RGB_ETC2_Format:
  42381. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42382. case RGBA_ETC2_EAC_Format:
  42383. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42384. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42385. case RGBA_ASTC_4x4_Format:
  42386. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42387. case RGBA_ASTC_5x4_Format:
  42388. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42389. case RGBA_ASTC_5x5_Format:
  42390. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42391. case RGBA_ASTC_6x5_Format:
  42392. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42393. case RGBA_ASTC_6x6_Format:
  42394. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42395. case RGBA_ASTC_8x5_Format:
  42396. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42397. case RGBA_ASTC_8x6_Format:
  42398. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42399. case RGBA_ASTC_8x8_Format:
  42400. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42401. case RGBA_ASTC_10x5_Format:
  42402. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42403. case RGBA_ASTC_10x6_Format:
  42404. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42405. case RGBA_ASTC_10x8_Format:
  42406. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42407. case RGBA_ASTC_10x10_Format:
  42408. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42409. case RGBA_ASTC_12x10_Format:
  42410. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42411. case RGBA_ASTC_12x12_Format:
  42412. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42413. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42414. case RGBA_BPTC_Format:
  42415. case RGB_BPTC_SIGNED_Format:
  42416. case RGB_BPTC_UNSIGNED_Format:
  42417. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42418. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42419. case RED_RGTC1_Format:
  42420. case SIGNED_RED_RGTC1_Format:
  42421. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42422. case RED_GREEN_RGTC2_Format:
  42423. case SIGNED_RED_GREEN_RGTC2_Format:
  42424. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42425. }
  42426. throw new Error(
  42427. `Unable to determine texture byte length for ${format} format.`,
  42428. );
  42429. }
  42430. function getTextureTypeByteLength( type ) {
  42431. switch ( type ) {
  42432. case UnsignedByteType:
  42433. case ByteType:
  42434. return { byteLength: 1, components: 1 };
  42435. case UnsignedShortType:
  42436. case ShortType:
  42437. case HalfFloatType:
  42438. return { byteLength: 2, components: 1 };
  42439. case UnsignedShort4444Type:
  42440. case UnsignedShort5551Type:
  42441. return { byteLength: 2, components: 4 };
  42442. case UnsignedIntType:
  42443. case IntType:
  42444. case FloatType:
  42445. return { byteLength: 4, components: 1 };
  42446. case UnsignedInt5999Type:
  42447. case UnsignedInt101111Type:
  42448. return { byteLength: 4, components: 3 };
  42449. }
  42450. throw new Error( `Unknown texture type ${type}.` );
  42451. }
  42452. /**
  42453. * A class containing utility functions for textures.
  42454. *
  42455. * @hideconstructor
  42456. */
  42457. class TextureUtils {
  42458. /**
  42459. * Scales the texture as large as possible within its surface without cropping
  42460. * or stretching the texture. The method preserves the original aspect ratio of
  42461. * the texture. Akin to CSS `object-fit: contain`
  42462. *
  42463. * @param {Texture} texture - The texture.
  42464. * @param {number} aspect - The texture's aspect ratio.
  42465. * @return {Texture} The updated texture.
  42466. */
  42467. static contain( texture, aspect ) {
  42468. return contain( texture, aspect );
  42469. }
  42470. /**
  42471. * Scales the texture to the smallest possible size to fill the surface, leaving
  42472. * no empty space. The method preserves the original aspect ratio of the texture.
  42473. * Akin to CSS `object-fit: cover`.
  42474. *
  42475. * @param {Texture} texture - The texture.
  42476. * @param {number} aspect - The texture's aspect ratio.
  42477. * @return {Texture} The updated texture.
  42478. */
  42479. static cover( texture, aspect ) {
  42480. return cover( texture, aspect );
  42481. }
  42482. /**
  42483. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42484. *
  42485. * @param {Texture} texture - The texture.
  42486. * @return {Texture} The updated texture.
  42487. */
  42488. static fill( texture ) {
  42489. return fill( texture );
  42490. }
  42491. /**
  42492. * Determines how many bytes must be used to represent the texture.
  42493. *
  42494. * @param {number} width - The width of the texture.
  42495. * @param {number} height - The height of the texture.
  42496. * @param {number} format - The texture's format.
  42497. * @param {number} type - The texture's type.
  42498. * @return {number} The byte length.
  42499. */
  42500. static getByteLength( width, height, format, type ) {
  42501. return getByteLength( width, height, format, type );
  42502. }
  42503. }
  42504. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42505. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42506. revision: REVISION,
  42507. } } ) );
  42508. }
  42509. if ( typeof window !== 'undefined' ) {
  42510. if ( window.__THREE__ ) {
  42511. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42512. } else {
  42513. window.__THREE__ = REVISION;
  42514. }
  42515. }
  42516. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, FrustumArray, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, MaterialLoader, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RenderTarget3D, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, arrayNeedsUint32, cloneUniforms, createCanvasElement, createElementNS, getByteLength, getUnlitUniformColorSpace, mergeUniforms, probeAsync, warnOnce };
粤ICP备19079148号