three.core.js 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '183dev';
  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. * Represents material blending.
  145. *
  146. * @type {number}
  147. * @constant
  148. */
  149. const MaterialBlending = 6;
  150. /**
  151. * A `source + destination` blending equation.
  152. *
  153. * @type {number}
  154. * @constant
  155. */
  156. const AddEquation = 100;
  157. /**
  158. * A `source - destination` blending equation.
  159. *
  160. * @type {number}
  161. * @constant
  162. */
  163. const SubtractEquation = 101;
  164. /**
  165. * A `destination - source` blending equation.
  166. *
  167. * @type {number}
  168. * @constant
  169. */
  170. const ReverseSubtractEquation = 102;
  171. /**
  172. * A blend equation that uses the minimum of source and destination.
  173. *
  174. * @type {number}
  175. * @constant
  176. */
  177. const MinEquation = 103;
  178. /**
  179. * A blend equation that uses the maximum of source and destination.
  180. *
  181. * @type {number}
  182. * @constant
  183. */
  184. const MaxEquation = 104;
  185. /**
  186. * Multiplies all colors by `0`.
  187. *
  188. * @type {number}
  189. * @constant
  190. */
  191. const ZeroFactor = 200;
  192. /**
  193. * Multiplies all colors by `1`.
  194. *
  195. * @type {number}
  196. * @constant
  197. */
  198. const OneFactor = 201;
  199. /**
  200. * Multiplies all colors by the source colors.
  201. *
  202. * @type {number}
  203. * @constant
  204. */
  205. const SrcColorFactor = 202;
  206. /**
  207. * Multiplies all colors by `1` minus each source color.
  208. *
  209. * @type {number}
  210. * @constant
  211. */
  212. const OneMinusSrcColorFactor = 203;
  213. /**
  214. * Multiplies all colors by the source alpha value.
  215. *
  216. * @type {number}
  217. * @constant
  218. */
  219. const SrcAlphaFactor = 204;
  220. /**
  221. * Multiplies all colors by 1 minus the source alpha value.
  222. *
  223. * @type {number}
  224. * @constant
  225. */
  226. const OneMinusSrcAlphaFactor = 205;
  227. /**
  228. * Multiplies all colors by the destination alpha value.
  229. *
  230. * @type {number}
  231. * @constant
  232. */
  233. const DstAlphaFactor = 206;
  234. /**
  235. * Multiplies all colors by `1` minus the destination alpha value.
  236. *
  237. * @type {number}
  238. * @constant
  239. */
  240. const OneMinusDstAlphaFactor = 207;
  241. /**
  242. * Multiplies all colors by the destination color.
  243. *
  244. * @type {number}
  245. * @constant
  246. */
  247. const DstColorFactor = 208;
  248. /**
  249. * Multiplies all colors by `1` minus each destination color.
  250. *
  251. * @type {number}
  252. * @constant
  253. */
  254. const OneMinusDstColorFactor = 209;
  255. /**
  256. * Multiplies the RGB colors by the smaller of either the source alpha
  257. * value or the value of `1` minus the destination alpha value. The alpha
  258. * value is multiplied by `1`.
  259. *
  260. * @type {number}
  261. * @constant
  262. */
  263. const SrcAlphaSaturateFactor = 210;
  264. /**
  265. * Multiplies all colors by a constant color.
  266. *
  267. * @type {number}
  268. * @constant
  269. */
  270. const ConstantColorFactor = 211;
  271. /**
  272. * Multiplies all colors by `1` minus a constant color.
  273. *
  274. * @type {number}
  275. * @constant
  276. */
  277. const OneMinusConstantColorFactor = 212;
  278. /**
  279. * Multiplies all colors by a constant alpha value.
  280. *
  281. * @type {number}
  282. * @constant
  283. */
  284. const ConstantAlphaFactor = 213;
  285. /**
  286. * Multiplies all colors by 1 minus a constant alpha value.
  287. *
  288. * @type {number}
  289. * @constant
  290. */
  291. const OneMinusConstantAlphaFactor = 214;
  292. /**
  293. * Never pass.
  294. *
  295. * @type {number}
  296. * @constant
  297. */
  298. const NeverDepth = 0;
  299. /**
  300. * Always pass.
  301. *
  302. * @type {number}
  303. * @constant
  304. */
  305. const AlwaysDepth = 1;
  306. /**
  307. * Pass if the incoming value is less than the depth buffer value.
  308. *
  309. * @type {number}
  310. * @constant
  311. */
  312. const LessDepth = 2;
  313. /**
  314. * Pass if the incoming value is less than or equal to the depth buffer value.
  315. *
  316. * @type {number}
  317. * @constant
  318. */
  319. const LessEqualDepth = 3;
  320. /**
  321. * Pass if the incoming value equals the depth buffer value.
  322. *
  323. * @type {number}
  324. * @constant
  325. */
  326. const EqualDepth = 4;
  327. /**
  328. * Pass if the incoming value is greater than or equal to the depth buffer value.
  329. *
  330. * @type {number}
  331. * @constant
  332. */
  333. const GreaterEqualDepth = 5;
  334. /**
  335. * Pass if the incoming value is greater than the depth buffer value.
  336. *
  337. * @type {number}
  338. * @constant
  339. */
  340. const GreaterDepth = 6;
  341. /**
  342. * Pass if the incoming value is not equal to the depth buffer value.
  343. *
  344. * @type {number}
  345. * @constant
  346. */
  347. const NotEqualDepth = 7;
  348. /**
  349. * Multiplies the environment map color with the surface color.
  350. *
  351. * @type {number}
  352. * @constant
  353. */
  354. const MultiplyOperation = 0;
  355. /**
  356. * Uses reflectivity to blend between the two colors.
  357. *
  358. * @type {number}
  359. * @constant
  360. */
  361. const MixOperation = 1;
  362. /**
  363. * Adds the two colors.
  364. *
  365. * @type {number}
  366. * @constant
  367. */
  368. const AddOperation = 2;
  369. /**
  370. * No tone mapping is applied.
  371. *
  372. * @type {number}
  373. * @constant
  374. */
  375. const NoToneMapping = 0;
  376. /**
  377. * Linear tone mapping.
  378. *
  379. * @type {number}
  380. * @constant
  381. */
  382. const LinearToneMapping = 1;
  383. /**
  384. * Reinhard tone mapping.
  385. *
  386. * @type {number}
  387. * @constant
  388. */
  389. const ReinhardToneMapping = 2;
  390. /**
  391. * Cineon tone mapping.
  392. *
  393. * @type {number}
  394. * @constant
  395. */
  396. const CineonToneMapping = 3;
  397. /**
  398. * ACES Filmic tone mapping.
  399. *
  400. * @type {number}
  401. * @constant
  402. */
  403. const ACESFilmicToneMapping = 4;
  404. /**
  405. * Custom tone mapping.
  406. *
  407. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  408. *
  409. * @type {number}
  410. * @constant
  411. */
  412. const CustomToneMapping = 5;
  413. /**
  414. * AgX tone mapping.
  415. *
  416. * @type {number}
  417. * @constant
  418. */
  419. const AgXToneMapping = 6;
  420. /**
  421. * Neutral tone mapping.
  422. *
  423. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  424. *
  425. * @type {number}
  426. * @constant
  427. */
  428. const NeutralToneMapping = 7;
  429. /**
  430. * The skinned mesh shares the same world space as the skeleton.
  431. *
  432. * @type {string}
  433. * @constant
  434. */
  435. const AttachedBindMode = 'attached';
  436. /**
  437. * The skinned mesh does not share the same world space as the skeleton.
  438. * This is useful when a skeleton is shared across multiple skinned meshes.
  439. *
  440. * @type {string}
  441. * @constant
  442. */
  443. const DetachedBindMode = 'detached';
  444. /**
  445. * Maps textures using the geometry's UV coordinates.
  446. *
  447. * @type {number}
  448. * @constant
  449. */
  450. const UVMapping = 300;
  451. /**
  452. * Reflection mapping for cube textures.
  453. *
  454. * @type {number}
  455. * @constant
  456. */
  457. const CubeReflectionMapping = 301;
  458. /**
  459. * Refraction mapping for cube textures.
  460. *
  461. * @type {number}
  462. * @constant
  463. */
  464. const CubeRefractionMapping = 302;
  465. /**
  466. * Reflection mapping for equirectangular textures.
  467. *
  468. * @type {number}
  469. * @constant
  470. */
  471. const EquirectangularReflectionMapping = 303;
  472. /**
  473. * Refraction mapping for equirectangular textures.
  474. *
  475. * @type {number}
  476. * @constant
  477. */
  478. const EquirectangularRefractionMapping = 304;
  479. /**
  480. * Reflection mapping for PMREM textures.
  481. *
  482. * @type {number}
  483. * @constant
  484. */
  485. const CubeUVReflectionMapping = 306;
  486. /**
  487. * The texture will simply repeat to infinity.
  488. *
  489. * @type {number}
  490. * @constant
  491. */
  492. const RepeatWrapping = 1000;
  493. /**
  494. * The last pixel of the texture stretches to the edge of the mesh.
  495. *
  496. * @type {number}
  497. * @constant
  498. */
  499. const ClampToEdgeWrapping = 1001;
  500. /**
  501. * The texture will repeats to infinity, mirroring on each repeat.
  502. *
  503. * @type {number}
  504. * @constant
  505. */
  506. const MirroredRepeatWrapping = 1002;
  507. /**
  508. * Returns the value of the texture element that is nearest (in Manhattan distance)
  509. * to the specified texture coordinates.
  510. *
  511. * @type {number}
  512. * @constant
  513. */
  514. const NearestFilter = 1003;
  515. /**
  516. * Chooses the mipmap that most closely matches the size of the pixel being textured
  517. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  518. * to produce a texture value.
  519. *
  520. * @type {number}
  521. * @constant
  522. */
  523. const NearestMipmapNearestFilter = 1004;
  524. const NearestMipMapNearestFilter = 1004; // legacy
  525. /**
  526. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  527. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  528. * The final texture value is a weighted average of those two values.
  529. *
  530. * @type {number}
  531. * @constant
  532. */
  533. const NearestMipmapLinearFilter = 1005;
  534. const NearestMipMapLinearFilter = 1005; // legacy
  535. /**
  536. * Returns the weighted average of the four texture elements that are closest to the specified
  537. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  538. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  539. *
  540. * @type {number}
  541. * @constant
  542. */
  543. const LinearFilter = 1006;
  544. /**
  545. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  546. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  547. * center of the pixel) to produce a texture value.
  548. *
  549. * @type {number}
  550. * @constant
  551. */
  552. const LinearMipmapNearestFilter = 1007;
  553. const LinearMipMapNearestFilter = 1007; // legacy
  554. /**
  555. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  556. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  557. * is a weighted average of those two values.
  558. *
  559. * @type {number}
  560. * @constant
  561. */
  562. const LinearMipmapLinearFilter = 1008;
  563. const LinearMipMapLinearFilter = 1008; // legacy
  564. /**
  565. * An unsigned byte data type for textures.
  566. *
  567. * @type {number}
  568. * @constant
  569. */
  570. const UnsignedByteType = 1009;
  571. /**
  572. * A byte data type for textures.
  573. *
  574. * @type {number}
  575. * @constant
  576. */
  577. const ByteType = 1010;
  578. /**
  579. * A short data type for textures.
  580. *
  581. * @type {number}
  582. * @constant
  583. */
  584. const ShortType = 1011;
  585. /**
  586. * An unsigned short data type for textures.
  587. *
  588. * @type {number}
  589. * @constant
  590. */
  591. const UnsignedShortType = 1012;
  592. /**
  593. * An int data type for textures.
  594. *
  595. * @type {number}
  596. * @constant
  597. */
  598. const IntType = 1013;
  599. /**
  600. * An unsigned int data type for textures.
  601. *
  602. * @type {number}
  603. * @constant
  604. */
  605. const UnsignedIntType = 1014;
  606. /**
  607. * A float data type for textures.
  608. *
  609. * @type {number}
  610. * @constant
  611. */
  612. const FloatType = 1015;
  613. /**
  614. * A half float data type for textures.
  615. *
  616. * @type {number}
  617. * @constant
  618. */
  619. const HalfFloatType = 1016;
  620. /**
  621. * An unsigned short 4_4_4_4 (packed) data type for textures.
  622. *
  623. * @type {number}
  624. * @constant
  625. */
  626. const UnsignedShort4444Type = 1017;
  627. /**
  628. * An unsigned short 5_5_5_1 (packed) data type for textures.
  629. *
  630. * @type {number}
  631. * @constant
  632. */
  633. const UnsignedShort5551Type = 1018;
  634. /**
  635. * An unsigned int 24_8 data type for textures.
  636. *
  637. * @type {number}
  638. * @constant
  639. */
  640. const UnsignedInt248Type = 1020;
  641. /**
  642. * An unsigned int 5_9_9_9 (packed) data type for textures.
  643. *
  644. * @type {number}
  645. * @constant
  646. */
  647. const UnsignedInt5999Type = 35902;
  648. /**
  649. * An unsigned int 10_11_11 (packed) data type for textures.
  650. *
  651. * @type {number}
  652. * @constant
  653. */
  654. const UnsignedInt101111Type = 35899;
  655. /**
  656. * Discards the red, green and blue components and reads just the alpha component.
  657. *
  658. * @type {number}
  659. * @constant
  660. */
  661. const AlphaFormat = 1021;
  662. /**
  663. * Discards the alpha component and reads the red, green and blue component.
  664. *
  665. * @type {number}
  666. * @constant
  667. */
  668. const RGBFormat = 1022;
  669. /**
  670. * Reads the red, green, blue and alpha components.
  671. *
  672. * @type {number}
  673. * @constant
  674. */
  675. const RGBAFormat = 1023;
  676. /**
  677. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  678. *
  679. * @type {number}
  680. * @constant
  681. */
  682. const DepthFormat = 1026;
  683. /**
  684. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  685. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  686. *
  687. * @type {number}
  688. * @constant
  689. */
  690. const DepthStencilFormat = 1027;
  691. /**
  692. * Discards the green, blue and alpha components and reads just the red component.
  693. *
  694. * @type {number}
  695. * @constant
  696. */
  697. const RedFormat = 1028;
  698. /**
  699. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  700. *
  701. * @type {number}
  702. * @constant
  703. */
  704. const RedIntegerFormat = 1029;
  705. /**
  706. * Discards the alpha, and blue components and reads the red, and green components.
  707. *
  708. * @type {number}
  709. * @constant
  710. */
  711. const RGFormat = 1030;
  712. /**
  713. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  714. *
  715. * @type {number}
  716. * @constant
  717. */
  718. const RGIntegerFormat = 1031;
  719. /**
  720. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  721. *
  722. * @type {number}
  723. * @constant
  724. */
  725. const RGBIntegerFormat = 1032;
  726. /**
  727. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  728. *
  729. * @type {number}
  730. * @constant
  731. */
  732. const RGBAIntegerFormat = 1033;
  733. /**
  734. * A DXT1-compressed image in an RGB image format.
  735. *
  736. * @type {number}
  737. * @constant
  738. */
  739. const RGB_S3TC_DXT1_Format = 33776;
  740. /**
  741. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  742. *
  743. * @type {number}
  744. * @constant
  745. */
  746. const RGBA_S3TC_DXT1_Format = 33777;
  747. /**
  748. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  749. *
  750. * @type {number}
  751. * @constant
  752. */
  753. const RGBA_S3TC_DXT3_Format = 33778;
  754. /**
  755. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  756. * compression in how the alpha compression is done.
  757. *
  758. * @type {number}
  759. * @constant
  760. */
  761. const RGBA_S3TC_DXT5_Format = 33779;
  762. /**
  763. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  764. *
  765. * @type {number}
  766. * @constant
  767. */
  768. const RGB_PVRTC_4BPPV1_Format = 35840;
  769. /**
  770. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  771. *
  772. * @type {number}
  773. * @constant
  774. */
  775. const RGB_PVRTC_2BPPV1_Format = 35841;
  776. /**
  777. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  778. *
  779. * @type {number}
  780. * @constant
  781. */
  782. const RGBA_PVRTC_4BPPV1_Format = 35842;
  783. /**
  784. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  785. *
  786. * @type {number}
  787. * @constant
  788. */
  789. const RGBA_PVRTC_2BPPV1_Format = 35843;
  790. /**
  791. * ETC1 RGB format.
  792. *
  793. * @type {number}
  794. * @constant
  795. */
  796. const RGB_ETC1_Format = 36196;
  797. /**
  798. * ETC2 RGB format.
  799. *
  800. * @type {number}
  801. * @constant
  802. */
  803. const RGB_ETC2_Format = 37492;
  804. /**
  805. * ETC2 RGBA format.
  806. *
  807. * @type {number}
  808. * @constant
  809. */
  810. const RGBA_ETC2_EAC_Format = 37496;
  811. /**
  812. * EAC R11 UNORM format.
  813. *
  814. * @type {number}
  815. * @constant
  816. */
  817. const R11_EAC_Format = 37488; // 0x9270
  818. /**
  819. * EAC R11 SNORM format.
  820. *
  821. * @type {number}
  822. * @constant
  823. */
  824. const SIGNED_R11_EAC_Format = 37489; // 0x9271
  825. /**
  826. * EAC RG11 UNORM format.
  827. *
  828. * @type {number}
  829. * @constant
  830. */
  831. const RG11_EAC_Format = 37490; // 0x9272
  832. /**
  833. * EAC RG11 SNORM format.
  834. *
  835. * @type {number}
  836. * @constant
  837. */
  838. const SIGNED_RG11_EAC_Format = 37491; // 0x9273
  839. /**
  840. * ASTC RGBA 4x4 format.
  841. *
  842. * @type {number}
  843. * @constant
  844. */
  845. const RGBA_ASTC_4x4_Format = 37808;
  846. /**
  847. * ASTC RGBA 5x4 format.
  848. *
  849. * @type {number}
  850. * @constant
  851. */
  852. const RGBA_ASTC_5x4_Format = 37809;
  853. /**
  854. * ASTC RGBA 5x5 format.
  855. *
  856. * @type {number}
  857. * @constant
  858. */
  859. const RGBA_ASTC_5x5_Format = 37810;
  860. /**
  861. * ASTC RGBA 6x5 format.
  862. *
  863. * @type {number}
  864. * @constant
  865. */
  866. const RGBA_ASTC_6x5_Format = 37811;
  867. /**
  868. * ASTC RGBA 6x6 format.
  869. *
  870. * @type {number}
  871. * @constant
  872. */
  873. const RGBA_ASTC_6x6_Format = 37812;
  874. /**
  875. * ASTC RGBA 8x5 format.
  876. *
  877. * @type {number}
  878. * @constant
  879. */
  880. const RGBA_ASTC_8x5_Format = 37813;
  881. /**
  882. * ASTC RGBA 8x6 format.
  883. *
  884. * @type {number}
  885. * @constant
  886. */
  887. const RGBA_ASTC_8x6_Format = 37814;
  888. /**
  889. * ASTC RGBA 8x8 format.
  890. *
  891. * @type {number}
  892. * @constant
  893. */
  894. const RGBA_ASTC_8x8_Format = 37815;
  895. /**
  896. * ASTC RGBA 10x5 format.
  897. *
  898. * @type {number}
  899. * @constant
  900. */
  901. const RGBA_ASTC_10x5_Format = 37816;
  902. /**
  903. * ASTC RGBA 10x6 format.
  904. *
  905. * @type {number}
  906. * @constant
  907. */
  908. const RGBA_ASTC_10x6_Format = 37817;
  909. /**
  910. * ASTC RGBA 10x8 format.
  911. *
  912. * @type {number}
  913. * @constant
  914. */
  915. const RGBA_ASTC_10x8_Format = 37818;
  916. /**
  917. * ASTC RGBA 10x10 format.
  918. *
  919. * @type {number}
  920. * @constant
  921. */
  922. const RGBA_ASTC_10x10_Format = 37819;
  923. /**
  924. * ASTC RGBA 12x10 format.
  925. *
  926. * @type {number}
  927. * @constant
  928. */
  929. const RGBA_ASTC_12x10_Format = 37820;
  930. /**
  931. * ASTC RGBA 12x12 format.
  932. *
  933. * @type {number}
  934. * @constant
  935. */
  936. const RGBA_ASTC_12x12_Format = 37821;
  937. /**
  938. * BPTC RGBA format.
  939. *
  940. * @type {number}
  941. * @constant
  942. */
  943. const RGBA_BPTC_Format = 36492;
  944. /**
  945. * BPTC Signed RGB format.
  946. *
  947. * @type {number}
  948. * @constant
  949. */
  950. const RGB_BPTC_SIGNED_Format = 36494;
  951. /**
  952. * BPTC Unsigned RGB format.
  953. *
  954. * @type {number}
  955. * @constant
  956. */
  957. const RGB_BPTC_UNSIGNED_Format = 36495;
  958. /**
  959. * RGTC1 Red format.
  960. *
  961. * @type {number}
  962. * @constant
  963. */
  964. const RED_RGTC1_Format = 36283;
  965. /**
  966. * RGTC1 Signed Red format.
  967. *
  968. * @type {number}
  969. * @constant
  970. */
  971. const SIGNED_RED_RGTC1_Format = 36284;
  972. /**
  973. * RGTC2 Red Green format.
  974. *
  975. * @type {number}
  976. * @constant
  977. */
  978. const RED_GREEN_RGTC2_Format = 36285;
  979. /**
  980. * RGTC2 Signed Red Green format.
  981. *
  982. * @type {number}
  983. * @constant
  984. */
  985. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  986. /**
  987. * Animations are played once.
  988. *
  989. * @type {number}
  990. * @constant
  991. */
  992. const LoopOnce = 2200;
  993. /**
  994. * Animations are played with a chosen number of repetitions, each time jumping from
  995. * the end of the clip directly to its beginning.
  996. *
  997. * @type {number}
  998. * @constant
  999. */
  1000. const LoopRepeat = 2201;
  1001. /**
  1002. * Animations are played with a chosen number of repetitions, alternately playing forward
  1003. * and backward.
  1004. *
  1005. * @type {number}
  1006. * @constant
  1007. */
  1008. const LoopPingPong = 2202;
  1009. /**
  1010. * Discrete interpolation mode for keyframe tracks.
  1011. *
  1012. * @type {number}
  1013. * @constant
  1014. */
  1015. const InterpolateDiscrete = 2300;
  1016. /**
  1017. * Linear interpolation mode for keyframe tracks.
  1018. *
  1019. * @type {number}
  1020. * @constant
  1021. */
  1022. const InterpolateLinear = 2301;
  1023. /**
  1024. * Smooth interpolation mode for keyframe tracks.
  1025. *
  1026. * @type {number}
  1027. * @constant
  1028. */
  1029. const InterpolateSmooth = 2302;
  1030. /**
  1031. * Bezier interpolation mode for keyframe tracks.
  1032. *
  1033. * Uses cubic Bezier curves with explicit 2D control points.
  1034. * Requires tangent data to be set on the track.
  1035. *
  1036. * @type {number}
  1037. * @constant
  1038. */
  1039. const InterpolateBezier = 2303;
  1040. /**
  1041. * Zero curvature ending for animations.
  1042. *
  1043. * @type {number}
  1044. * @constant
  1045. */
  1046. const ZeroCurvatureEnding = 2400;
  1047. /**
  1048. * Zero slope ending for animations.
  1049. *
  1050. * @type {number}
  1051. * @constant
  1052. */
  1053. const ZeroSlopeEnding = 2401;
  1054. /**
  1055. * Wrap around ending for animations.
  1056. *
  1057. * @type {number}
  1058. * @constant
  1059. */
  1060. const WrapAroundEnding = 2402;
  1061. /**
  1062. * Default animation blend mode.
  1063. *
  1064. * @type {number}
  1065. * @constant
  1066. */
  1067. const NormalAnimationBlendMode = 2500;
  1068. /**
  1069. * Additive animation blend mode. Can be used to layer motions on top of
  1070. * each other to build complex performances from smaller re-usable assets.
  1071. *
  1072. * @type {number}
  1073. * @constant
  1074. */
  1075. const AdditiveAnimationBlendMode = 2501;
  1076. /**
  1077. * For every three vertices draw a single triangle.
  1078. *
  1079. * @type {number}
  1080. * @constant
  1081. */
  1082. const TrianglesDrawMode = 0;
  1083. /**
  1084. * For each vertex draw a triangle from the last three vertices.
  1085. *
  1086. * @type {number}
  1087. * @constant
  1088. */
  1089. const TriangleStripDrawMode = 1;
  1090. /**
  1091. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1092. *
  1093. * @type {number}
  1094. * @constant
  1095. */
  1096. const TriangleFanDrawMode = 2;
  1097. /**
  1098. * The depth value is inverted (1.0 - z) for visualization purposes.
  1099. *
  1100. * @type {number}
  1101. * @constant
  1102. */
  1103. const BasicDepthPacking = 3200;
  1104. /**
  1105. * The depth value is packed into 32 bit RGBA.
  1106. *
  1107. * @type {number}
  1108. * @constant
  1109. */
  1110. const RGBADepthPacking = 3201;
  1111. /**
  1112. * The depth value is packed into 24 bit RGB.
  1113. *
  1114. * @type {number}
  1115. * @constant
  1116. */
  1117. const RGBDepthPacking = 3202;
  1118. /**
  1119. * The depth value is packed into 16 bit RG.
  1120. *
  1121. * @type {number}
  1122. * @constant
  1123. */
  1124. const RGDepthPacking = 3203;
  1125. /**
  1126. * Normal information is relative to the underlying surface.
  1127. *
  1128. * @type {number}
  1129. * @constant
  1130. */
  1131. const TangentSpaceNormalMap = 0;
  1132. /**
  1133. * Normal information is relative to the object orientation.
  1134. *
  1135. * @type {number}
  1136. * @constant
  1137. */
  1138. const ObjectSpaceNormalMap = 1;
  1139. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1140. /**
  1141. * No color space.
  1142. *
  1143. * @type {string}
  1144. * @constant
  1145. */
  1146. const NoColorSpace = '';
  1147. /**
  1148. * sRGB color space.
  1149. *
  1150. * @type {string}
  1151. * @constant
  1152. */
  1153. const SRGBColorSpace = 'srgb';
  1154. /**
  1155. * sRGB-linear color space.
  1156. *
  1157. * @type {string}
  1158. * @constant
  1159. */
  1160. const LinearSRGBColorSpace = 'srgb-linear';
  1161. /**
  1162. * Linear transfer function.
  1163. *
  1164. * @type {string}
  1165. * @constant
  1166. */
  1167. const LinearTransfer = 'linear';
  1168. /**
  1169. * sRGB transfer function.
  1170. *
  1171. * @type {string}
  1172. * @constant
  1173. */
  1174. const SRGBTransfer = 'srgb';
  1175. /**
  1176. * No normal map packing.
  1177. *
  1178. * @type {string}
  1179. * @constant
  1180. */
  1181. const NoNormalPacking = '';
  1182. /**
  1183. * Normal RG packing.
  1184. *
  1185. * @type {string}
  1186. * @constant
  1187. */
  1188. const NormalRGPacking = 'rg';
  1189. /**
  1190. * Normal GA packing.
  1191. *
  1192. * @type {string}
  1193. * @constant
  1194. */
  1195. const NormalGAPacking = 'ga';
  1196. /**
  1197. * Sets the stencil buffer value to `0`.
  1198. *
  1199. * @type {number}
  1200. * @constant
  1201. */
  1202. const ZeroStencilOp = 0;
  1203. /**
  1204. * Keeps the current value.
  1205. *
  1206. * @type {number}
  1207. * @constant
  1208. */
  1209. const KeepStencilOp = 7680;
  1210. /**
  1211. * Sets the stencil buffer value to the specified reference value.
  1212. *
  1213. * @type {number}
  1214. * @constant
  1215. */
  1216. const ReplaceStencilOp = 7681;
  1217. /**
  1218. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1219. *
  1220. * @type {number}
  1221. * @constant
  1222. */
  1223. const IncrementStencilOp = 7682;
  1224. /**
  1225. * Decrements the current stencil buffer value. Clamps to `0`.
  1226. *
  1227. * @type {number}
  1228. * @constant
  1229. */
  1230. const DecrementStencilOp = 7683;
  1231. /**
  1232. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1233. * the maximum representable unsigned value.
  1234. *
  1235. * @type {number}
  1236. * @constant
  1237. */
  1238. const IncrementWrapStencilOp = 34055;
  1239. /**
  1240. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1241. * unsigned value when decrementing a stencil buffer value of `0`.
  1242. *
  1243. * @type {number}
  1244. * @constant
  1245. */
  1246. const DecrementWrapStencilOp = 34056;
  1247. /**
  1248. * Inverts the current stencil buffer value bitwise.
  1249. *
  1250. * @type {number}
  1251. * @constant
  1252. */
  1253. const InvertStencilOp = 5386;
  1254. /**
  1255. * Will never return true.
  1256. *
  1257. * @type {number}
  1258. * @constant
  1259. */
  1260. const NeverStencilFunc = 512;
  1261. /**
  1262. * Will return true if the stencil reference value is less than the current stencil value.
  1263. *
  1264. * @type {number}
  1265. * @constant
  1266. */
  1267. const LessStencilFunc = 513;
  1268. /**
  1269. * Will return true if the stencil reference value is equal to the current stencil value.
  1270. *
  1271. * @type {number}
  1272. * @constant
  1273. */
  1274. const EqualStencilFunc = 514;
  1275. /**
  1276. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1277. *
  1278. * @type {number}
  1279. * @constant
  1280. */
  1281. const LessEqualStencilFunc = 515;
  1282. /**
  1283. * Will return true if the stencil reference value is greater than the current stencil value.
  1284. *
  1285. * @type {number}
  1286. * @constant
  1287. */
  1288. const GreaterStencilFunc = 516;
  1289. /**
  1290. * Will return true if the stencil reference value is not equal to the current stencil value.
  1291. *
  1292. * @type {number}
  1293. * @constant
  1294. */
  1295. const NotEqualStencilFunc = 517;
  1296. /**
  1297. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1298. *
  1299. * @type {number}
  1300. * @constant
  1301. */
  1302. const GreaterEqualStencilFunc = 518;
  1303. /**
  1304. * Will always return true.
  1305. *
  1306. * @type {number}
  1307. * @constant
  1308. */
  1309. const AlwaysStencilFunc = 519;
  1310. /**
  1311. * Never pass.
  1312. *
  1313. * @type {number}
  1314. * @constant
  1315. */
  1316. const NeverCompare = 512;
  1317. /**
  1318. * Pass if the incoming value is less than the texture value.
  1319. *
  1320. * @type {number}
  1321. * @constant
  1322. */
  1323. const LessCompare = 513;
  1324. /**
  1325. * Pass if the incoming value equals the texture value.
  1326. *
  1327. * @type {number}
  1328. * @constant
  1329. */
  1330. const EqualCompare = 514;
  1331. /**
  1332. * Pass if the incoming value is less than or equal to the texture value.
  1333. *
  1334. * @type {number}
  1335. * @constant
  1336. */
  1337. const LessEqualCompare = 515;
  1338. /**
  1339. * Pass if the incoming value is greater than the texture value.
  1340. *
  1341. * @type {number}
  1342. * @constant
  1343. */
  1344. const GreaterCompare = 516;
  1345. /**
  1346. * Pass if the incoming value is not equal to the texture value.
  1347. *
  1348. * @type {number}
  1349. * @constant
  1350. */
  1351. const NotEqualCompare = 517;
  1352. /**
  1353. * Pass if the incoming value is greater than or equal to the texture value.
  1354. *
  1355. * @type {number}
  1356. * @constant
  1357. */
  1358. const GreaterEqualCompare = 518;
  1359. /**
  1360. * Always pass.
  1361. *
  1362. * @type {number}
  1363. * @constant
  1364. */
  1365. const AlwaysCompare = 519;
  1366. /**
  1367. * The contents are intended to be specified once by the application, and used many
  1368. * times as the source for drawing and image specification commands.
  1369. *
  1370. * @type {number}
  1371. * @constant
  1372. */
  1373. const StaticDrawUsage = 35044;
  1374. /**
  1375. * The contents are intended to be respecified repeatedly by the application, and
  1376. * used many times as the source for drawing and image specification commands.
  1377. *
  1378. * @type {number}
  1379. * @constant
  1380. */
  1381. const DynamicDrawUsage = 35048;
  1382. /**
  1383. * The contents are intended to be specified once by the application, and used at most
  1384. * a few times as the source for drawing and image specification commands.
  1385. *
  1386. * @type {number}
  1387. * @constant
  1388. */
  1389. const StreamDrawUsage = 35040;
  1390. /**
  1391. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1392. * many times by the application.
  1393. *
  1394. * @type {number}
  1395. * @constant
  1396. */
  1397. const StaticReadUsage = 35045;
  1398. /**
  1399. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1400. * many times by the application.
  1401. *
  1402. * @type {number}
  1403. * @constant
  1404. */
  1405. const DynamicReadUsage = 35049;
  1406. /**
  1407. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1408. * a few times by the application
  1409. *
  1410. * @type {number}
  1411. * @constant
  1412. */
  1413. const StreamReadUsage = 35041;
  1414. /**
  1415. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1416. * the source for WebGL drawing and image specification commands.
  1417. *
  1418. * @type {number}
  1419. * @constant
  1420. */
  1421. const StaticCopyUsage = 35046;
  1422. /**
  1423. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1424. * as the source for WebGL drawing and image specification commands.
  1425. *
  1426. * @type {number}
  1427. * @constant
  1428. */
  1429. const DynamicCopyUsage = 35050;
  1430. /**
  1431. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1432. * as the source for WebGL drawing and image specification commands.
  1433. *
  1434. * @type {number}
  1435. * @constant
  1436. */
  1437. const StreamCopyUsage = 35042;
  1438. /**
  1439. * GLSL 1 shader code.
  1440. *
  1441. * @type {string}
  1442. * @constant
  1443. */
  1444. const GLSL1 = '100';
  1445. /**
  1446. * GLSL 3 shader code.
  1447. *
  1448. * @type {string}
  1449. * @constant
  1450. */
  1451. const GLSL3 = '300 es';
  1452. /**
  1453. * WebGL coordinate system.
  1454. *
  1455. * @type {number}
  1456. * @constant
  1457. */
  1458. const WebGLCoordinateSystem = 2000;
  1459. /**
  1460. * WebGPU coordinate system.
  1461. *
  1462. * @type {number}
  1463. * @constant
  1464. */
  1465. const WebGPUCoordinateSystem = 2001;
  1466. /**
  1467. * Represents the different timestamp query types.
  1468. *
  1469. * @type {ConstantsTimestampQuery}
  1470. * @constant
  1471. */
  1472. const TimestampQuery = {
  1473. COMPUTE: 'compute',
  1474. RENDER: 'render'
  1475. };
  1476. /**
  1477. * Represents mouse buttons and interaction types in context of controls.
  1478. *
  1479. * @type {ConstantsInterpolationSamplingType}
  1480. * @constant
  1481. */
  1482. const InterpolationSamplingType = {
  1483. PERSPECTIVE: 'perspective',
  1484. LINEAR: 'linear',
  1485. FLAT: 'flat'
  1486. };
  1487. /**
  1488. * Represents the different interpolation sampling modes.
  1489. *
  1490. * @type {ConstantsInterpolationSamplingMode}
  1491. * @constant
  1492. */
  1493. const InterpolationSamplingMode = {
  1494. NORMAL: 'normal',
  1495. CENTROID: 'centroid',
  1496. SAMPLE: 'sample',
  1497. FIRST: 'first',
  1498. EITHER: 'either'
  1499. };
  1500. /**
  1501. * Compatibility flags for features that may not be supported across all platforms.
  1502. *
  1503. * @type {Object}
  1504. * @constant
  1505. */
  1506. const Compatibility = {
  1507. TEXTURE_COMPARE: 'depthTextureCompare'
  1508. };
  1509. /**
  1510. * This type represents mouse buttons and interaction types in context of controls.
  1511. *
  1512. * @typedef {Object} ConstantsMouse
  1513. * @property {number} MIDDLE - The left mouse button.
  1514. * @property {number} LEFT - The middle mouse button.
  1515. * @property {number} RIGHT - The right mouse button.
  1516. * @property {number} ROTATE - A rotate interaction.
  1517. * @property {number} DOLLY - A dolly interaction.
  1518. * @property {number} PAN - A pan interaction.
  1519. **/
  1520. /**
  1521. * This type represents touch interaction types in context of controls.
  1522. *
  1523. * @typedef {Object} ConstantsTouch
  1524. * @property {number} ROTATE - A rotate interaction.
  1525. * @property {number} PAN - A pan interaction.
  1526. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1527. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1528. **/
  1529. /**
  1530. * This type represents the different timestamp query types.
  1531. *
  1532. * @typedef {Object} ConstantsTimestampQuery
  1533. * @property {string} COMPUTE - A `compute` timestamp query.
  1534. * @property {string} RENDER - A `render` timestamp query.
  1535. **/
  1536. /**
  1537. * Represents the different interpolation sampling types.
  1538. *
  1539. * @typedef {Object} ConstantsInterpolationSamplingType
  1540. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1541. * @property {string} LINEAR - Linear interpolation.
  1542. * @property {string} FLAT - Flat interpolation.
  1543. */
  1544. /**
  1545. * Represents the different interpolation sampling modes.
  1546. *
  1547. * @typedef {Object} ConstantsInterpolationSamplingMode
  1548. * @property {string} NORMAL - Normal sampling mode.
  1549. * @property {string} CENTROID - Centroid sampling mode.
  1550. * @property {string} SAMPLE - Sample-specific sampling mode.
  1551. * @property {string} FIRST - Flat interpolation using the first vertex.
  1552. * @property {string} EITHER - Flat interpolation using either vertex.
  1553. */
  1554. /**
  1555. * Finds the minimum value in an array.
  1556. *
  1557. * @private
  1558. * @param {Array<number>} array - The array to search for the minimum value.
  1559. * @return {number} The minimum value in the array, or Infinity if the array is empty.
  1560. */
  1561. /**
  1562. * Checks if an array contains values that require Uint32 representation.
  1563. *
  1564. * This function determines whether the array contains any values >= 65535,
  1565. * which would require a Uint32Array rather than a Uint16Array for proper storage.
  1566. * The function iterates from the end of the array, assuming larger values are
  1567. * typically located at the end.
  1568. *
  1569. * @private
  1570. * @param {Array<number>} array - The array to check.
  1571. * @return {boolean} True if the array contains values >= 65535, false otherwise.
  1572. */
  1573. function arrayNeedsUint32( array ) {
  1574. // assumes larger values usually on last
  1575. for ( let i = array.length - 1; i >= 0; -- i ) {
  1576. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1577. }
  1578. return false;
  1579. }
  1580. /**
  1581. * Map of typed array constructor names to their constructors.
  1582. * This mapping enables dynamic creation of typed arrays based on string type names.
  1583. *
  1584. * @private
  1585. * @constant
  1586. * @type {Object<string, TypedArrayConstructor>}
  1587. */
  1588. const TYPED_ARRAYS = {
  1589. Int8Array: Int8Array,
  1590. Uint8Array: Uint8Array,
  1591. Uint8ClampedArray: Uint8ClampedArray,
  1592. Int16Array: Int16Array,
  1593. Uint16Array: Uint16Array,
  1594. Int32Array: Int32Array,
  1595. Uint32Array: Uint32Array,
  1596. Float32Array: Float32Array,
  1597. Float64Array: Float64Array
  1598. };
  1599. /**
  1600. * Creates a typed array of the specified type from the given buffer.
  1601. *
  1602. * @private
  1603. * @param {string} type - The name of the typed array type (e.g., 'Float32Array', 'Uint16Array').
  1604. * @param {ArrayBuffer} buffer - The buffer to create the typed array from.
  1605. * @return {TypedArray} A new typed array of the specified type.
  1606. */
  1607. function getTypedArray( type, buffer ) {
  1608. return new TYPED_ARRAYS[ type ]( buffer );
  1609. }
  1610. /**
  1611. * Returns `true` if the given object is a typed array.
  1612. *
  1613. * @param {any} array - The object to check.
  1614. * @return {boolean} Whether the given object is a typed array.
  1615. */
  1616. function isTypedArray( array ) {
  1617. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1618. }
  1619. /**
  1620. * Creates an XHTML element with the specified tag name.
  1621. *
  1622. * This function uses the XHTML namespace to create DOM elements,
  1623. * ensuring proper element creation in XML-based contexts.
  1624. *
  1625. * @private
  1626. * @param {string} name - The tag name of the element to create (e.g., 'canvas', 'div').
  1627. * @return {HTMLElement} The created XHTML element.
  1628. */
  1629. function createElementNS( name ) {
  1630. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1631. }
  1632. /**
  1633. * Creates a canvas element configured for block display.
  1634. *
  1635. * This is a convenience function that creates a canvas element with
  1636. * display style set to 'block', which is commonly used in three.js
  1637. * rendering contexts to avoid inline element spacing issues.
  1638. *
  1639. * @return {HTMLCanvasElement} A canvas element with display set to 'block'.
  1640. */
  1641. function createCanvasElement() {
  1642. const canvas = createElementNS( 'canvas' );
  1643. canvas.style.display = 'block';
  1644. return canvas;
  1645. }
  1646. /**
  1647. * Internal cache for tracking warning messages to prevent duplicate warnings.
  1648. *
  1649. * @private
  1650. * @type {Object<string, boolean>}
  1651. */
  1652. const _cache = {};
  1653. /**
  1654. * Custom console function handler for intercepting log, warn, and error calls.
  1655. *
  1656. * @private
  1657. * @type {Function|null}
  1658. */
  1659. let _setConsoleFunction = null;
  1660. /**
  1661. * Sets a custom function to handle console output.
  1662. *
  1663. * This allows external code to intercept and handle console.log, console.warn,
  1664. * and console.error calls made by three.js, which is useful for custom logging,
  1665. * testing, or debugging workflows.
  1666. *
  1667. * @param {Function} fn - The function to handle console output. Should accept
  1668. * (type, message, ...params) where type is 'log', 'warn', or 'error'.
  1669. */
  1670. function setConsoleFunction( fn ) {
  1671. _setConsoleFunction = fn;
  1672. }
  1673. /**
  1674. * Gets the currently set custom console function.
  1675. *
  1676. * @return {Function|null} The custom console function, or null if not set.
  1677. */
  1678. function getConsoleFunction() {
  1679. return _setConsoleFunction;
  1680. }
  1681. /**
  1682. * Logs an informational message with the 'THREE.' prefix.
  1683. *
  1684. * If a custom console function is set via setConsoleFunction(), it will be used
  1685. * instead of the native console.log. The first parameter is treated as the
  1686. * method name and is automatically prefixed with 'THREE.'.
  1687. *
  1688. * @param {...any} params - The message components. The first param is used as
  1689. * the method name and prefixed with 'THREE.'.
  1690. */
  1691. function log( ...params ) {
  1692. const message = 'THREE.' + params.shift();
  1693. if ( _setConsoleFunction ) {
  1694. _setConsoleFunction( 'log', message, ...params );
  1695. } else {
  1696. console.log( message, ...params );
  1697. }
  1698. }
  1699. /**
  1700. * Enhances log/warn/error messages related to TSL.
  1701. *
  1702. * @param {Array<any>} params - The original message parameters.
  1703. * @returns {Array<any>} The filtered and enhanced message parameters.
  1704. */
  1705. function enhanceLogMessage( params ) {
  1706. const message = params[ 0 ];
  1707. if ( typeof message === 'string' && message.startsWith( 'TSL:' ) ) {
  1708. const stackTrace = params[ 1 ];
  1709. if ( stackTrace && stackTrace.isStackTrace ) {
  1710. params[ 0 ] += ' ' + stackTrace.getLocation();
  1711. } else {
  1712. params[ 1 ] = 'Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.';
  1713. }
  1714. }
  1715. return params;
  1716. }
  1717. /**
  1718. * Logs a warning message with the 'THREE.' prefix.
  1719. *
  1720. * If a custom console function is set via setConsoleFunction(), it will be used
  1721. * instead of the native console.warn. The first parameter is treated as the
  1722. * method name and is automatically prefixed with 'THREE.'.
  1723. *
  1724. * @param {...any} params - The message components. The first param is used as
  1725. * the method name and prefixed with 'THREE.'.
  1726. */
  1727. function warn( ...params ) {
  1728. params = enhanceLogMessage( params );
  1729. const message = 'THREE.' + params.shift();
  1730. if ( _setConsoleFunction ) {
  1731. _setConsoleFunction( 'warn', message, ...params );
  1732. } else {
  1733. const stackTrace = params[ 0 ];
  1734. if ( stackTrace && stackTrace.isStackTrace ) {
  1735. console.warn( stackTrace.getError( message ) );
  1736. } else {
  1737. console.warn( message, ...params );
  1738. }
  1739. }
  1740. }
  1741. /**
  1742. * Logs an error message with the 'THREE.' prefix.
  1743. *
  1744. * If a custom console function is set via setConsoleFunction(), it will be used
  1745. * instead of the native console.error. The first parameter is treated as the
  1746. * method name and is automatically prefixed with 'THREE.'.
  1747. *
  1748. * @param {...any} params - The message components. The first param is used as
  1749. * the method name and prefixed with 'THREE.'.
  1750. */
  1751. function error( ...params ) {
  1752. params = enhanceLogMessage( params );
  1753. const message = 'THREE.' + params.shift();
  1754. if ( _setConsoleFunction ) {
  1755. _setConsoleFunction( 'error', message, ...params );
  1756. } else {
  1757. const stackTrace = params[ 0 ];
  1758. if ( stackTrace && stackTrace.isStackTrace ) {
  1759. console.error( stackTrace.getError( message ) );
  1760. } else {
  1761. console.error( message, ...params );
  1762. }
  1763. }
  1764. }
  1765. /**
  1766. * Logs a warning message only once, preventing duplicate warnings.
  1767. *
  1768. * This function maintains an internal cache of warning messages and will only
  1769. * output each unique warning message once. Useful for warnings that may be
  1770. * triggered repeatedly but should only be shown to the user once.
  1771. *
  1772. * @param {...any} params - The warning message components.
  1773. */
  1774. function warnOnce( ...params ) {
  1775. const message = params.join( ' ' );
  1776. if ( message in _cache ) return;
  1777. _cache[ message ] = true;
  1778. warn( ...params );
  1779. }
  1780. /**
  1781. * Asynchronously probes for WebGL sync object completion.
  1782. *
  1783. * This function creates a promise that resolves when the WebGL sync object
  1784. * signals completion or rejects if the sync operation fails. It uses polling
  1785. * at the specified interval to check the sync status without blocking the
  1786. * main thread. This is useful for GPU-CPU synchronization in WebGL contexts.
  1787. *
  1788. * @private
  1789. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL rendering context.
  1790. * @param {WebGLSync} sync - The WebGL sync object to wait for.
  1791. * @param {number} interval - The polling interval in milliseconds.
  1792. * @return {Promise<void>} A promise that resolves when the sync completes or rejects if it fails.
  1793. */
  1794. function probeAsync( gl, sync, interval ) {
  1795. return new Promise( function ( resolve, reject ) {
  1796. function probe() {
  1797. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1798. case gl.WAIT_FAILED:
  1799. reject();
  1800. break;
  1801. case gl.TIMEOUT_EXPIRED:
  1802. setTimeout( probe, interval );
  1803. break;
  1804. default:
  1805. resolve();
  1806. }
  1807. }
  1808. setTimeout( probe, interval );
  1809. } );
  1810. }
  1811. /**
  1812. * This modules allows to dispatch event objects on custom JavaScript objects.
  1813. *
  1814. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1815. *
  1816. * Code Example:
  1817. * ```js
  1818. * class Car extends EventDispatcher {
  1819. * start() {
  1820. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1821. * }
  1822. *};
  1823. *
  1824. * // Using events with the custom object
  1825. * const car = new Car();
  1826. * car.addEventListener( 'start', function ( event ) {
  1827. * alert( event.message );
  1828. * } );
  1829. *
  1830. * car.start();
  1831. * ```
  1832. */
  1833. class EventDispatcher {
  1834. /**
  1835. * Adds the given event listener to the given event type.
  1836. *
  1837. * @param {string} type - The type of event to listen to.
  1838. * @param {Function} listener - The function that gets called when the event is fired.
  1839. */
  1840. addEventListener( type, listener ) {
  1841. if ( this._listeners === undefined ) this._listeners = {};
  1842. const listeners = this._listeners;
  1843. if ( listeners[ type ] === undefined ) {
  1844. listeners[ type ] = [];
  1845. }
  1846. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1847. listeners[ type ].push( listener );
  1848. }
  1849. }
  1850. /**
  1851. * Returns `true` if the given event listener has been added to the given event type.
  1852. *
  1853. * @param {string} type - The type of event.
  1854. * @param {Function} listener - The listener to check.
  1855. * @return {boolean} Whether the given event listener has been added to the given event type.
  1856. */
  1857. hasEventListener( type, listener ) {
  1858. const listeners = this._listeners;
  1859. if ( listeners === undefined ) return false;
  1860. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1861. }
  1862. /**
  1863. * Removes the given event listener from the given event type.
  1864. *
  1865. * @param {string} type - The type of event.
  1866. * @param {Function} listener - The listener to remove.
  1867. */
  1868. removeEventListener( type, listener ) {
  1869. const listeners = this._listeners;
  1870. if ( listeners === undefined ) return;
  1871. const listenerArray = listeners[ type ];
  1872. if ( listenerArray !== undefined ) {
  1873. const index = listenerArray.indexOf( listener );
  1874. if ( index !== -1 ) {
  1875. listenerArray.splice( index, 1 );
  1876. }
  1877. }
  1878. }
  1879. /**
  1880. * Dispatches an event object.
  1881. *
  1882. * @param {Object} event - The event that gets fired.
  1883. */
  1884. dispatchEvent( event ) {
  1885. const listeners = this._listeners;
  1886. if ( listeners === undefined ) return;
  1887. const listenerArray = listeners[ event.type ];
  1888. if ( listenerArray !== undefined ) {
  1889. event.target = this;
  1890. // Make a copy, in case listeners are removed while iterating.
  1891. const array = listenerArray.slice( 0 );
  1892. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1893. array[ i ].call( this, event );
  1894. }
  1895. event.target = null;
  1896. }
  1897. }
  1898. }
  1899. 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' ];
  1900. let _seed = 1234567;
  1901. const DEG2RAD = Math.PI / 180;
  1902. const RAD2DEG = 180 / Math.PI;
  1903. /**
  1904. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1905. * (universally unique identifier).
  1906. *
  1907. * @return {string} The UUID.
  1908. */
  1909. function generateUUID() {
  1910. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1911. const d0 = Math.random() * 0xffffffff | 0;
  1912. const d1 = Math.random() * 0xffffffff | 0;
  1913. const d2 = Math.random() * 0xffffffff | 0;
  1914. const d3 = Math.random() * 0xffffffff | 0;
  1915. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1916. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1917. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1918. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1919. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1920. return uuid.toLowerCase();
  1921. }
  1922. /**
  1923. * Clamps the given value between min and max.
  1924. *
  1925. * @param {number} value - The value to clamp.
  1926. * @param {number} min - The min value.
  1927. * @param {number} max - The max value.
  1928. * @return {number} The clamped value.
  1929. */
  1930. function clamp( value, min, max ) {
  1931. return Math.max( min, Math.min( max, value ) );
  1932. }
  1933. /**
  1934. * Computes the Euclidean modulo of the given parameters that
  1935. * is `( ( n % m ) + m ) % m`.
  1936. *
  1937. * @param {number} n - The first parameter.
  1938. * @param {number} m - The second parameter.
  1939. * @return {number} The Euclidean modulo.
  1940. */
  1941. function euclideanModulo( n, m ) {
  1942. // https://en.wikipedia.org/wiki/Modulo_operation
  1943. return ( ( n % m ) + m ) % m;
  1944. }
  1945. /**
  1946. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1947. * for the given value. `a2` must be greater than `a1`.
  1948. *
  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. function mapLinear( x, a1, a2, b1, b2 ) {
  1957. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1958. }
  1959. /**
  1960. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1961. * between the start and end point.
  1962. *
  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. function inverseLerp( x, y, value ) {
  1969. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1970. if ( x !== y ) {
  1971. return ( value - x ) / ( y - x );
  1972. } else {
  1973. return 0;
  1974. }
  1975. }
  1976. /**
  1977. * Returns a value linearly interpolated from two known points based on the given interval -
  1978. * `t = 0` will return `x` and `t = 1` will return `y`.
  1979. *
  1980. * @param {number} x - The start point
  1981. * @param {number} y - The end point.
  1982. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1983. * @return {number} The interpolated value.
  1984. */
  1985. function lerp( x, y, t ) {
  1986. return ( 1 - t ) * x + t * y;
  1987. }
  1988. /**
  1989. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1990. * time to maintain frame rate independent movement. For details, see
  1991. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  1992. *
  1993. * @param {number} x - The current point.
  1994. * @param {number} y - The target point.
  1995. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1996. * and a lower value will make the movement more gradual.
  1997. * @param {number} dt - Delta time in seconds.
  1998. * @return {number} The interpolated value.
  1999. */
  2000. function damp( x, y, lambda, dt ) {
  2001. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  2002. }
  2003. /**
  2004. * Returns a value that alternates between `0` and the given `length` parameter.
  2005. *
  2006. * @param {number} x - The value to pingpong.
  2007. * @param {number} [length=1] - The positive value the function will pingpong to.
  2008. * @return {number} The alternated value.
  2009. */
  2010. function pingpong( x, length = 1 ) {
  2011. // https://www.desmos.com/calculator/vcsjnyz7x4
  2012. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  2013. }
  2014. /**
  2015. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2016. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2017. * the `min` and `max`.
  2018. *
  2019. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2020. *
  2021. * @param {number} x - The value to evaluate based on its position between `min` and `max`.
  2022. * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`.
  2023. * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`.
  2024. * @return {number} The alternated value.
  2025. */
  2026. function smoothstep( x, min, max ) {
  2027. if ( x <= min ) return 0;
  2028. if ( x >= max ) return 1;
  2029. x = ( x - min ) / ( max - min );
  2030. return x * x * ( 3 - 2 * x );
  2031. }
  2032. /**
  2033. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2034. * that has zero 1st and 2nd order derivatives at `x=0` and `x=1`.
  2035. *
  2036. * @param {number} x - The value to evaluate based on its position between `min` and `max`.
  2037. * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`.
  2038. * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`.
  2039. * @return {number} The alternated value.
  2040. */
  2041. function smootherstep( x, min, max ) {
  2042. if ( x <= min ) return 0;
  2043. if ( x >= max ) return 1;
  2044. x = ( x - min ) / ( max - min );
  2045. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  2046. }
  2047. /**
  2048. * Returns a random integer from `<low, high>` interval.
  2049. *
  2050. * @param {number} low - The lower value boundary.
  2051. * @param {number} high - The upper value boundary
  2052. * @return {number} A random integer.
  2053. */
  2054. function randInt( low, high ) {
  2055. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2056. }
  2057. /**
  2058. * Returns a random float from `<low, high>` interval.
  2059. *
  2060. * @param {number} low - The lower value boundary.
  2061. * @param {number} high - The upper value boundary
  2062. * @return {number} A random float.
  2063. */
  2064. function randFloat( low, high ) {
  2065. return low + Math.random() * ( high - low );
  2066. }
  2067. /**
  2068. * Returns a random integer from `<-range/2, range/2>` interval.
  2069. *
  2070. * @param {number} range - Defines the value range.
  2071. * @return {number} A random float.
  2072. */
  2073. function randFloatSpread( range ) {
  2074. return range * ( 0.5 - Math.random() );
  2075. }
  2076. /**
  2077. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2078. *
  2079. * @param {number} [s] - The integer seed.
  2080. * @return {number} A random float.
  2081. */
  2082. function seededRandom( s ) {
  2083. if ( s !== undefined ) _seed = s;
  2084. // Mulberry32 generator
  2085. let t = _seed += 0x6D2B79F5;
  2086. t = Math.imul( t ^ t >>> 15, t | 1 );
  2087. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  2088. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  2089. }
  2090. /**
  2091. * Converts degrees to radians.
  2092. *
  2093. * @param {number} degrees - A value in degrees.
  2094. * @return {number} The converted value in radians.
  2095. */
  2096. function degToRad( degrees ) {
  2097. return degrees * DEG2RAD;
  2098. }
  2099. /**
  2100. * Converts radians to degrees.
  2101. *
  2102. * @param {number} radians - A value in radians.
  2103. * @return {number} The converted value in degrees.
  2104. */
  2105. function radToDeg( radians ) {
  2106. return radians * RAD2DEG;
  2107. }
  2108. /**
  2109. * Returns `true` if the given number is a power of two.
  2110. *
  2111. * @param {number} value - The value to check.
  2112. * @return {boolean} Whether the given number is a power of two or not.
  2113. */
  2114. function isPowerOfTwo( value ) {
  2115. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  2116. }
  2117. /**
  2118. * Returns the smallest power of two that is greater than or equal to the given number.
  2119. *
  2120. * @param {number} value - The value to find a POT for. Must be greater than `0`.
  2121. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2122. */
  2123. function ceilPowerOfTwo( value ) {
  2124. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  2125. }
  2126. /**
  2127. * Returns the largest power of two that is less than or equal to the given number.
  2128. *
  2129. * @param {number} value - The value to find a POT for. Must be greater than `0`.
  2130. * @return {number} The largest power of two that is less than or equal to the given number.
  2131. */
  2132. function floorPowerOfTwo( value ) {
  2133. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  2134. }
  2135. /**
  2136. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2137. * defined by the given angles and order.
  2138. *
  2139. * Rotations are applied to the axes in the order specified by order:
  2140. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2141. *
  2142. * @param {Quaternion} q - The quaternion to set.
  2143. * @param {number} a - The rotation applied to the first axis, in radians.
  2144. * @param {number} b - The rotation applied to the second axis, in radians.
  2145. * @param {number} c - The rotation applied to the third axis, in radians.
  2146. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2147. */
  2148. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  2149. const cos = Math.cos;
  2150. const sin = Math.sin;
  2151. const c2 = cos( b / 2 );
  2152. const s2 = sin( b / 2 );
  2153. const c13 = cos( ( a + c ) / 2 );
  2154. const s13 = sin( ( a + c ) / 2 );
  2155. const c1_3 = cos( ( a - c ) / 2 );
  2156. const s1_3 = sin( ( a - c ) / 2 );
  2157. const c3_1 = cos( ( c - a ) / 2 );
  2158. const s3_1 = sin( ( c - a ) / 2 );
  2159. switch ( order ) {
  2160. case 'XYX':
  2161. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  2162. break;
  2163. case 'YZY':
  2164. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  2165. break;
  2166. case 'ZXZ':
  2167. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  2168. break;
  2169. case 'XZX':
  2170. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  2171. break;
  2172. case 'YXY':
  2173. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  2174. break;
  2175. case 'ZYZ':
  2176. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  2177. break;
  2178. default:
  2179. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  2180. }
  2181. }
  2182. /**
  2183. * Denormalizes the given value according to the given typed array.
  2184. *
  2185. * @param {number} value - The value to denormalize.
  2186. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2187. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2188. */
  2189. function denormalize( value, array ) {
  2190. switch ( array.constructor ) {
  2191. case Float32Array:
  2192. return value;
  2193. case Uint32Array:
  2194. return value / 4294967295.0;
  2195. case Uint16Array:
  2196. return value / 65535.0;
  2197. case Uint8Array:
  2198. return value / 255.0;
  2199. case Int32Array:
  2200. return Math.max( value / 2147483647.0, -1 );
  2201. case Int16Array:
  2202. return Math.max( value / 32767.0, -1 );
  2203. case Int8Array:
  2204. return Math.max( value / 127.0, -1 );
  2205. default:
  2206. throw new Error( 'Invalid component type.' );
  2207. }
  2208. }
  2209. /**
  2210. * Normalizes the given value according to the given typed array.
  2211. *
  2212. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2213. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2214. * @return {number} The normalize value.
  2215. */
  2216. function normalize( value, array ) {
  2217. switch ( array.constructor ) {
  2218. case Float32Array:
  2219. return value;
  2220. case Uint32Array:
  2221. return Math.round( value * 4294967295.0 );
  2222. case Uint16Array:
  2223. return Math.round( value * 65535.0 );
  2224. case Uint8Array:
  2225. return Math.round( value * 255.0 );
  2226. case Int32Array:
  2227. return Math.round( value * 2147483647.0 );
  2228. case Int16Array:
  2229. return Math.round( value * 32767.0 );
  2230. case Int8Array:
  2231. return Math.round( value * 127.0 );
  2232. default:
  2233. throw new Error( 'Invalid component type.' );
  2234. }
  2235. }
  2236. /**
  2237. * @class
  2238. * @classdesc A collection of math utility functions.
  2239. * @hideconstructor
  2240. */
  2241. const MathUtils = {
  2242. DEG2RAD: DEG2RAD,
  2243. RAD2DEG: RAD2DEG,
  2244. /**
  2245. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2246. * (universally unique identifier).
  2247. *
  2248. * @static
  2249. * @method
  2250. * @return {string} The UUID.
  2251. */
  2252. generateUUID: generateUUID,
  2253. /**
  2254. * Clamps the given value between min and max.
  2255. *
  2256. * @static
  2257. * @method
  2258. * @param {number} value - The value to clamp.
  2259. * @param {number} min - The min value.
  2260. * @param {number} max - The max value.
  2261. * @return {number} The clamped value.
  2262. */
  2263. clamp: clamp,
  2264. /**
  2265. * Computes the Euclidean modulo of the given parameters that
  2266. * is `( ( n % m ) + m ) % m`.
  2267. *
  2268. * @static
  2269. * @method
  2270. * @param {number} n - The first parameter.
  2271. * @param {number} m - The second parameter.
  2272. * @return {number} The Euclidean modulo.
  2273. */
  2274. euclideanModulo: euclideanModulo,
  2275. /**
  2276. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2277. * for the given value.
  2278. *
  2279. * @static
  2280. * @method
  2281. * @param {number} x - The value to be mapped.
  2282. * @param {number} a1 - Minimum value for range A.
  2283. * @param {number} a2 - Maximum value for range A.
  2284. * @param {number} b1 - Minimum value for range B.
  2285. * @param {number} b2 - Maximum value for range B.
  2286. * @return {number} The mapped value.
  2287. */
  2288. mapLinear: mapLinear,
  2289. /**
  2290. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2291. * between the start and end point.
  2292. *
  2293. * @static
  2294. * @method
  2295. * @param {number} x - The start point
  2296. * @param {number} y - The end point.
  2297. * @param {number} value - A value between start and end.
  2298. * @return {number} The interpolation factor.
  2299. */
  2300. inverseLerp: inverseLerp,
  2301. /**
  2302. * Returns a value linearly interpolated from two known points based on the given interval -
  2303. * `t = 0` will return `x` and `t = 1` will return `y`.
  2304. *
  2305. * @static
  2306. * @method
  2307. * @param {number} x - The start point
  2308. * @param {number} y - The end point.
  2309. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2310. * @return {number} The interpolated value.
  2311. */
  2312. lerp: lerp,
  2313. /**
  2314. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2315. * time to maintain frame rate independent movement. For details, see
  2316. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2317. *
  2318. * @static
  2319. * @method
  2320. * @param {number} x - The current point.
  2321. * @param {number} y - The target point.
  2322. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2323. * and a lower value will make the movement more gradual.
  2324. * @param {number} dt - Delta time in seconds.
  2325. * @return {number} The interpolated value.
  2326. */
  2327. damp: damp,
  2328. /**
  2329. * Returns a value that alternates between `0` and the given `length` parameter.
  2330. *
  2331. * @static
  2332. * @method
  2333. * @param {number} x - The value to pingpong.
  2334. * @param {number} [length=1] - The positive value the function will pingpong to.
  2335. * @return {number} The alternated value.
  2336. */
  2337. pingpong: pingpong,
  2338. /**
  2339. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2340. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2341. * the `min` and `max`.
  2342. *
  2343. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2344. *
  2345. * @static
  2346. * @method
  2347. * @param {number} x - The value to evaluate based on its position between min and max.
  2348. * @param {number} min - The min value. Any x value below min will be `0`.
  2349. * @param {number} max - The max value. Any x value above max will be `1`.
  2350. * @return {number} The alternated value.
  2351. */
  2352. smoothstep: smoothstep,
  2353. /**
  2354. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2355. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2356. *
  2357. * @static
  2358. * @method
  2359. * @param {number} x - The value to evaluate based on its position between min and max.
  2360. * @param {number} min - The min value. Any x value below min will be `0`.
  2361. * @param {number} max - The max value. Any x value above max will be `1`.
  2362. * @return {number} The alternated value.
  2363. */
  2364. smootherstep: smootherstep,
  2365. /**
  2366. * Returns a random integer from `<low, high>` interval.
  2367. *
  2368. * @static
  2369. * @method
  2370. * @param {number} low - The lower value boundary.
  2371. * @param {number} high - The upper value boundary
  2372. * @return {number} A random integer.
  2373. */
  2374. randInt: randInt,
  2375. /**
  2376. * Returns a random float from `<low, high>` interval.
  2377. *
  2378. * @static
  2379. * @method
  2380. * @param {number} low - The lower value boundary.
  2381. * @param {number} high - The upper value boundary
  2382. * @return {number} A random float.
  2383. */
  2384. randFloat: randFloat,
  2385. /**
  2386. * Returns a random integer from `<-range/2, range/2>` interval.
  2387. *
  2388. * @static
  2389. * @method
  2390. * @param {number} range - Defines the value range.
  2391. * @return {number} A random float.
  2392. */
  2393. randFloatSpread: randFloatSpread,
  2394. /**
  2395. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2396. *
  2397. * @static
  2398. * @method
  2399. * @param {number} [s] - The integer seed.
  2400. * @return {number} A random float.
  2401. */
  2402. seededRandom: seededRandom,
  2403. /**
  2404. * Converts degrees to radians.
  2405. *
  2406. * @static
  2407. * @method
  2408. * @param {number} degrees - A value in degrees.
  2409. * @return {number} The converted value in radians.
  2410. */
  2411. degToRad: degToRad,
  2412. /**
  2413. * Converts radians to degrees.
  2414. *
  2415. * @static
  2416. * @method
  2417. * @param {number} radians - A value in radians.
  2418. * @return {number} The converted value in degrees.
  2419. */
  2420. radToDeg: radToDeg,
  2421. /**
  2422. * Returns `true` if the given number is a power of two.
  2423. *
  2424. * @static
  2425. * @method
  2426. * @param {number} value - The value to check.
  2427. * @return {boolean} Whether the given number is a power of two or not.
  2428. */
  2429. isPowerOfTwo: isPowerOfTwo,
  2430. /**
  2431. * Returns the smallest power of two that is greater than or equal to the given number.
  2432. *
  2433. * @static
  2434. * @method
  2435. * @param {number} value - The value to find a POT for.
  2436. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2437. */
  2438. ceilPowerOfTwo: ceilPowerOfTwo,
  2439. /**
  2440. * Returns the largest power of two that is less than or equal to the given number.
  2441. *
  2442. * @static
  2443. * @method
  2444. * @param {number} value - The value to find a POT for.
  2445. * @return {number} The largest power of two that is less than or equal to the given number.
  2446. */
  2447. floorPowerOfTwo: floorPowerOfTwo,
  2448. /**
  2449. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2450. * defined by the given angles and order.
  2451. *
  2452. * Rotations are applied to the axes in the order specified by order:
  2453. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2454. *
  2455. * @static
  2456. * @method
  2457. * @param {Quaternion} q - The quaternion to set.
  2458. * @param {number} a - The rotation applied to the first axis, in radians.
  2459. * @param {number} b - The rotation applied to the second axis, in radians.
  2460. * @param {number} c - The rotation applied to the third axis, in radians.
  2461. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2462. */
  2463. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2464. /**
  2465. * Normalizes the given value according to the given typed array.
  2466. *
  2467. * @static
  2468. * @method
  2469. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2470. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2471. * @return {number} The normalize value.
  2472. */
  2473. normalize: normalize,
  2474. /**
  2475. * Denormalizes the given value according to the given typed array.
  2476. *
  2477. * @static
  2478. * @method
  2479. * @param {number} value - The value to denormalize.
  2480. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2481. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2482. */
  2483. denormalize: denormalize
  2484. };
  2485. /**
  2486. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2487. * (labeled x and y), which can be used to represent a number of things, such as:
  2488. *
  2489. * - A point in 2D space (i.e. a position on a plane).
  2490. * - A direction and length across a plane. In three.js the length will
  2491. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2492. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2493. * - Any arbitrary ordered pair of numbers.
  2494. *
  2495. * There are other things a 2D vector can be used to represent, such as
  2496. * momentum vectors, complex numbers and so on, however these are the most
  2497. * common uses in three.js.
  2498. *
  2499. * Iterating through a vector instance will yield its components `(x, y)` in
  2500. * the corresponding order.
  2501. * ```js
  2502. * const a = new THREE.Vector2( 0, 1 );
  2503. *
  2504. * //no arguments; will be initialised to (0, 0)
  2505. * const b = new THREE.Vector2( );
  2506. *
  2507. * const d = a.distanceTo( b );
  2508. * ```
  2509. */
  2510. class Vector2 {
  2511. /**
  2512. * Constructs a new 2D vector.
  2513. *
  2514. * @param {number} [x=0] - The x value of this vector.
  2515. * @param {number} [y=0] - The y value of this vector.
  2516. */
  2517. constructor( x = 0, y = 0 ) {
  2518. /**
  2519. * This flag can be used for type testing.
  2520. *
  2521. * @type {boolean}
  2522. * @readonly
  2523. * @default true
  2524. */
  2525. Vector2.prototype.isVector2 = true;
  2526. /**
  2527. * The x value of this vector.
  2528. *
  2529. * @type {number}
  2530. */
  2531. this.x = x;
  2532. /**
  2533. * The y value of this vector.
  2534. *
  2535. * @type {number}
  2536. */
  2537. this.y = y;
  2538. }
  2539. /**
  2540. * Alias for {@link Vector2#x}.
  2541. *
  2542. * @type {number}
  2543. */
  2544. get width() {
  2545. return this.x;
  2546. }
  2547. set width( value ) {
  2548. this.x = value;
  2549. }
  2550. /**
  2551. * Alias for {@link Vector2#y}.
  2552. *
  2553. * @type {number}
  2554. */
  2555. get height() {
  2556. return this.y;
  2557. }
  2558. set height( value ) {
  2559. this.y = value;
  2560. }
  2561. /**
  2562. * Sets the vector components.
  2563. *
  2564. * @param {number} x - The value of the x component.
  2565. * @param {number} y - The value of the y component.
  2566. * @return {Vector2} A reference to this vector.
  2567. */
  2568. set( x, y ) {
  2569. this.x = x;
  2570. this.y = y;
  2571. return this;
  2572. }
  2573. /**
  2574. * Sets the vector components to the same value.
  2575. *
  2576. * @param {number} scalar - The value to set for all vector components.
  2577. * @return {Vector2} A reference to this vector.
  2578. */
  2579. setScalar( scalar ) {
  2580. this.x = scalar;
  2581. this.y = scalar;
  2582. return this;
  2583. }
  2584. /**
  2585. * Sets the vector's x component to the given value
  2586. *
  2587. * @param {number} x - The value to set.
  2588. * @return {Vector2} A reference to this vector.
  2589. */
  2590. setX( x ) {
  2591. this.x = x;
  2592. return this;
  2593. }
  2594. /**
  2595. * Sets the vector's y component to the given value
  2596. *
  2597. * @param {number} y - The value to set.
  2598. * @return {Vector2} A reference to this vector.
  2599. */
  2600. setY( y ) {
  2601. this.y = y;
  2602. return this;
  2603. }
  2604. /**
  2605. * Allows to set a vector component with an index.
  2606. *
  2607. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2608. * @param {number} value - The value to set.
  2609. * @return {Vector2} A reference to this vector.
  2610. */
  2611. setComponent( index, value ) {
  2612. switch ( index ) {
  2613. case 0: this.x = value; break;
  2614. case 1: this.y = value; break;
  2615. default: throw new Error( 'index is out of range: ' + index );
  2616. }
  2617. return this;
  2618. }
  2619. /**
  2620. * Returns the value of the vector component which matches the given index.
  2621. *
  2622. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2623. * @return {number} A vector component value.
  2624. */
  2625. getComponent( index ) {
  2626. switch ( index ) {
  2627. case 0: return this.x;
  2628. case 1: return this.y;
  2629. default: throw new Error( 'index is out of range: ' + index );
  2630. }
  2631. }
  2632. /**
  2633. * Returns a new vector with copied values from this instance.
  2634. *
  2635. * @return {Vector2} A clone of this instance.
  2636. */
  2637. clone() {
  2638. return new this.constructor( this.x, this.y );
  2639. }
  2640. /**
  2641. * Copies the values of the given vector to this instance.
  2642. *
  2643. * @param {Vector2} v - The vector to copy.
  2644. * @return {Vector2} A reference to this vector.
  2645. */
  2646. copy( v ) {
  2647. this.x = v.x;
  2648. this.y = v.y;
  2649. return this;
  2650. }
  2651. /**
  2652. * Adds the given vector to this instance.
  2653. *
  2654. * @param {Vector2} v - The vector to add.
  2655. * @return {Vector2} A reference to this vector.
  2656. */
  2657. add( v ) {
  2658. this.x += v.x;
  2659. this.y += v.y;
  2660. return this;
  2661. }
  2662. /**
  2663. * Adds the given scalar value to all components of this instance.
  2664. *
  2665. * @param {number} s - The scalar to add.
  2666. * @return {Vector2} A reference to this vector.
  2667. */
  2668. addScalar( s ) {
  2669. this.x += s;
  2670. this.y += s;
  2671. return this;
  2672. }
  2673. /**
  2674. * Adds the given vectors and stores the result in this instance.
  2675. *
  2676. * @param {Vector2} a - The first vector.
  2677. * @param {Vector2} b - The second vector.
  2678. * @return {Vector2} A reference to this vector.
  2679. */
  2680. addVectors( a, b ) {
  2681. this.x = a.x + b.x;
  2682. this.y = a.y + b.y;
  2683. return this;
  2684. }
  2685. /**
  2686. * Adds the given vector scaled by the given factor to this instance.
  2687. *
  2688. * @param {Vector2} v - The vector.
  2689. * @param {number} s - The factor that scales `v`.
  2690. * @return {Vector2} A reference to this vector.
  2691. */
  2692. addScaledVector( v, s ) {
  2693. this.x += v.x * s;
  2694. this.y += v.y * s;
  2695. return this;
  2696. }
  2697. /**
  2698. * Subtracts the given vector from this instance.
  2699. *
  2700. * @param {Vector2} v - The vector to subtract.
  2701. * @return {Vector2} A reference to this vector.
  2702. */
  2703. sub( v ) {
  2704. this.x -= v.x;
  2705. this.y -= v.y;
  2706. return this;
  2707. }
  2708. /**
  2709. * Subtracts the given scalar value from all components of this instance.
  2710. *
  2711. * @param {number} s - The scalar to subtract.
  2712. * @return {Vector2} A reference to this vector.
  2713. */
  2714. subScalar( s ) {
  2715. this.x -= s;
  2716. this.y -= s;
  2717. return this;
  2718. }
  2719. /**
  2720. * Subtracts the given vectors and stores the result in this instance.
  2721. *
  2722. * @param {Vector2} a - The first vector.
  2723. * @param {Vector2} b - The second vector.
  2724. * @return {Vector2} A reference to this vector.
  2725. */
  2726. subVectors( a, b ) {
  2727. this.x = a.x - b.x;
  2728. this.y = a.y - b.y;
  2729. return this;
  2730. }
  2731. /**
  2732. * Multiplies the given vector with this instance.
  2733. *
  2734. * @param {Vector2} v - The vector to multiply.
  2735. * @return {Vector2} A reference to this vector.
  2736. */
  2737. multiply( v ) {
  2738. this.x *= v.x;
  2739. this.y *= v.y;
  2740. return this;
  2741. }
  2742. /**
  2743. * Multiplies the given scalar value with all components of this instance.
  2744. *
  2745. * @param {number} scalar - The scalar to multiply.
  2746. * @return {Vector2} A reference to this vector.
  2747. */
  2748. multiplyScalar( scalar ) {
  2749. this.x *= scalar;
  2750. this.y *= scalar;
  2751. return this;
  2752. }
  2753. /**
  2754. * Divides this instance by the given vector.
  2755. *
  2756. * @param {Vector2} v - The vector to divide.
  2757. * @return {Vector2} A reference to this vector.
  2758. */
  2759. divide( v ) {
  2760. this.x /= v.x;
  2761. this.y /= v.y;
  2762. return this;
  2763. }
  2764. /**
  2765. * Divides this vector by the given scalar.
  2766. *
  2767. * @param {number} scalar - The scalar to divide.
  2768. * @return {Vector2} A reference to this vector.
  2769. */
  2770. divideScalar( scalar ) {
  2771. return this.multiplyScalar( 1 / scalar );
  2772. }
  2773. /**
  2774. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2775. * the given 3x3 matrix.
  2776. *
  2777. * @param {Matrix3} m - The matrix to apply.
  2778. * @return {Vector2} A reference to this vector.
  2779. */
  2780. applyMatrix3( m ) {
  2781. const x = this.x, y = this.y;
  2782. const e = m.elements;
  2783. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2784. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2785. return this;
  2786. }
  2787. /**
  2788. * If this vector's x or y value is greater than the given vector's x or y
  2789. * value, replace that value with the corresponding min value.
  2790. *
  2791. * @param {Vector2} v - The vector.
  2792. * @return {Vector2} A reference to this vector.
  2793. */
  2794. min( v ) {
  2795. this.x = Math.min( this.x, v.x );
  2796. this.y = Math.min( this.y, v.y );
  2797. return this;
  2798. }
  2799. /**
  2800. * If this vector's x or y value is less than the given vector's x or y
  2801. * value, replace that value with the corresponding max value.
  2802. *
  2803. * @param {Vector2} v - The vector.
  2804. * @return {Vector2} A reference to this vector.
  2805. */
  2806. max( v ) {
  2807. this.x = Math.max( this.x, v.x );
  2808. this.y = Math.max( this.y, v.y );
  2809. return this;
  2810. }
  2811. /**
  2812. * If this vector's x or y value is greater than the max vector's x or y
  2813. * value, it is replaced by the corresponding value.
  2814. * If this vector's x or y value is less than the min vector's x or y value,
  2815. * it is replaced by the corresponding value.
  2816. *
  2817. * @param {Vector2} min - The minimum x and y values.
  2818. * @param {Vector2} max - The maximum x and y values in the desired range.
  2819. * @return {Vector2} A reference to this vector.
  2820. */
  2821. clamp( min, max ) {
  2822. // assumes min < max, componentwise
  2823. this.x = clamp( this.x, min.x, max.x );
  2824. this.y = clamp( this.y, min.y, max.y );
  2825. return this;
  2826. }
  2827. /**
  2828. * If this vector's x or y values are greater than the max value, they are
  2829. * replaced by the max value.
  2830. * If this vector's x or y values are less than the min value, they are
  2831. * replaced by the min value.
  2832. *
  2833. * @param {number} minVal - The minimum value the components will be clamped to.
  2834. * @param {number} maxVal - The maximum value the components will be clamped to.
  2835. * @return {Vector2} A reference to this vector.
  2836. */
  2837. clampScalar( minVal, maxVal ) {
  2838. this.x = clamp( this.x, minVal, maxVal );
  2839. this.y = clamp( this.y, minVal, maxVal );
  2840. return this;
  2841. }
  2842. /**
  2843. * If this vector's length is greater than the max value, it is replaced by
  2844. * the max value.
  2845. * If this vector's length is less than the min value, it is replaced by the
  2846. * min value.
  2847. *
  2848. * @param {number} min - The minimum value the vector length will be clamped to.
  2849. * @param {number} max - The maximum value the vector length will be clamped to.
  2850. * @return {Vector2} A reference to this vector.
  2851. */
  2852. clampLength( min, max ) {
  2853. const length = this.length();
  2854. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2855. }
  2856. /**
  2857. * The components of this vector are rounded down to the nearest integer value.
  2858. *
  2859. * @return {Vector2} A reference to this vector.
  2860. */
  2861. floor() {
  2862. this.x = Math.floor( this.x );
  2863. this.y = Math.floor( this.y );
  2864. return this;
  2865. }
  2866. /**
  2867. * The components of this vector are rounded up to the nearest integer value.
  2868. *
  2869. * @return {Vector2} A reference to this vector.
  2870. */
  2871. ceil() {
  2872. this.x = Math.ceil( this.x );
  2873. this.y = Math.ceil( this.y );
  2874. return this;
  2875. }
  2876. /**
  2877. * The components of this vector are rounded to the nearest integer value
  2878. *
  2879. * @return {Vector2} A reference to this vector.
  2880. */
  2881. round() {
  2882. this.x = Math.round( this.x );
  2883. this.y = Math.round( this.y );
  2884. return this;
  2885. }
  2886. /**
  2887. * The components of this vector are rounded towards zero (up if negative,
  2888. * down if positive) to an integer value.
  2889. *
  2890. * @return {Vector2} A reference to this vector.
  2891. */
  2892. roundToZero() {
  2893. this.x = Math.trunc( this.x );
  2894. this.y = Math.trunc( this.y );
  2895. return this;
  2896. }
  2897. /**
  2898. * Inverts this vector - i.e. sets x = -x and y = -y.
  2899. *
  2900. * @return {Vector2} A reference to this vector.
  2901. */
  2902. negate() {
  2903. this.x = - this.x;
  2904. this.y = - this.y;
  2905. return this;
  2906. }
  2907. /**
  2908. * Calculates the dot product of the given vector with this instance.
  2909. *
  2910. * @param {Vector2} v - The vector to compute the dot product with.
  2911. * @return {number} The result of the dot product.
  2912. */
  2913. dot( v ) {
  2914. return this.x * v.x + this.y * v.y;
  2915. }
  2916. /**
  2917. * Calculates the cross product of the given vector with this instance.
  2918. *
  2919. * @param {Vector2} v - The vector to compute the cross product with.
  2920. * @return {number} The result of the cross product.
  2921. */
  2922. cross( v ) {
  2923. return this.x * v.y - this.y * v.x;
  2924. }
  2925. /**
  2926. * Computes the square of the Euclidean length (straight-line length) from
  2927. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2928. * compare the length squared instead as it is slightly more efficient to calculate.
  2929. *
  2930. * @return {number} The square length of this vector.
  2931. */
  2932. lengthSq() {
  2933. return this.x * this.x + this.y * this.y;
  2934. }
  2935. /**
  2936. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2937. *
  2938. * @return {number} The length of this vector.
  2939. */
  2940. length() {
  2941. return Math.sqrt( this.x * this.x + this.y * this.y );
  2942. }
  2943. /**
  2944. * Computes the Manhattan length of this vector.
  2945. *
  2946. * @return {number} The length of this vector.
  2947. */
  2948. manhattanLength() {
  2949. return Math.abs( this.x ) + Math.abs( this.y );
  2950. }
  2951. /**
  2952. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2953. * with the same direction as this one, but with a vector length of `1`.
  2954. *
  2955. * @return {Vector2} A reference to this vector.
  2956. */
  2957. normalize() {
  2958. return this.divideScalar( this.length() || 1 );
  2959. }
  2960. /**
  2961. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2962. *
  2963. * @return {number} The angle in radians.
  2964. */
  2965. angle() {
  2966. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2967. return angle;
  2968. }
  2969. /**
  2970. * Returns the angle between the given vector and this instance in radians.
  2971. *
  2972. * @param {Vector2} v - The vector to compute the angle with.
  2973. * @return {number} The angle in radians.
  2974. */
  2975. angleTo( v ) {
  2976. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2977. if ( denominator === 0 ) return Math.PI / 2;
  2978. const theta = this.dot( v ) / denominator;
  2979. // clamp, to handle numerical problems
  2980. return Math.acos( clamp( theta, -1, 1 ) );
  2981. }
  2982. /**
  2983. * Computes the distance from the given vector to this instance.
  2984. *
  2985. * @param {Vector2} v - The vector to compute the distance to.
  2986. * @return {number} The distance.
  2987. */
  2988. distanceTo( v ) {
  2989. return Math.sqrt( this.distanceToSquared( v ) );
  2990. }
  2991. /**
  2992. * Computes the squared distance from the given vector to this instance.
  2993. * If you are just comparing the distance with another distance, you should compare
  2994. * the distance squared instead as it is slightly more efficient to calculate.
  2995. *
  2996. * @param {Vector2} v - The vector to compute the squared distance to.
  2997. * @return {number} The squared distance.
  2998. */
  2999. distanceToSquared( v ) {
  3000. const dx = this.x - v.x, dy = this.y - v.y;
  3001. return dx * dx + dy * dy;
  3002. }
  3003. /**
  3004. * Computes the Manhattan distance from the given vector to this instance.
  3005. *
  3006. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  3007. * @return {number} The Manhattan distance.
  3008. */
  3009. manhattanDistanceTo( v ) {
  3010. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  3011. }
  3012. /**
  3013. * Sets this vector to a vector with the same direction as this one, but
  3014. * with the specified length.
  3015. *
  3016. * @param {number} length - The new length of this vector.
  3017. * @return {Vector2} A reference to this vector.
  3018. */
  3019. setLength( length ) {
  3020. return this.normalize().multiplyScalar( length );
  3021. }
  3022. /**
  3023. * Linearly interpolates between the given vector and this instance, where
  3024. * alpha is the percent distance along the line - alpha = 0 will be this
  3025. * vector, and alpha = 1 will be the given one.
  3026. *
  3027. * @param {Vector2} v - The vector to interpolate towards.
  3028. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3029. * @return {Vector2} A reference to this vector.
  3030. */
  3031. lerp( v, alpha ) {
  3032. this.x += ( v.x - this.x ) * alpha;
  3033. this.y += ( v.y - this.y ) * alpha;
  3034. return this;
  3035. }
  3036. /**
  3037. * Linearly interpolates between the given vectors, where alpha is the percent
  3038. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  3039. * be the second one. The result is stored in this instance.
  3040. *
  3041. * @param {Vector2} v1 - The first vector.
  3042. * @param {Vector2} v2 - The second vector.
  3043. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3044. * @return {Vector2} A reference to this vector.
  3045. */
  3046. lerpVectors( v1, v2, alpha ) {
  3047. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3048. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3049. return this;
  3050. }
  3051. /**
  3052. * Returns `true` if this vector is equal with the given one.
  3053. *
  3054. * @param {Vector2} v - The vector to test for equality.
  3055. * @return {boolean} Whether this vector is equal with the given one.
  3056. */
  3057. equals( v ) {
  3058. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  3059. }
  3060. /**
  3061. * Sets this vector's x value to be `array[ offset ]` and y
  3062. * value to be `array[ offset + 1 ]`.
  3063. *
  3064. * @param {Array<number>} array - An array holding the vector component values.
  3065. * @param {number} [offset=0] - The offset into the array.
  3066. * @return {Vector2} A reference to this vector.
  3067. */
  3068. fromArray( array, offset = 0 ) {
  3069. this.x = array[ offset ];
  3070. this.y = array[ offset + 1 ];
  3071. return this;
  3072. }
  3073. /**
  3074. * Writes the components of this vector to the given array. If no array is provided,
  3075. * the method returns a new instance.
  3076. *
  3077. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  3078. * @param {number} [offset=0] - Index of the first element in the array.
  3079. * @return {Array<number>} The vector components.
  3080. */
  3081. toArray( array = [], offset = 0 ) {
  3082. array[ offset ] = this.x;
  3083. array[ offset + 1 ] = this.y;
  3084. return array;
  3085. }
  3086. /**
  3087. * Sets the components of this vector from the given buffer attribute.
  3088. *
  3089. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  3090. * @param {number} index - The index into the attribute.
  3091. * @return {Vector2} A reference to this vector.
  3092. */
  3093. fromBufferAttribute( attribute, index ) {
  3094. this.x = attribute.getX( index );
  3095. this.y = attribute.getY( index );
  3096. return this;
  3097. }
  3098. /**
  3099. * Rotates this vector around the given center by the given angle.
  3100. *
  3101. * @param {Vector2} center - The point around which to rotate.
  3102. * @param {number} angle - The angle to rotate, in radians.
  3103. * @return {Vector2} A reference to this vector.
  3104. */
  3105. rotateAround( center, angle ) {
  3106. const c = Math.cos( angle ), s = Math.sin( angle );
  3107. const x = this.x - center.x;
  3108. const y = this.y - center.y;
  3109. this.x = x * c - y * s + center.x;
  3110. this.y = x * s + y * c + center.y;
  3111. return this;
  3112. }
  3113. /**
  3114. * Sets each component of this vector to a pseudo-random value between `0` and
  3115. * `1`, excluding `1`.
  3116. *
  3117. * @return {Vector2} A reference to this vector.
  3118. */
  3119. random() {
  3120. this.x = Math.random();
  3121. this.y = Math.random();
  3122. return this;
  3123. }
  3124. *[ Symbol.iterator ]() {
  3125. yield this.x;
  3126. yield this.y;
  3127. }
  3128. }
  3129. /**
  3130. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  3131. *
  3132. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  3133. * the corresponding order.
  3134. *
  3135. * Note that three.js expects Quaternions to be normalized.
  3136. * ```js
  3137. * const quaternion = new THREE.Quaternion();
  3138. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  3139. *
  3140. * const vector = new THREE.Vector3( 1, 0, 0 );
  3141. * vector.applyQuaternion( quaternion );
  3142. * ```
  3143. */
  3144. class Quaternion {
  3145. /**
  3146. * Constructs a new quaternion.
  3147. *
  3148. * @param {number} [x=0] - The x value of this quaternion.
  3149. * @param {number} [y=0] - The y value of this quaternion.
  3150. * @param {number} [z=0] - The z value of this quaternion.
  3151. * @param {number} [w=1] - The w value of this quaternion.
  3152. */
  3153. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  3154. /**
  3155. * This flag can be used for type testing.
  3156. *
  3157. * @type {boolean}
  3158. * @readonly
  3159. * @default true
  3160. */
  3161. this.isQuaternion = true;
  3162. this._x = x;
  3163. this._y = y;
  3164. this._z = z;
  3165. this._w = w;
  3166. }
  3167. /**
  3168. * Interpolates between two quaternions via SLERP. This implementation assumes the
  3169. * quaternion data are managed in flat arrays.
  3170. *
  3171. * @param {Array<number>} dst - The destination array.
  3172. * @param {number} dstOffset - An offset into the destination array.
  3173. * @param {Array<number>} src0 - The source array of the first quaternion.
  3174. * @param {number} srcOffset0 - An offset into the first source array.
  3175. * @param {Array<number>} src1 - The source array of the second quaternion.
  3176. * @param {number} srcOffset1 - An offset into the second source array.
  3177. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3178. * @see {@link Quaternion#slerp}
  3179. */
  3180. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3181. let x0 = src0[ srcOffset0 + 0 ],
  3182. y0 = src0[ srcOffset0 + 1 ],
  3183. z0 = src0[ srcOffset0 + 2 ],
  3184. w0 = src0[ srcOffset0 + 3 ];
  3185. let x1 = src1[ srcOffset1 + 0 ],
  3186. y1 = src1[ srcOffset1 + 1 ],
  3187. z1 = src1[ srcOffset1 + 2 ],
  3188. w1 = src1[ srcOffset1 + 3 ];
  3189. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3190. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3191. if ( dot < 0 ) {
  3192. x1 = - x1;
  3193. y1 = - y1;
  3194. z1 = - z1;
  3195. w1 = - w1;
  3196. dot = - dot;
  3197. }
  3198. let s = 1 - t;
  3199. if ( dot < 0.9995 ) {
  3200. // slerp
  3201. const theta = Math.acos( dot );
  3202. const sin = Math.sin( theta );
  3203. s = Math.sin( s * theta ) / sin;
  3204. t = Math.sin( t * theta ) / sin;
  3205. x0 = x0 * s + x1 * t;
  3206. y0 = y0 * s + y1 * t;
  3207. z0 = z0 * s + z1 * t;
  3208. w0 = w0 * s + w1 * t;
  3209. } else {
  3210. // for small angles, lerp then normalize
  3211. x0 = x0 * s + x1 * t;
  3212. y0 = y0 * s + y1 * t;
  3213. z0 = z0 * s + z1 * t;
  3214. w0 = w0 * s + w1 * t;
  3215. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3216. x0 *= f;
  3217. y0 *= f;
  3218. z0 *= f;
  3219. w0 *= f;
  3220. }
  3221. }
  3222. dst[ dstOffset ] = x0;
  3223. dst[ dstOffset + 1 ] = y0;
  3224. dst[ dstOffset + 2 ] = z0;
  3225. dst[ dstOffset + 3 ] = w0;
  3226. }
  3227. /**
  3228. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3229. * in flat arrays.
  3230. *
  3231. * @param {Array<number>} dst - The destination array.
  3232. * @param {number} dstOffset - An offset into the destination array.
  3233. * @param {Array<number>} src0 - The source array of the first quaternion.
  3234. * @param {number} srcOffset0 - An offset into the first source array.
  3235. * @param {Array<number>} src1 - The source array of the second quaternion.
  3236. * @param {number} srcOffset1 - An offset into the second source array.
  3237. * @return {Array<number>} The destination array.
  3238. * @see {@link Quaternion#multiplyQuaternions}.
  3239. */
  3240. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3241. const x0 = src0[ srcOffset0 ];
  3242. const y0 = src0[ srcOffset0 + 1 ];
  3243. const z0 = src0[ srcOffset0 + 2 ];
  3244. const w0 = src0[ srcOffset0 + 3 ];
  3245. const x1 = src1[ srcOffset1 ];
  3246. const y1 = src1[ srcOffset1 + 1 ];
  3247. const z1 = src1[ srcOffset1 + 2 ];
  3248. const w1 = src1[ srcOffset1 + 3 ];
  3249. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3250. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3251. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3252. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3253. return dst;
  3254. }
  3255. /**
  3256. * The x value of this quaternion.
  3257. *
  3258. * @type {number}
  3259. * @default 0
  3260. */
  3261. get x() {
  3262. return this._x;
  3263. }
  3264. set x( value ) {
  3265. this._x = value;
  3266. this._onChangeCallback();
  3267. }
  3268. /**
  3269. * The y value of this quaternion.
  3270. *
  3271. * @type {number}
  3272. * @default 0
  3273. */
  3274. get y() {
  3275. return this._y;
  3276. }
  3277. set y( value ) {
  3278. this._y = value;
  3279. this._onChangeCallback();
  3280. }
  3281. /**
  3282. * The z value of this quaternion.
  3283. *
  3284. * @type {number}
  3285. * @default 0
  3286. */
  3287. get z() {
  3288. return this._z;
  3289. }
  3290. set z( value ) {
  3291. this._z = value;
  3292. this._onChangeCallback();
  3293. }
  3294. /**
  3295. * The w value of this quaternion.
  3296. *
  3297. * @type {number}
  3298. * @default 1
  3299. */
  3300. get w() {
  3301. return this._w;
  3302. }
  3303. set w( value ) {
  3304. this._w = value;
  3305. this._onChangeCallback();
  3306. }
  3307. /**
  3308. * Sets the quaternion components.
  3309. *
  3310. * @param {number} x - The x value of this quaternion.
  3311. * @param {number} y - The y value of this quaternion.
  3312. * @param {number} z - The z value of this quaternion.
  3313. * @param {number} w - The w value of this quaternion.
  3314. * @return {Quaternion} A reference to this quaternion.
  3315. */
  3316. set( x, y, z, w ) {
  3317. this._x = x;
  3318. this._y = y;
  3319. this._z = z;
  3320. this._w = w;
  3321. this._onChangeCallback();
  3322. return this;
  3323. }
  3324. /**
  3325. * Returns a new quaternion with copied values from this instance.
  3326. *
  3327. * @return {Quaternion} A clone of this instance.
  3328. */
  3329. clone() {
  3330. return new this.constructor( this._x, this._y, this._z, this._w );
  3331. }
  3332. /**
  3333. * Copies the values of the given quaternion to this instance.
  3334. *
  3335. * @param {Quaternion} quaternion - The quaternion to copy.
  3336. * @return {Quaternion} A reference to this quaternion.
  3337. */
  3338. copy( quaternion ) {
  3339. this._x = quaternion.x;
  3340. this._y = quaternion.y;
  3341. this._z = quaternion.z;
  3342. this._w = quaternion.w;
  3343. this._onChangeCallback();
  3344. return this;
  3345. }
  3346. /**
  3347. * Sets this quaternion from the rotation specified by the given
  3348. * Euler angles.
  3349. *
  3350. * @param {Euler} euler - The Euler angles.
  3351. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3352. * @return {Quaternion} A reference to this quaternion.
  3353. */
  3354. setFromEuler( euler, update = true ) {
  3355. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3356. // http://www.mathworks.com/matlabcentral/fileexchange/
  3357. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3358. // content/SpinCalc.m
  3359. const cos = Math.cos;
  3360. const sin = Math.sin;
  3361. const c1 = cos( x / 2 );
  3362. const c2 = cos( y / 2 );
  3363. const c3 = cos( z / 2 );
  3364. const s1 = sin( x / 2 );
  3365. const s2 = sin( y / 2 );
  3366. const s3 = sin( z / 2 );
  3367. switch ( order ) {
  3368. case 'XYZ':
  3369. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3370. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3371. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3372. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3373. break;
  3374. case 'YXZ':
  3375. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3376. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3377. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3378. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3379. break;
  3380. case 'ZXY':
  3381. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3382. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3383. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3384. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3385. break;
  3386. case 'ZYX':
  3387. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3388. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3389. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3390. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3391. break;
  3392. case 'YZX':
  3393. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3394. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3395. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3396. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3397. break;
  3398. case 'XZY':
  3399. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3400. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3401. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3402. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3403. break;
  3404. default:
  3405. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3406. }
  3407. if ( update === true ) this._onChangeCallback();
  3408. return this;
  3409. }
  3410. /**
  3411. * Sets this quaternion from the given axis and angle.
  3412. *
  3413. * @param {Vector3} axis - The normalized axis.
  3414. * @param {number} angle - The angle in radians.
  3415. * @return {Quaternion} A reference to this quaternion.
  3416. */
  3417. setFromAxisAngle( axis, angle ) {
  3418. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3419. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3420. this._x = axis.x * s;
  3421. this._y = axis.y * s;
  3422. this._z = axis.z * s;
  3423. this._w = Math.cos( halfAngle );
  3424. this._onChangeCallback();
  3425. return this;
  3426. }
  3427. /**
  3428. * Sets this quaternion from the given rotation matrix.
  3429. *
  3430. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3431. * @return {Quaternion} A reference to this quaternion.
  3432. */
  3433. setFromRotationMatrix( m ) {
  3434. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3435. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3436. const te = m.elements,
  3437. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3438. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3439. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3440. trace = m11 + m22 + m33;
  3441. if ( trace > 0 ) {
  3442. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3443. this._w = 0.25 / s;
  3444. this._x = ( m32 - m23 ) * s;
  3445. this._y = ( m13 - m31 ) * s;
  3446. this._z = ( m21 - m12 ) * s;
  3447. } else if ( m11 > m22 && m11 > m33 ) {
  3448. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3449. this._w = ( m32 - m23 ) / s;
  3450. this._x = 0.25 * s;
  3451. this._y = ( m12 + m21 ) / s;
  3452. this._z = ( m13 + m31 ) / s;
  3453. } else if ( m22 > m33 ) {
  3454. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3455. this._w = ( m13 - m31 ) / s;
  3456. this._x = ( m12 + m21 ) / s;
  3457. this._y = 0.25 * s;
  3458. this._z = ( m23 + m32 ) / s;
  3459. } else {
  3460. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3461. this._w = ( m21 - m12 ) / s;
  3462. this._x = ( m13 + m31 ) / s;
  3463. this._y = ( m23 + m32 ) / s;
  3464. this._z = 0.25 * s;
  3465. }
  3466. this._onChangeCallback();
  3467. return this;
  3468. }
  3469. /**
  3470. * Sets this quaternion to the rotation required to rotate the direction vector
  3471. * `vFrom` to the direction vector `vTo`.
  3472. *
  3473. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3474. * @param {Vector3} vTo - The second (normalized) direction vector.
  3475. * @return {Quaternion} A reference to this quaternion.
  3476. */
  3477. setFromUnitVectors( vFrom, vTo ) {
  3478. // assumes direction vectors vFrom and vTo are normalized
  3479. let r = vFrom.dot( vTo ) + 1;
  3480. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3481. // vFrom and vTo point in opposite directions
  3482. r = 0;
  3483. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3484. this._x = - vFrom.y;
  3485. this._y = vFrom.x;
  3486. this._z = 0;
  3487. this._w = r;
  3488. } else {
  3489. this._x = 0;
  3490. this._y = - vFrom.z;
  3491. this._z = vFrom.y;
  3492. this._w = r;
  3493. }
  3494. } else {
  3495. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3496. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3497. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3498. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3499. this._w = r;
  3500. }
  3501. return this.normalize();
  3502. }
  3503. /**
  3504. * Returns the angle between this quaternion and the given one in radians.
  3505. *
  3506. * @param {Quaternion} q - The quaternion to compute the angle with.
  3507. * @return {number} The angle in radians.
  3508. */
  3509. angleTo( q ) {
  3510. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3511. }
  3512. /**
  3513. * Rotates this quaternion by a given angular step to the given quaternion.
  3514. * The method ensures that the final quaternion will not overshoot `q`.
  3515. *
  3516. * @param {Quaternion} q - The target quaternion.
  3517. * @param {number} step - The angular step in radians.
  3518. * @return {Quaternion} A reference to this quaternion.
  3519. */
  3520. rotateTowards( q, step ) {
  3521. const angle = this.angleTo( q );
  3522. if ( angle === 0 ) return this;
  3523. const t = Math.min( 1, step / angle );
  3524. this.slerp( q, t );
  3525. return this;
  3526. }
  3527. /**
  3528. * Sets this quaternion to the identity quaternion; that is, to the
  3529. * quaternion that represents "no rotation".
  3530. *
  3531. * @return {Quaternion} A reference to this quaternion.
  3532. */
  3533. identity() {
  3534. return this.set( 0, 0, 0, 1 );
  3535. }
  3536. /**
  3537. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3538. * quaternion is assumed to have unit length.
  3539. *
  3540. * @return {Quaternion} A reference to this quaternion.
  3541. */
  3542. invert() {
  3543. return this.conjugate();
  3544. }
  3545. /**
  3546. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3547. * quaternion represents the same rotation in the opposite direction about
  3548. * the rotational axis.
  3549. *
  3550. * @return {Quaternion} A reference to this quaternion.
  3551. */
  3552. conjugate() {
  3553. this._x *= -1;
  3554. this._y *= -1;
  3555. this._z *= -1;
  3556. this._onChangeCallback();
  3557. return this;
  3558. }
  3559. /**
  3560. * Calculates the dot product of this quaternion and the given one.
  3561. *
  3562. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3563. * @return {number} The result of the dot product.
  3564. */
  3565. dot( v ) {
  3566. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3567. }
  3568. /**
  3569. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3570. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3571. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3572. * {@link Quaternion#length}.
  3573. *
  3574. * @return {number} The squared Euclidean length.
  3575. */
  3576. lengthSq() {
  3577. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3578. }
  3579. /**
  3580. * Computes the Euclidean length (straight-line length) of this quaternion,
  3581. * considered as a 4 dimensional vector.
  3582. *
  3583. * @return {number} The Euclidean length.
  3584. */
  3585. length() {
  3586. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3587. }
  3588. /**
  3589. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3590. * the same rotation as this one, but has a length equal to `1`.
  3591. *
  3592. * @return {Quaternion} A reference to this quaternion.
  3593. */
  3594. normalize() {
  3595. let l = this.length();
  3596. if ( l === 0 ) {
  3597. this._x = 0;
  3598. this._y = 0;
  3599. this._z = 0;
  3600. this._w = 1;
  3601. } else {
  3602. l = 1 / l;
  3603. this._x = this._x * l;
  3604. this._y = this._y * l;
  3605. this._z = this._z * l;
  3606. this._w = this._w * l;
  3607. }
  3608. this._onChangeCallback();
  3609. return this;
  3610. }
  3611. /**
  3612. * Multiplies this quaternion by the given one.
  3613. *
  3614. * @param {Quaternion} q - The quaternion.
  3615. * @return {Quaternion} A reference to this quaternion.
  3616. */
  3617. multiply( q ) {
  3618. return this.multiplyQuaternions( this, q );
  3619. }
  3620. /**
  3621. * Pre-multiplies this quaternion by the given one.
  3622. *
  3623. * @param {Quaternion} q - The quaternion.
  3624. * @return {Quaternion} A reference to this quaternion.
  3625. */
  3626. premultiply( q ) {
  3627. return this.multiplyQuaternions( q, this );
  3628. }
  3629. /**
  3630. * Multiplies the given quaternions and stores the result in this instance.
  3631. *
  3632. * @param {Quaternion} a - The first quaternion.
  3633. * @param {Quaternion} b - The second quaternion.
  3634. * @return {Quaternion} A reference to this quaternion.
  3635. */
  3636. multiplyQuaternions( a, b ) {
  3637. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3638. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3639. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3640. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3641. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3642. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3643. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3644. this._onChangeCallback();
  3645. return this;
  3646. }
  3647. /**
  3648. * Performs a spherical linear interpolation between this quaternion and the target quaternion.
  3649. *
  3650. * @param {Quaternion} qb - The target quaternion.
  3651. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3652. * @return {Quaternion} A reference to this quaternion.
  3653. */
  3654. slerp( qb, t ) {
  3655. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3656. let dot = this.dot( qb );
  3657. if ( dot < 0 ) {
  3658. x = - x;
  3659. y = - y;
  3660. z = - z;
  3661. w = - w;
  3662. dot = - dot;
  3663. }
  3664. let s = 1 - t;
  3665. if ( dot < 0.9995 ) {
  3666. // slerp
  3667. const theta = Math.acos( dot );
  3668. const sin = Math.sin( theta );
  3669. s = Math.sin( s * theta ) / sin;
  3670. t = Math.sin( t * theta ) / sin;
  3671. this._x = this._x * s + x * t;
  3672. this._y = this._y * s + y * t;
  3673. this._z = this._z * s + z * t;
  3674. this._w = this._w * s + w * t;
  3675. this._onChangeCallback();
  3676. } else {
  3677. // for small angles, lerp then normalize
  3678. this._x = this._x * s + x * t;
  3679. this._y = this._y * s + y * t;
  3680. this._z = this._z * s + z * t;
  3681. this._w = this._w * s + w * t;
  3682. this.normalize(); // normalize calls _onChangeCallback()
  3683. }
  3684. return this;
  3685. }
  3686. /**
  3687. * Performs a spherical linear interpolation between the given quaternions
  3688. * and stores the result in this quaternion.
  3689. *
  3690. * @param {Quaternion} qa - The source quaternion.
  3691. * @param {Quaternion} qb - The target quaternion.
  3692. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3693. * @return {Quaternion} A reference to this quaternion.
  3694. */
  3695. slerpQuaternions( qa, qb, t ) {
  3696. return this.copy( qa ).slerp( qb, t );
  3697. }
  3698. /**
  3699. * Sets this quaternion to a uniformly random, normalized quaternion.
  3700. *
  3701. * @return {Quaternion} A reference to this quaternion.
  3702. */
  3703. random() {
  3704. // Ken Shoemake
  3705. // Uniform random rotations
  3706. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3707. const theta1 = 2 * Math.PI * Math.random();
  3708. const theta2 = 2 * Math.PI * Math.random();
  3709. const x0 = Math.random();
  3710. const r1 = Math.sqrt( 1 - x0 );
  3711. const r2 = Math.sqrt( x0 );
  3712. return this.set(
  3713. r1 * Math.sin( theta1 ),
  3714. r1 * Math.cos( theta1 ),
  3715. r2 * Math.sin( theta2 ),
  3716. r2 * Math.cos( theta2 ),
  3717. );
  3718. }
  3719. /**
  3720. * Returns `true` if this quaternion is equal with the given one.
  3721. *
  3722. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3723. * @return {boolean} Whether this quaternion is equal with the given one.
  3724. */
  3725. equals( quaternion ) {
  3726. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3727. }
  3728. /**
  3729. * Sets this quaternion's components from the given array.
  3730. *
  3731. * @param {Array<number>} array - An array holding the quaternion component values.
  3732. * @param {number} [offset=0] - The offset into the array.
  3733. * @return {Quaternion} A reference to this quaternion.
  3734. */
  3735. fromArray( array, offset = 0 ) {
  3736. this._x = array[ offset ];
  3737. this._y = array[ offset + 1 ];
  3738. this._z = array[ offset + 2 ];
  3739. this._w = array[ offset + 3 ];
  3740. this._onChangeCallback();
  3741. return this;
  3742. }
  3743. /**
  3744. * Writes the components of this quaternion to the given array. If no array is provided,
  3745. * the method returns a new instance.
  3746. *
  3747. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3748. * @param {number} [offset=0] - Index of the first element in the array.
  3749. * @return {Array<number>} The quaternion components.
  3750. */
  3751. toArray( array = [], offset = 0 ) {
  3752. array[ offset ] = this._x;
  3753. array[ offset + 1 ] = this._y;
  3754. array[ offset + 2 ] = this._z;
  3755. array[ offset + 3 ] = this._w;
  3756. return array;
  3757. }
  3758. /**
  3759. * Sets the components of this quaternion from the given buffer attribute.
  3760. *
  3761. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3762. * @param {number} index - The index into the attribute.
  3763. * @return {Quaternion} A reference to this quaternion.
  3764. */
  3765. fromBufferAttribute( attribute, index ) {
  3766. this._x = attribute.getX( index );
  3767. this._y = attribute.getY( index );
  3768. this._z = attribute.getZ( index );
  3769. this._w = attribute.getW( index );
  3770. this._onChangeCallback();
  3771. return this;
  3772. }
  3773. /**
  3774. * This methods defines the serialization result of this class. Returns the
  3775. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3776. *
  3777. * @return {Array<number>} The serialized quaternion.
  3778. */
  3779. toJSON() {
  3780. return this.toArray();
  3781. }
  3782. _onChange( callback ) {
  3783. this._onChangeCallback = callback;
  3784. return this;
  3785. }
  3786. _onChangeCallback() {}
  3787. *[ Symbol.iterator ]() {
  3788. yield this._x;
  3789. yield this._y;
  3790. yield this._z;
  3791. yield this._w;
  3792. }
  3793. }
  3794. /**
  3795. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3796. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3797. *
  3798. * - A point in 3D space.
  3799. * - A direction and length in 3D space. In three.js the length will
  3800. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3801. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3802. * - Any arbitrary ordered triplet of numbers.
  3803. *
  3804. * There are other things a 3D vector can be used to represent, such as
  3805. * momentum vectors and so on, however these are the most
  3806. * common uses in three.js.
  3807. *
  3808. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3809. * the corresponding order.
  3810. * ```js
  3811. * const a = new THREE.Vector3( 0, 1, 0 );
  3812. *
  3813. * //no arguments; will be initialised to (0, 0, 0)
  3814. * const b = new THREE.Vector3( );
  3815. *
  3816. * const d = a.distanceTo( b );
  3817. * ```
  3818. */
  3819. class Vector3 {
  3820. /**
  3821. * Constructs a new 3D vector.
  3822. *
  3823. * @param {number} [x=0] - The x value of this vector.
  3824. * @param {number} [y=0] - The y value of this vector.
  3825. * @param {number} [z=0] - The z value of this vector.
  3826. */
  3827. constructor( x = 0, y = 0, z = 0 ) {
  3828. /**
  3829. * This flag can be used for type testing.
  3830. *
  3831. * @type {boolean}
  3832. * @readonly
  3833. * @default true
  3834. */
  3835. Vector3.prototype.isVector3 = true;
  3836. /**
  3837. * The x value of this vector.
  3838. *
  3839. * @type {number}
  3840. */
  3841. this.x = x;
  3842. /**
  3843. * The y value of this vector.
  3844. *
  3845. * @type {number}
  3846. */
  3847. this.y = y;
  3848. /**
  3849. * The z value of this vector.
  3850. *
  3851. * @type {number}
  3852. */
  3853. this.z = z;
  3854. }
  3855. /**
  3856. * Sets the vector components.
  3857. *
  3858. * @param {number} x - The value of the x component.
  3859. * @param {number} y - The value of the y component.
  3860. * @param {number} z - The value of the z component.
  3861. * @return {Vector3} A reference to this vector.
  3862. */
  3863. set( x, y, z ) {
  3864. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3865. this.x = x;
  3866. this.y = y;
  3867. this.z = z;
  3868. return this;
  3869. }
  3870. /**
  3871. * Sets the vector components to the same value.
  3872. *
  3873. * @param {number} scalar - The value to set for all vector components.
  3874. * @return {Vector3} A reference to this vector.
  3875. */
  3876. setScalar( scalar ) {
  3877. this.x = scalar;
  3878. this.y = scalar;
  3879. this.z = scalar;
  3880. return this;
  3881. }
  3882. /**
  3883. * Sets the vector's x component to the given value.
  3884. *
  3885. * @param {number} x - The value to set.
  3886. * @return {Vector3} A reference to this vector.
  3887. */
  3888. setX( x ) {
  3889. this.x = x;
  3890. return this;
  3891. }
  3892. /**
  3893. * Sets the vector's y component to the given value.
  3894. *
  3895. * @param {number} y - The value to set.
  3896. * @return {Vector3} A reference to this vector.
  3897. */
  3898. setY( y ) {
  3899. this.y = y;
  3900. return this;
  3901. }
  3902. /**
  3903. * Sets the vector's z component to the given value.
  3904. *
  3905. * @param {number} z - The value to set.
  3906. * @return {Vector3} A reference to this vector.
  3907. */
  3908. setZ( z ) {
  3909. this.z = z;
  3910. return this;
  3911. }
  3912. /**
  3913. * Allows to set a vector component with an index.
  3914. *
  3915. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3916. * @param {number} value - The value to set.
  3917. * @return {Vector3} A reference to this vector.
  3918. */
  3919. setComponent( index, value ) {
  3920. switch ( index ) {
  3921. case 0: this.x = value; break;
  3922. case 1: this.y = value; break;
  3923. case 2: this.z = value; break;
  3924. default: throw new Error( 'index is out of range: ' + index );
  3925. }
  3926. return this;
  3927. }
  3928. /**
  3929. * Returns the value of the vector component which matches the given index.
  3930. *
  3931. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3932. * @return {number} A vector component value.
  3933. */
  3934. getComponent( index ) {
  3935. switch ( index ) {
  3936. case 0: return this.x;
  3937. case 1: return this.y;
  3938. case 2: return this.z;
  3939. default: throw new Error( 'index is out of range: ' + index );
  3940. }
  3941. }
  3942. /**
  3943. * Returns a new vector with copied values from this instance.
  3944. *
  3945. * @return {Vector3} A clone of this instance.
  3946. */
  3947. clone() {
  3948. return new this.constructor( this.x, this.y, this.z );
  3949. }
  3950. /**
  3951. * Copies the values of the given vector to this instance.
  3952. *
  3953. * @param {Vector3} v - The vector to copy.
  3954. * @return {Vector3} A reference to this vector.
  3955. */
  3956. copy( v ) {
  3957. this.x = v.x;
  3958. this.y = v.y;
  3959. this.z = v.z;
  3960. return this;
  3961. }
  3962. /**
  3963. * Adds the given vector to this instance.
  3964. *
  3965. * @param {Vector3} v - The vector to add.
  3966. * @return {Vector3} A reference to this vector.
  3967. */
  3968. add( v ) {
  3969. this.x += v.x;
  3970. this.y += v.y;
  3971. this.z += v.z;
  3972. return this;
  3973. }
  3974. /**
  3975. * Adds the given scalar value to all components of this instance.
  3976. *
  3977. * @param {number} s - The scalar to add.
  3978. * @return {Vector3} A reference to this vector.
  3979. */
  3980. addScalar( s ) {
  3981. this.x += s;
  3982. this.y += s;
  3983. this.z += s;
  3984. return this;
  3985. }
  3986. /**
  3987. * Adds the given vectors and stores the result in this instance.
  3988. *
  3989. * @param {Vector3} a - The first vector.
  3990. * @param {Vector3} b - The second vector.
  3991. * @return {Vector3} A reference to this vector.
  3992. */
  3993. addVectors( a, b ) {
  3994. this.x = a.x + b.x;
  3995. this.y = a.y + b.y;
  3996. this.z = a.z + b.z;
  3997. return this;
  3998. }
  3999. /**
  4000. * Adds the given vector scaled by the given factor to this instance.
  4001. *
  4002. * @param {Vector3|Vector4} v - The vector.
  4003. * @param {number} s - The factor that scales `v`.
  4004. * @return {Vector3} A reference to this vector.
  4005. */
  4006. addScaledVector( v, s ) {
  4007. this.x += v.x * s;
  4008. this.y += v.y * s;
  4009. this.z += v.z * s;
  4010. return this;
  4011. }
  4012. /**
  4013. * Subtracts the given vector from this instance.
  4014. *
  4015. * @param {Vector3} v - The vector to subtract.
  4016. * @return {Vector3} A reference to this vector.
  4017. */
  4018. sub( v ) {
  4019. this.x -= v.x;
  4020. this.y -= v.y;
  4021. this.z -= v.z;
  4022. return this;
  4023. }
  4024. /**
  4025. * Subtracts the given scalar value from all components of this instance.
  4026. *
  4027. * @param {number} s - The scalar to subtract.
  4028. * @return {Vector3} A reference to this vector.
  4029. */
  4030. subScalar( s ) {
  4031. this.x -= s;
  4032. this.y -= s;
  4033. this.z -= s;
  4034. return this;
  4035. }
  4036. /**
  4037. * Subtracts the given vectors and stores the result in this instance.
  4038. *
  4039. * @param {Vector3} a - The first vector.
  4040. * @param {Vector3} b - The second vector.
  4041. * @return {Vector3} A reference to this vector.
  4042. */
  4043. subVectors( a, b ) {
  4044. this.x = a.x - b.x;
  4045. this.y = a.y - b.y;
  4046. this.z = a.z - b.z;
  4047. return this;
  4048. }
  4049. /**
  4050. * Multiplies the given vector with this instance.
  4051. *
  4052. * @param {Vector3} v - The vector to multiply.
  4053. * @return {Vector3} A reference to this vector.
  4054. */
  4055. multiply( v ) {
  4056. this.x *= v.x;
  4057. this.y *= v.y;
  4058. this.z *= v.z;
  4059. return this;
  4060. }
  4061. /**
  4062. * Multiplies the given scalar value with all components of this instance.
  4063. *
  4064. * @param {number} scalar - The scalar to multiply.
  4065. * @return {Vector3} A reference to this vector.
  4066. */
  4067. multiplyScalar( scalar ) {
  4068. this.x *= scalar;
  4069. this.y *= scalar;
  4070. this.z *= scalar;
  4071. return this;
  4072. }
  4073. /**
  4074. * Multiplies the given vectors and stores the result in this instance.
  4075. *
  4076. * @param {Vector3} a - The first vector.
  4077. * @param {Vector3} b - The second vector.
  4078. * @return {Vector3} A reference to this vector.
  4079. */
  4080. multiplyVectors( a, b ) {
  4081. this.x = a.x * b.x;
  4082. this.y = a.y * b.y;
  4083. this.z = a.z * b.z;
  4084. return this;
  4085. }
  4086. /**
  4087. * Applies the given Euler rotation to this vector.
  4088. *
  4089. * @param {Euler} euler - The Euler angles.
  4090. * @return {Vector3} A reference to this vector.
  4091. */
  4092. applyEuler( euler ) {
  4093. return this.applyQuaternion( _quaternion$5.setFromEuler( euler ) );
  4094. }
  4095. /**
  4096. * Applies a rotation specified by an axis and an angle to this vector.
  4097. *
  4098. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  4099. * @param {number} angle - The angle in radians.
  4100. * @return {Vector3} A reference to this vector.
  4101. */
  4102. applyAxisAngle( axis, angle ) {
  4103. return this.applyQuaternion( _quaternion$5.setFromAxisAngle( axis, angle ) );
  4104. }
  4105. /**
  4106. * Multiplies this vector with the given 3x3 matrix.
  4107. *
  4108. * @param {Matrix3} m - The 3x3 matrix.
  4109. * @return {Vector3} A reference to this vector.
  4110. */
  4111. applyMatrix3( m ) {
  4112. const x = this.x, y = this.y, z = this.z;
  4113. const e = m.elements;
  4114. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  4115. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  4116. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  4117. return this;
  4118. }
  4119. /**
  4120. * Multiplies this vector by the given normal matrix and normalizes
  4121. * the result.
  4122. *
  4123. * @param {Matrix3} m - The normal matrix.
  4124. * @return {Vector3} A reference to this vector.
  4125. */
  4126. applyNormalMatrix( m ) {
  4127. return this.applyMatrix3( m ).normalize();
  4128. }
  4129. /**
  4130. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  4131. * divides by perspective.
  4132. *
  4133. * @param {Matrix4} m - The matrix to apply.
  4134. * @return {Vector3} A reference to this vector.
  4135. */
  4136. applyMatrix4( m ) {
  4137. const x = this.x, y = this.y, z = this.z;
  4138. const e = m.elements;
  4139. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  4140. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  4141. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  4142. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  4143. return this;
  4144. }
  4145. /**
  4146. * Applies the given Quaternion to this vector.
  4147. *
  4148. * @param {Quaternion} q - The Quaternion.
  4149. * @return {Vector3} A reference to this vector.
  4150. */
  4151. applyQuaternion( q ) {
  4152. // quaternion q is assumed to have unit length
  4153. const vx = this.x, vy = this.y, vz = this.z;
  4154. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  4155. // t = 2 * cross( q.xyz, v );
  4156. const tx = 2 * ( qy * vz - qz * vy );
  4157. const ty = 2 * ( qz * vx - qx * vz );
  4158. const tz = 2 * ( qx * vy - qy * vx );
  4159. // v + q.w * t + cross( q.xyz, t );
  4160. this.x = vx + qw * tx + qy * tz - qz * ty;
  4161. this.y = vy + qw * ty + qz * tx - qx * tz;
  4162. this.z = vz + qw * tz + qx * ty - qy * tx;
  4163. return this;
  4164. }
  4165. /**
  4166. * Projects this vector from world space into the camera's normalized
  4167. * device coordinate (NDC) space.
  4168. *
  4169. * @param {Camera} camera - The camera.
  4170. * @return {Vector3} A reference to this vector.
  4171. */
  4172. project( camera ) {
  4173. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4174. }
  4175. /**
  4176. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4177. * space into world space.
  4178. *
  4179. * @param {Camera} camera - The camera.
  4180. * @return {Vector3} A reference to this vector.
  4181. */
  4182. unproject( camera ) {
  4183. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4184. }
  4185. /**
  4186. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4187. * subset of the given 4x4 matrix and then normalizes the result.
  4188. *
  4189. * @param {Matrix4} m - The matrix.
  4190. * @return {Vector3} A reference to this vector.
  4191. */
  4192. transformDirection( m ) {
  4193. // input: THREE.Matrix4 affine matrix
  4194. // vector interpreted as a direction
  4195. const x = this.x, y = this.y, z = this.z;
  4196. const e = m.elements;
  4197. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4198. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4199. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4200. return this.normalize();
  4201. }
  4202. /**
  4203. * Divides this instance by the given vector.
  4204. *
  4205. * @param {Vector3} v - The vector to divide.
  4206. * @return {Vector3} A reference to this vector.
  4207. */
  4208. divide( v ) {
  4209. this.x /= v.x;
  4210. this.y /= v.y;
  4211. this.z /= v.z;
  4212. return this;
  4213. }
  4214. /**
  4215. * Divides this vector by the given scalar.
  4216. *
  4217. * @param {number} scalar - The scalar to divide.
  4218. * @return {Vector3} A reference to this vector.
  4219. */
  4220. divideScalar( scalar ) {
  4221. return this.multiplyScalar( 1 / scalar );
  4222. }
  4223. /**
  4224. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4225. * value, replace that value with the corresponding min value.
  4226. *
  4227. * @param {Vector3} v - The vector.
  4228. * @return {Vector3} A reference to this vector.
  4229. */
  4230. min( v ) {
  4231. this.x = Math.min( this.x, v.x );
  4232. this.y = Math.min( this.y, v.y );
  4233. this.z = Math.min( this.z, v.z );
  4234. return this;
  4235. }
  4236. /**
  4237. * If this vector's x, y or z value is less than the given vector's x, y or z
  4238. * value, replace that value with the corresponding max value.
  4239. *
  4240. * @param {Vector3} v - The vector.
  4241. * @return {Vector3} A reference to this vector.
  4242. */
  4243. max( v ) {
  4244. this.x = Math.max( this.x, v.x );
  4245. this.y = Math.max( this.y, v.y );
  4246. this.z = Math.max( this.z, v.z );
  4247. return this;
  4248. }
  4249. /**
  4250. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4251. * value, it is replaced by the corresponding value.
  4252. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4253. * it is replaced by the corresponding value.
  4254. *
  4255. * @param {Vector3} min - The minimum x, y and z values.
  4256. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4257. * @return {Vector3} A reference to this vector.
  4258. */
  4259. clamp( min, max ) {
  4260. // assumes min < max, componentwise
  4261. this.x = clamp( this.x, min.x, max.x );
  4262. this.y = clamp( this.y, min.y, max.y );
  4263. this.z = clamp( this.z, min.z, max.z );
  4264. return this;
  4265. }
  4266. /**
  4267. * If this vector's x, y or z values are greater than the max value, they are
  4268. * replaced by the max value.
  4269. * If this vector's x, y or z values are less than the min value, they are
  4270. * replaced by the min value.
  4271. *
  4272. * @param {number} minVal - The minimum value the components will be clamped to.
  4273. * @param {number} maxVal - The maximum value the components will be clamped to.
  4274. * @return {Vector3} A reference to this vector.
  4275. */
  4276. clampScalar( minVal, maxVal ) {
  4277. this.x = clamp( this.x, minVal, maxVal );
  4278. this.y = clamp( this.y, minVal, maxVal );
  4279. this.z = clamp( this.z, minVal, maxVal );
  4280. return this;
  4281. }
  4282. /**
  4283. * If this vector's length is greater than the max value, it is replaced by
  4284. * the max value.
  4285. * If this vector's length is less than the min value, it is replaced by the
  4286. * min value.
  4287. *
  4288. * @param {number} min - The minimum value the vector length will be clamped to.
  4289. * @param {number} max - The maximum value the vector length will be clamped to.
  4290. * @return {Vector3} A reference to this vector.
  4291. */
  4292. clampLength( min, max ) {
  4293. const length = this.length();
  4294. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4295. }
  4296. /**
  4297. * The components of this vector are rounded down to the nearest integer value.
  4298. *
  4299. * @return {Vector3} A reference to this vector.
  4300. */
  4301. floor() {
  4302. this.x = Math.floor( this.x );
  4303. this.y = Math.floor( this.y );
  4304. this.z = Math.floor( this.z );
  4305. return this;
  4306. }
  4307. /**
  4308. * The components of this vector are rounded up to the nearest integer value.
  4309. *
  4310. * @return {Vector3} A reference to this vector.
  4311. */
  4312. ceil() {
  4313. this.x = Math.ceil( this.x );
  4314. this.y = Math.ceil( this.y );
  4315. this.z = Math.ceil( this.z );
  4316. return this;
  4317. }
  4318. /**
  4319. * The components of this vector are rounded to the nearest integer value
  4320. *
  4321. * @return {Vector3} A reference to this vector.
  4322. */
  4323. round() {
  4324. this.x = Math.round( this.x );
  4325. this.y = Math.round( this.y );
  4326. this.z = Math.round( this.z );
  4327. return this;
  4328. }
  4329. /**
  4330. * The components of this vector are rounded towards zero (up if negative,
  4331. * down if positive) to an integer value.
  4332. *
  4333. * @return {Vector3} A reference to this vector.
  4334. */
  4335. roundToZero() {
  4336. this.x = Math.trunc( this.x );
  4337. this.y = Math.trunc( this.y );
  4338. this.z = Math.trunc( this.z );
  4339. return this;
  4340. }
  4341. /**
  4342. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4343. *
  4344. * @return {Vector3} A reference to this vector.
  4345. */
  4346. negate() {
  4347. this.x = - this.x;
  4348. this.y = - this.y;
  4349. this.z = - this.z;
  4350. return this;
  4351. }
  4352. /**
  4353. * Calculates the dot product of the given vector with this instance.
  4354. *
  4355. * @param {Vector3} v - The vector to compute the dot product with.
  4356. * @return {number} The result of the dot product.
  4357. */
  4358. dot( v ) {
  4359. return this.x * v.x + this.y * v.y + this.z * v.z;
  4360. }
  4361. /**
  4362. * Computes the square of the Euclidean length (straight-line length) from
  4363. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4364. * compare the length squared instead as it is slightly more efficient to calculate.
  4365. *
  4366. * @return {number} The square length of this vector.
  4367. */
  4368. lengthSq() {
  4369. return this.x * this.x + this.y * this.y + this.z * this.z;
  4370. }
  4371. /**
  4372. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4373. *
  4374. * @return {number} The length of this vector.
  4375. */
  4376. length() {
  4377. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4378. }
  4379. /**
  4380. * Computes the Manhattan length of this vector.
  4381. *
  4382. * @return {number} The length of this vector.
  4383. */
  4384. manhattanLength() {
  4385. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4386. }
  4387. /**
  4388. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4389. * with the same direction as this one, but with a vector length of `1`.
  4390. *
  4391. * @return {Vector3} A reference to this vector.
  4392. */
  4393. normalize() {
  4394. return this.divideScalar( this.length() || 1 );
  4395. }
  4396. /**
  4397. * Sets this vector to a vector with the same direction as this one, but
  4398. * with the specified length.
  4399. *
  4400. * @param {number} length - The new length of this vector.
  4401. * @return {Vector3} A reference to this vector.
  4402. */
  4403. setLength( length ) {
  4404. return this.normalize().multiplyScalar( length );
  4405. }
  4406. /**
  4407. * Linearly interpolates between the given vector and this instance, where
  4408. * alpha is the percent distance along the line - alpha = 0 will be this
  4409. * vector, and alpha = 1 will be the given one.
  4410. *
  4411. * @param {Vector3} v - The vector to interpolate towards.
  4412. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4413. * @return {Vector3} A reference to this vector.
  4414. */
  4415. lerp( v, alpha ) {
  4416. this.x += ( v.x - this.x ) * alpha;
  4417. this.y += ( v.y - this.y ) * alpha;
  4418. this.z += ( v.z - this.z ) * alpha;
  4419. return this;
  4420. }
  4421. /**
  4422. * Linearly interpolates between the given vectors, where alpha is the percent
  4423. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4424. * be the second one. The result is stored in this instance.
  4425. *
  4426. * @param {Vector3} v1 - The first vector.
  4427. * @param {Vector3} v2 - The second vector.
  4428. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4429. * @return {Vector3} A reference to this vector.
  4430. */
  4431. lerpVectors( v1, v2, alpha ) {
  4432. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4433. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4434. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4435. return this;
  4436. }
  4437. /**
  4438. * Calculates the cross product of the given vector with this instance.
  4439. *
  4440. * @param {Vector3} v - The vector to compute the cross product with.
  4441. * @return {Vector3} The result of the cross product.
  4442. */
  4443. cross( v ) {
  4444. return this.crossVectors( this, v );
  4445. }
  4446. /**
  4447. * Calculates the cross product of the given vectors and stores the result
  4448. * in this instance.
  4449. *
  4450. * @param {Vector3} a - The first vector.
  4451. * @param {Vector3} b - The second vector.
  4452. * @return {Vector3} A reference to this vector.
  4453. */
  4454. crossVectors( a, b ) {
  4455. const ax = a.x, ay = a.y, az = a.z;
  4456. const bx = b.x, by = b.y, bz = b.z;
  4457. this.x = ay * bz - az * by;
  4458. this.y = az * bx - ax * bz;
  4459. this.z = ax * by - ay * bx;
  4460. return this;
  4461. }
  4462. /**
  4463. * Projects this vector onto the given one.
  4464. *
  4465. * @param {Vector3} v - The vector to project to.
  4466. * @return {Vector3} A reference to this vector.
  4467. */
  4468. projectOnVector( v ) {
  4469. const denominator = v.lengthSq();
  4470. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4471. const scalar = v.dot( this ) / denominator;
  4472. return this.copy( v ).multiplyScalar( scalar );
  4473. }
  4474. /**
  4475. * Projects this vector onto a plane by subtracting this
  4476. * vector projected onto the plane's normal from this vector.
  4477. *
  4478. * @param {Vector3} planeNormal - The plane normal.
  4479. * @return {Vector3} A reference to this vector.
  4480. */
  4481. projectOnPlane( planeNormal ) {
  4482. _vector$c.copy( this ).projectOnVector( planeNormal );
  4483. return this.sub( _vector$c );
  4484. }
  4485. /**
  4486. * Reflects this vector off a plane orthogonal to the given normal vector.
  4487. *
  4488. * @param {Vector3} normal - The (normalized) normal vector.
  4489. * @return {Vector3} A reference to this vector.
  4490. */
  4491. reflect( normal ) {
  4492. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4493. }
  4494. /**
  4495. * Returns the angle between the given vector and this instance in radians.
  4496. *
  4497. * @param {Vector3} v - The vector to compute the angle with.
  4498. * @return {number} The angle in radians.
  4499. */
  4500. angleTo( v ) {
  4501. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4502. if ( denominator === 0 ) return Math.PI / 2;
  4503. const theta = this.dot( v ) / denominator;
  4504. // clamp, to handle numerical problems
  4505. return Math.acos( clamp( theta, -1, 1 ) );
  4506. }
  4507. /**
  4508. * Computes the distance from the given vector to this instance.
  4509. *
  4510. * @param {Vector3} v - The vector to compute the distance to.
  4511. * @return {number} The distance.
  4512. */
  4513. distanceTo( v ) {
  4514. return Math.sqrt( this.distanceToSquared( v ) );
  4515. }
  4516. /**
  4517. * Computes the squared distance from the given vector to this instance.
  4518. * If you are just comparing the distance with another distance, you should compare
  4519. * the distance squared instead as it is slightly more efficient to calculate.
  4520. *
  4521. * @param {Vector3} v - The vector to compute the squared distance to.
  4522. * @return {number} The squared distance.
  4523. */
  4524. distanceToSquared( v ) {
  4525. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4526. return dx * dx + dy * dy + dz * dz;
  4527. }
  4528. /**
  4529. * Computes the Manhattan distance from the given vector to this instance.
  4530. *
  4531. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4532. * @return {number} The Manhattan distance.
  4533. */
  4534. manhattanDistanceTo( v ) {
  4535. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4536. }
  4537. /**
  4538. * Sets the vector components from the given spherical coordinates.
  4539. *
  4540. * @param {Spherical} s - The spherical coordinates.
  4541. * @return {Vector3} A reference to this vector.
  4542. */
  4543. setFromSpherical( s ) {
  4544. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4545. }
  4546. /**
  4547. * Sets the vector components from the given spherical coordinates.
  4548. *
  4549. * @param {number} radius - The radius.
  4550. * @param {number} phi - The phi angle in radians.
  4551. * @param {number} theta - The theta angle in radians.
  4552. * @return {Vector3} A reference to this vector.
  4553. */
  4554. setFromSphericalCoords( radius, phi, theta ) {
  4555. const sinPhiRadius = Math.sin( phi ) * radius;
  4556. this.x = sinPhiRadius * Math.sin( theta );
  4557. this.y = Math.cos( phi ) * radius;
  4558. this.z = sinPhiRadius * Math.cos( theta );
  4559. return this;
  4560. }
  4561. /**
  4562. * Sets the vector components from the given cylindrical coordinates.
  4563. *
  4564. * @param {Cylindrical} c - The cylindrical coordinates.
  4565. * @return {Vector3} A reference to this vector.
  4566. */
  4567. setFromCylindrical( c ) {
  4568. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4569. }
  4570. /**
  4571. * Sets the vector components from the given cylindrical coordinates.
  4572. *
  4573. * @param {number} radius - The radius.
  4574. * @param {number} theta - The theta angle in radians.
  4575. * @param {number} y - The y value.
  4576. * @return {Vector3} A reference to this vector.
  4577. */
  4578. setFromCylindricalCoords( radius, theta, y ) {
  4579. this.x = radius * Math.sin( theta );
  4580. this.y = y;
  4581. this.z = radius * Math.cos( theta );
  4582. return this;
  4583. }
  4584. /**
  4585. * Sets the vector components to the position elements of the
  4586. * given transformation matrix.
  4587. *
  4588. * @param {Matrix4} m - The 4x4 matrix.
  4589. * @return {Vector3} A reference to this vector.
  4590. */
  4591. setFromMatrixPosition( m ) {
  4592. const e = m.elements;
  4593. this.x = e[ 12 ];
  4594. this.y = e[ 13 ];
  4595. this.z = e[ 14 ];
  4596. return this;
  4597. }
  4598. /**
  4599. * Sets the vector components to the scale elements of the
  4600. * given transformation matrix.
  4601. *
  4602. * @param {Matrix4} m - The 4x4 matrix.
  4603. * @return {Vector3} A reference to this vector.
  4604. */
  4605. setFromMatrixScale( m ) {
  4606. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4607. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4608. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4609. this.x = sx;
  4610. this.y = sy;
  4611. this.z = sz;
  4612. return this;
  4613. }
  4614. /**
  4615. * Sets the vector components from the specified matrix column.
  4616. *
  4617. * @param {Matrix4} m - The 4x4 matrix.
  4618. * @param {number} index - The column index.
  4619. * @return {Vector3} A reference to this vector.
  4620. */
  4621. setFromMatrixColumn( m, index ) {
  4622. return this.fromArray( m.elements, index * 4 );
  4623. }
  4624. /**
  4625. * Sets the vector components from the specified matrix column.
  4626. *
  4627. * @param {Matrix3} m - The 3x3 matrix.
  4628. * @param {number} index - The column index.
  4629. * @return {Vector3} A reference to this vector.
  4630. */
  4631. setFromMatrix3Column( m, index ) {
  4632. return this.fromArray( m.elements, index * 3 );
  4633. }
  4634. /**
  4635. * Sets the vector components from the given Euler angles.
  4636. *
  4637. * @param {Euler} e - The Euler angles to set.
  4638. * @return {Vector3} A reference to this vector.
  4639. */
  4640. setFromEuler( e ) {
  4641. this.x = e._x;
  4642. this.y = e._y;
  4643. this.z = e._z;
  4644. return this;
  4645. }
  4646. /**
  4647. * Sets the vector components from the RGB components of the
  4648. * given color.
  4649. *
  4650. * @param {Color} c - The color to set.
  4651. * @return {Vector3} A reference to this vector.
  4652. */
  4653. setFromColor( c ) {
  4654. this.x = c.r;
  4655. this.y = c.g;
  4656. this.z = c.b;
  4657. return this;
  4658. }
  4659. /**
  4660. * Returns `true` if this vector is equal with the given one.
  4661. *
  4662. * @param {Vector3} v - The vector to test for equality.
  4663. * @return {boolean} Whether this vector is equal with the given one.
  4664. */
  4665. equals( v ) {
  4666. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4667. }
  4668. /**
  4669. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4670. * and z value to be `array[ offset + 2 ]`.
  4671. *
  4672. * @param {Array<number>} array - An array holding the vector component values.
  4673. * @param {number} [offset=0] - The offset into the array.
  4674. * @return {Vector3} A reference to this vector.
  4675. */
  4676. fromArray( array, offset = 0 ) {
  4677. this.x = array[ offset ];
  4678. this.y = array[ offset + 1 ];
  4679. this.z = array[ offset + 2 ];
  4680. return this;
  4681. }
  4682. /**
  4683. * Writes the components of this vector to the given array. If no array is provided,
  4684. * the method returns a new instance.
  4685. *
  4686. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4687. * @param {number} [offset=0] - Index of the first element in the array.
  4688. * @return {Array<number>} The vector components.
  4689. */
  4690. toArray( array = [], offset = 0 ) {
  4691. array[ offset ] = this.x;
  4692. array[ offset + 1 ] = this.y;
  4693. array[ offset + 2 ] = this.z;
  4694. return array;
  4695. }
  4696. /**
  4697. * Sets the components of this vector from the given buffer attribute.
  4698. *
  4699. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4700. * @param {number} index - The index into the attribute.
  4701. * @return {Vector3} A reference to this vector.
  4702. */
  4703. fromBufferAttribute( attribute, index ) {
  4704. this.x = attribute.getX( index );
  4705. this.y = attribute.getY( index );
  4706. this.z = attribute.getZ( index );
  4707. return this;
  4708. }
  4709. /**
  4710. * Sets each component of this vector to a pseudo-random value between `0` and
  4711. * `1`, excluding `1`.
  4712. *
  4713. * @return {Vector3} A reference to this vector.
  4714. */
  4715. random() {
  4716. this.x = Math.random();
  4717. this.y = Math.random();
  4718. this.z = Math.random();
  4719. return this;
  4720. }
  4721. /**
  4722. * Sets this vector to a uniformly random point on a unit sphere.
  4723. *
  4724. * @return {Vector3} A reference to this vector.
  4725. */
  4726. randomDirection() {
  4727. // https://mathworld.wolfram.com/SpherePointPicking.html
  4728. const theta = Math.random() * Math.PI * 2;
  4729. const u = Math.random() * 2 - 1;
  4730. const c = Math.sqrt( 1 - u * u );
  4731. this.x = c * Math.cos( theta );
  4732. this.y = u;
  4733. this.z = c * Math.sin( theta );
  4734. return this;
  4735. }
  4736. *[ Symbol.iterator ]() {
  4737. yield this.x;
  4738. yield this.y;
  4739. yield this.z;
  4740. }
  4741. }
  4742. const _vector$c = /*@__PURE__*/ new Vector3();
  4743. const _quaternion$5 = /*@__PURE__*/ new Quaternion();
  4744. /**
  4745. * Represents a 3x3 matrix.
  4746. *
  4747. * A Note on Row-Major and Column-Major Ordering:
  4748. *
  4749. * The constructor and {@link Matrix3#set} method take arguments in
  4750. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4751. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4752. * This means that calling:
  4753. * ```js
  4754. * const m = new THREE.Matrix();
  4755. * m.set( 11, 12, 13,
  4756. * 21, 22, 23,
  4757. * 31, 32, 33 );
  4758. * ```
  4759. * will result in the elements array containing:
  4760. * ```js
  4761. * m.elements = [ 11, 21, 31,
  4762. * 12, 22, 32,
  4763. * 13, 23, 33 ];
  4764. * ```
  4765. * and internally all calculations are performed using column-major ordering.
  4766. * However, as the actual ordering makes no difference mathematically and
  4767. * most people are used to thinking about matrices in row-major order, the
  4768. * three.js documentation shows matrices in row-major order. Just bear in
  4769. * mind that if you are reading the source code, you'll have to take the
  4770. * transpose of any matrices outlined here to make sense of the calculations.
  4771. */
  4772. class Matrix3 {
  4773. /**
  4774. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4775. * in row-major order. If no arguments are provided, the constructor
  4776. * initializes the matrix as an identity matrix.
  4777. *
  4778. * @param {number} [n11] - 1-1 matrix element.
  4779. * @param {number} [n12] - 1-2 matrix element.
  4780. * @param {number} [n13] - 1-3 matrix element.
  4781. * @param {number} [n21] - 2-1 matrix element.
  4782. * @param {number} [n22] - 2-2 matrix element.
  4783. * @param {number} [n23] - 2-3 matrix element.
  4784. * @param {number} [n31] - 3-1 matrix element.
  4785. * @param {number} [n32] - 3-2 matrix element.
  4786. * @param {number} [n33] - 3-3 matrix element.
  4787. */
  4788. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4789. /**
  4790. * This flag can be used for type testing.
  4791. *
  4792. * @type {boolean}
  4793. * @readonly
  4794. * @default true
  4795. */
  4796. Matrix3.prototype.isMatrix3 = true;
  4797. /**
  4798. * A column-major list of matrix values.
  4799. *
  4800. * @type {Array<number>}
  4801. */
  4802. this.elements = [
  4803. 1, 0, 0,
  4804. 0, 1, 0,
  4805. 0, 0, 1
  4806. ];
  4807. if ( n11 !== undefined ) {
  4808. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4809. }
  4810. }
  4811. /**
  4812. * Sets the elements of the matrix.The arguments are supposed to be
  4813. * in row-major order.
  4814. *
  4815. * @param {number} [n11] - 1-1 matrix element.
  4816. * @param {number} [n12] - 1-2 matrix element.
  4817. * @param {number} [n13] - 1-3 matrix element.
  4818. * @param {number} [n21] - 2-1 matrix element.
  4819. * @param {number} [n22] - 2-2 matrix element.
  4820. * @param {number} [n23] - 2-3 matrix element.
  4821. * @param {number} [n31] - 3-1 matrix element.
  4822. * @param {number} [n32] - 3-2 matrix element.
  4823. * @param {number} [n33] - 3-3 matrix element.
  4824. * @return {Matrix3} A reference to this matrix.
  4825. */
  4826. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4827. const te = this.elements;
  4828. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4829. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4830. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4831. return this;
  4832. }
  4833. /**
  4834. * Sets this matrix to the 3x3 identity matrix.
  4835. *
  4836. * @return {Matrix3} A reference to this matrix.
  4837. */
  4838. identity() {
  4839. this.set(
  4840. 1, 0, 0,
  4841. 0, 1, 0,
  4842. 0, 0, 1
  4843. );
  4844. return this;
  4845. }
  4846. /**
  4847. * Copies the values of the given matrix to this instance.
  4848. *
  4849. * @param {Matrix3} m - The matrix to copy.
  4850. * @return {Matrix3} A reference to this matrix.
  4851. */
  4852. copy( m ) {
  4853. const te = this.elements;
  4854. const me = m.elements;
  4855. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4856. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4857. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4858. return this;
  4859. }
  4860. /**
  4861. * Extracts the basis of this matrix into the three axis vectors provided.
  4862. *
  4863. * @param {Vector3} xAxis - The basis's x axis.
  4864. * @param {Vector3} yAxis - The basis's y axis.
  4865. * @param {Vector3} zAxis - The basis's z axis.
  4866. * @return {Matrix3} A reference to this matrix.
  4867. */
  4868. extractBasis( xAxis, yAxis, zAxis ) {
  4869. xAxis.setFromMatrix3Column( this, 0 );
  4870. yAxis.setFromMatrix3Column( this, 1 );
  4871. zAxis.setFromMatrix3Column( this, 2 );
  4872. return this;
  4873. }
  4874. /**
  4875. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4876. *
  4877. * @param {Matrix4} m - The 4x4 matrix.
  4878. * @return {Matrix3} A reference to this matrix.
  4879. */
  4880. setFromMatrix4( m ) {
  4881. const me = m.elements;
  4882. this.set(
  4883. me[ 0 ], me[ 4 ], me[ 8 ],
  4884. me[ 1 ], me[ 5 ], me[ 9 ],
  4885. me[ 2 ], me[ 6 ], me[ 10 ]
  4886. );
  4887. return this;
  4888. }
  4889. /**
  4890. * Post-multiplies this matrix by the given 3x3 matrix.
  4891. *
  4892. * @param {Matrix3} m - The matrix to multiply with.
  4893. * @return {Matrix3} A reference to this matrix.
  4894. */
  4895. multiply( m ) {
  4896. return this.multiplyMatrices( this, m );
  4897. }
  4898. /**
  4899. * Pre-multiplies this matrix by the given 3x3 matrix.
  4900. *
  4901. * @param {Matrix3} m - The matrix to multiply with.
  4902. * @return {Matrix3} A reference to this matrix.
  4903. */
  4904. premultiply( m ) {
  4905. return this.multiplyMatrices( m, this );
  4906. }
  4907. /**
  4908. * Multiples the given 3x3 matrices and stores the result
  4909. * in this matrix.
  4910. *
  4911. * @param {Matrix3} a - The first matrix.
  4912. * @param {Matrix3} b - The second matrix.
  4913. * @return {Matrix3} A reference to this matrix.
  4914. */
  4915. multiplyMatrices( a, b ) {
  4916. const ae = a.elements;
  4917. const be = b.elements;
  4918. const te = this.elements;
  4919. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4920. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4921. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4922. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4923. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4924. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4925. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4926. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4927. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4928. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4929. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4930. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4931. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4932. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4933. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4934. return this;
  4935. }
  4936. /**
  4937. * Multiplies every component of the matrix by the given scalar.
  4938. *
  4939. * @param {number} s - The scalar.
  4940. * @return {Matrix3} A reference to this matrix.
  4941. */
  4942. multiplyScalar( s ) {
  4943. const te = this.elements;
  4944. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4945. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4946. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4947. return this;
  4948. }
  4949. /**
  4950. * Computes and returns the determinant of this matrix.
  4951. *
  4952. * @return {number} The determinant.
  4953. */
  4954. determinant() {
  4955. const te = this.elements;
  4956. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4957. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4958. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4959. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4960. }
  4961. /**
  4962. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4963. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4964. * a zero matrix instead.
  4965. *
  4966. * @return {Matrix3} A reference to this matrix.
  4967. */
  4968. invert() {
  4969. const te = this.elements,
  4970. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4971. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4972. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4973. t11 = n33 * n22 - n32 * n23,
  4974. t12 = n32 * n13 - n33 * n12,
  4975. t13 = n23 * n12 - n22 * n13,
  4976. det = n11 * t11 + n21 * t12 + n31 * t13;
  4977. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4978. const detInv = 1 / det;
  4979. te[ 0 ] = t11 * detInv;
  4980. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4981. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4982. te[ 3 ] = t12 * detInv;
  4983. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4984. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4985. te[ 6 ] = t13 * detInv;
  4986. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4987. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4988. return this;
  4989. }
  4990. /**
  4991. * Transposes this matrix in place.
  4992. *
  4993. * @return {Matrix3} A reference to this matrix.
  4994. */
  4995. transpose() {
  4996. let tmp;
  4997. const m = this.elements;
  4998. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4999. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5000. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5001. return this;
  5002. }
  5003. /**
  5004. * Computes the normal matrix which is the inverse transpose of the upper
  5005. * left 3x3 portion of the given 4x4 matrix.
  5006. *
  5007. * @param {Matrix4} matrix4 - The 4x4 matrix.
  5008. * @return {Matrix3} A reference to this matrix.
  5009. */
  5010. getNormalMatrix( matrix4 ) {
  5011. return this.setFromMatrix4( matrix4 ).invert().transpose();
  5012. }
  5013. /**
  5014. * Transposes this matrix into the supplied array, and returns itself unchanged.
  5015. *
  5016. * @param {Array<number>} r - An array to store the transposed matrix elements.
  5017. * @return {Matrix3} A reference to this matrix.
  5018. */
  5019. transposeIntoArray( r ) {
  5020. const m = this.elements;
  5021. r[ 0 ] = m[ 0 ];
  5022. r[ 1 ] = m[ 3 ];
  5023. r[ 2 ] = m[ 6 ];
  5024. r[ 3 ] = m[ 1 ];
  5025. r[ 4 ] = m[ 4 ];
  5026. r[ 5 ] = m[ 7 ];
  5027. r[ 6 ] = m[ 2 ];
  5028. r[ 7 ] = m[ 5 ];
  5029. r[ 8 ] = m[ 8 ];
  5030. return this;
  5031. }
  5032. /**
  5033. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  5034. *
  5035. * @param {number} tx - Offset x.
  5036. * @param {number} ty - Offset y.
  5037. * @param {number} sx - Repeat x.
  5038. * @param {number} sy - Repeat y.
  5039. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  5040. * @param {number} cx - Center x of rotation.
  5041. * @param {number} cy - Center y of rotation
  5042. * @return {Matrix3} A reference to this matrix.
  5043. */
  5044. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  5045. const c = Math.cos( rotation );
  5046. const s = Math.sin( rotation );
  5047. this.set(
  5048. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  5049. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  5050. 0, 0, 1
  5051. );
  5052. return this;
  5053. }
  5054. /**
  5055. * Scales this matrix with the given scalar values.
  5056. *
  5057. * @param {number} sx - The amount to scale in the X axis.
  5058. * @param {number} sy - The amount to scale in the Y axis.
  5059. * @return {Matrix3} A reference to this matrix.
  5060. */
  5061. scale( sx, sy ) {
  5062. this.premultiply( _m3.makeScale( sx, sy ) );
  5063. return this;
  5064. }
  5065. /**
  5066. * Rotates this matrix by the given angle.
  5067. *
  5068. * @param {number} theta - The rotation in radians.
  5069. * @return {Matrix3} A reference to this matrix.
  5070. */
  5071. rotate( theta ) {
  5072. this.premultiply( _m3.makeRotation( - theta ) );
  5073. return this;
  5074. }
  5075. /**
  5076. * Translates this matrix by the given scalar values.
  5077. *
  5078. * @param {number} tx - The amount to translate in the X axis.
  5079. * @param {number} ty - The amount to translate in the Y axis.
  5080. * @return {Matrix3} A reference to this matrix.
  5081. */
  5082. translate( tx, ty ) {
  5083. this.premultiply( _m3.makeTranslation( tx, ty ) );
  5084. return this;
  5085. }
  5086. // for 2D Transforms
  5087. /**
  5088. * Sets this matrix as a 2D translation transform.
  5089. *
  5090. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  5091. * @param {number} y - The amount to translate in the Y axis.
  5092. * @return {Matrix3} A reference to this matrix.
  5093. */
  5094. makeTranslation( x, y ) {
  5095. if ( x.isVector2 ) {
  5096. this.set(
  5097. 1, 0, x.x,
  5098. 0, 1, x.y,
  5099. 0, 0, 1
  5100. );
  5101. } else {
  5102. this.set(
  5103. 1, 0, x,
  5104. 0, 1, y,
  5105. 0, 0, 1
  5106. );
  5107. }
  5108. return this;
  5109. }
  5110. /**
  5111. * Sets this matrix as a 2D rotational transformation.
  5112. *
  5113. * @param {number} theta - The rotation in radians.
  5114. * @return {Matrix3} A reference to this matrix.
  5115. */
  5116. makeRotation( theta ) {
  5117. // counterclockwise
  5118. const c = Math.cos( theta );
  5119. const s = Math.sin( theta );
  5120. this.set(
  5121. c, - s, 0,
  5122. s, c, 0,
  5123. 0, 0, 1
  5124. );
  5125. return this;
  5126. }
  5127. /**
  5128. * Sets this matrix as a 2D scale transform.
  5129. *
  5130. * @param {number} x - The amount to scale in the X axis.
  5131. * @param {number} y - The amount to scale in the Y axis.
  5132. * @return {Matrix3} A reference to this matrix.
  5133. */
  5134. makeScale( x, y ) {
  5135. this.set(
  5136. x, 0, 0,
  5137. 0, y, 0,
  5138. 0, 0, 1
  5139. );
  5140. return this;
  5141. }
  5142. /**
  5143. * Returns `true` if this matrix is equal with the given one.
  5144. *
  5145. * @param {Matrix3} matrix - The matrix to test for equality.
  5146. * @return {boolean} Whether this matrix is equal with the given one.
  5147. */
  5148. equals( matrix ) {
  5149. const te = this.elements;
  5150. const me = matrix.elements;
  5151. for ( let i = 0; i < 9; i ++ ) {
  5152. if ( te[ i ] !== me[ i ] ) return false;
  5153. }
  5154. return true;
  5155. }
  5156. /**
  5157. * Sets the elements of the matrix from the given array.
  5158. *
  5159. * @param {Array<number>} array - The matrix elements in column-major order.
  5160. * @param {number} [offset=0] - Index of the first element in the array.
  5161. * @return {Matrix3} A reference to this matrix.
  5162. */
  5163. fromArray( array, offset = 0 ) {
  5164. for ( let i = 0; i < 9; i ++ ) {
  5165. this.elements[ i ] = array[ i + offset ];
  5166. }
  5167. return this;
  5168. }
  5169. /**
  5170. * Writes the elements of this matrix to the given array. If no array is provided,
  5171. * the method returns a new instance.
  5172. *
  5173. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  5174. * @param {number} [offset=0] - Index of the first element in the array.
  5175. * @return {Array<number>} The matrix elements in column-major order.
  5176. */
  5177. toArray( array = [], offset = 0 ) {
  5178. const te = this.elements;
  5179. array[ offset ] = te[ 0 ];
  5180. array[ offset + 1 ] = te[ 1 ];
  5181. array[ offset + 2 ] = te[ 2 ];
  5182. array[ offset + 3 ] = te[ 3 ];
  5183. array[ offset + 4 ] = te[ 4 ];
  5184. array[ offset + 5 ] = te[ 5 ];
  5185. array[ offset + 6 ] = te[ 6 ];
  5186. array[ offset + 7 ] = te[ 7 ];
  5187. array[ offset + 8 ] = te[ 8 ];
  5188. return array;
  5189. }
  5190. /**
  5191. * Returns a matrix with copied values from this instance.
  5192. *
  5193. * @return {Matrix3} A clone of this instance.
  5194. */
  5195. clone() {
  5196. return new this.constructor().fromArray( this.elements );
  5197. }
  5198. }
  5199. const _m3 = /*@__PURE__*/ new Matrix3();
  5200. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5201. 0.4123908, 0.3575843, 0.1804808,
  5202. 0.2126390, 0.7151687, 0.0721923,
  5203. 0.0193308, 0.1191948, 0.9505322
  5204. );
  5205. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5206. 3.2409699, -1.5373832, -0.4986108,
  5207. -0.9692436, 1.8759675, 0.0415551,
  5208. 0.0556301, -0.203977, 1.0569715
  5209. );
  5210. function createColorManagement() {
  5211. const ColorManagement = {
  5212. enabled: true,
  5213. workingColorSpace: LinearSRGBColorSpace,
  5214. /**
  5215. * Implementations of supported color spaces.
  5216. *
  5217. * Required:
  5218. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5219. * - whitePoint: reference white [ x y ]
  5220. * - transfer: transfer function (pre-defined)
  5221. * - toXYZ: Matrix3 RGB to XYZ transform
  5222. * - fromXYZ: Matrix3 XYZ to RGB transform
  5223. * - luminanceCoefficients: RGB luminance coefficients
  5224. *
  5225. * Optional:
  5226. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5227. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5228. *
  5229. * Reference:
  5230. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5231. */
  5232. spaces: {},
  5233. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5234. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5235. return color;
  5236. }
  5237. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5238. color.r = SRGBToLinear( color.r );
  5239. color.g = SRGBToLinear( color.g );
  5240. color.b = SRGBToLinear( color.b );
  5241. }
  5242. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5243. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5244. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5245. }
  5246. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5247. color.r = LinearToSRGB( color.r );
  5248. color.g = LinearToSRGB( color.g );
  5249. color.b = LinearToSRGB( color.b );
  5250. }
  5251. return color;
  5252. },
  5253. workingToColorSpace: function ( color, targetColorSpace ) {
  5254. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5255. },
  5256. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5257. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5258. },
  5259. getPrimaries: function ( colorSpace ) {
  5260. return this.spaces[ colorSpace ].primaries;
  5261. },
  5262. getTransfer: function ( colorSpace ) {
  5263. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5264. return this.spaces[ colorSpace ].transfer;
  5265. },
  5266. getToneMappingMode: function ( colorSpace ) {
  5267. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5268. },
  5269. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5270. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5271. },
  5272. define: function ( colorSpaces ) {
  5273. Object.assign( this.spaces, colorSpaces );
  5274. },
  5275. // Internal APIs
  5276. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5277. return targetMatrix
  5278. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5279. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5280. },
  5281. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5282. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5283. },
  5284. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5285. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5286. },
  5287. // Deprecated
  5288. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5289. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5290. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5291. },
  5292. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5293. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5294. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5295. },
  5296. };
  5297. /******************************************************************************
  5298. * sRGB definitions
  5299. */
  5300. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5301. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5302. const D65 = [ 0.3127, 0.3290 ];
  5303. ColorManagement.define( {
  5304. [ LinearSRGBColorSpace ]: {
  5305. primaries: REC709_PRIMARIES,
  5306. whitePoint: D65,
  5307. transfer: LinearTransfer,
  5308. toXYZ: LINEAR_REC709_TO_XYZ,
  5309. fromXYZ: XYZ_TO_LINEAR_REC709,
  5310. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5311. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5312. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5313. },
  5314. [ SRGBColorSpace ]: {
  5315. primaries: REC709_PRIMARIES,
  5316. whitePoint: D65,
  5317. transfer: SRGBTransfer,
  5318. toXYZ: LINEAR_REC709_TO_XYZ,
  5319. fromXYZ: XYZ_TO_LINEAR_REC709,
  5320. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5321. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5322. },
  5323. } );
  5324. return ColorManagement;
  5325. }
  5326. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5327. function SRGBToLinear( c ) {
  5328. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5329. }
  5330. function LinearToSRGB( c ) {
  5331. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5332. }
  5333. let _canvas;
  5334. /**
  5335. * A class containing utility functions for images.
  5336. *
  5337. * @hideconstructor
  5338. */
  5339. class ImageUtils {
  5340. /**
  5341. * Returns a data URI containing a representation of the given image.
  5342. *
  5343. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5344. * @param {string} [type='image/png'] - Indicates the image format.
  5345. * @return {string} The data URI.
  5346. */
  5347. static getDataURL( image, type = 'image/png' ) {
  5348. if ( /^data:/i.test( image.src ) ) {
  5349. return image.src;
  5350. }
  5351. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5352. return image.src;
  5353. }
  5354. let canvas;
  5355. if ( image instanceof HTMLCanvasElement ) {
  5356. canvas = image;
  5357. } else {
  5358. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5359. _canvas.width = image.width;
  5360. _canvas.height = image.height;
  5361. const context = _canvas.getContext( '2d' );
  5362. if ( image instanceof ImageData ) {
  5363. context.putImageData( image, 0, 0 );
  5364. } else {
  5365. context.drawImage( image, 0, 0, image.width, image.height );
  5366. }
  5367. canvas = _canvas;
  5368. }
  5369. return canvas.toDataURL( type );
  5370. }
  5371. /**
  5372. * Converts the given sRGB image data to linear color space.
  5373. *
  5374. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5375. * @return {HTMLCanvasElement|Object} The converted image.
  5376. */
  5377. static sRGBToLinear( image ) {
  5378. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5379. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5380. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5381. const canvas = createElementNS( 'canvas' );
  5382. canvas.width = image.width;
  5383. canvas.height = image.height;
  5384. const context = canvas.getContext( '2d' );
  5385. context.drawImage( image, 0, 0, image.width, image.height );
  5386. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5387. const data = imageData.data;
  5388. for ( let i = 0; i < data.length; i ++ ) {
  5389. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5390. }
  5391. context.putImageData( imageData, 0, 0 );
  5392. return canvas;
  5393. } else if ( image.data ) {
  5394. const data = image.data.slice( 0 );
  5395. for ( let i = 0; i < data.length; i ++ ) {
  5396. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5397. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5398. } else {
  5399. // assuming float
  5400. data[ i ] = SRGBToLinear( data[ i ] );
  5401. }
  5402. }
  5403. return {
  5404. data: data,
  5405. width: image.width,
  5406. height: image.height
  5407. };
  5408. } else {
  5409. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5410. return image;
  5411. }
  5412. }
  5413. }
  5414. let _sourceId = 0;
  5415. /**
  5416. * Represents the data source of a texture.
  5417. *
  5418. * The main purpose of this class is to decouple the data definition from the texture
  5419. * definition so the same data can be used with multiple texture instances.
  5420. */
  5421. class Source {
  5422. /**
  5423. * Constructs a new video texture.
  5424. *
  5425. * @param {any} [data=null] - The data definition of a texture.
  5426. */
  5427. constructor( data = null ) {
  5428. /**
  5429. * This flag can be used for type testing.
  5430. *
  5431. * @type {boolean}
  5432. * @readonly
  5433. * @default true
  5434. */
  5435. this.isSource = true;
  5436. /**
  5437. * The ID of the source.
  5438. *
  5439. * @name Source#id
  5440. * @type {number}
  5441. * @readonly
  5442. */
  5443. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5444. /**
  5445. * The UUID of the source.
  5446. *
  5447. * @type {string}
  5448. * @readonly
  5449. */
  5450. this.uuid = generateUUID();
  5451. /**
  5452. * The data definition of a texture.
  5453. *
  5454. * @type {any}
  5455. */
  5456. this.data = data;
  5457. /**
  5458. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5459. * provides more control on how texture data should be processed. When `dataReady` is set
  5460. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5461. * the data into the GPU memory.
  5462. *
  5463. * @type {boolean}
  5464. * @default true
  5465. */
  5466. this.dataReady = true;
  5467. /**
  5468. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5469. *
  5470. * @type {number}
  5471. * @readonly
  5472. * @default 0
  5473. */
  5474. this.version = 0;
  5475. }
  5476. /**
  5477. * Returns the dimensions of the source into the given target vector.
  5478. *
  5479. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5480. * @return {(Vector2|Vector3)} The dimensions of the source.
  5481. */
  5482. getSize( target ) {
  5483. const data = this.data;
  5484. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5485. target.set( data.videoWidth, data.videoHeight, 0 );
  5486. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5487. target.set( data.displayHeight, data.displayWidth, 0 );
  5488. } else if ( data !== null ) {
  5489. target.set( data.width, data.height, data.depth || 0 );
  5490. } else {
  5491. target.set( 0, 0, 0 );
  5492. }
  5493. return target;
  5494. }
  5495. /**
  5496. * When the property is set to `true`, the engine allocates the memory
  5497. * for the texture (if necessary) and triggers the actual texture upload
  5498. * to the GPU next time the source is used.
  5499. *
  5500. * @type {boolean}
  5501. * @default false
  5502. * @param {boolean} value
  5503. */
  5504. set needsUpdate( value ) {
  5505. if ( value === true ) this.version ++;
  5506. }
  5507. /**
  5508. * Serializes the source into JSON.
  5509. *
  5510. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5511. * @return {Object} A JSON object representing the serialized source.
  5512. * @see {@link ObjectLoader#parse}
  5513. */
  5514. toJSON( meta ) {
  5515. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5516. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5517. return meta.images[ this.uuid ];
  5518. }
  5519. const output = {
  5520. uuid: this.uuid,
  5521. url: ''
  5522. };
  5523. const data = this.data;
  5524. if ( data !== null ) {
  5525. let url;
  5526. if ( Array.isArray( data ) ) {
  5527. // cube texture
  5528. url = [];
  5529. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5530. if ( data[ i ].isDataTexture ) {
  5531. url.push( serializeImage( data[ i ].image ) );
  5532. } else {
  5533. url.push( serializeImage( data[ i ] ) );
  5534. }
  5535. }
  5536. } else {
  5537. // texture
  5538. url = serializeImage( data );
  5539. }
  5540. output.url = url;
  5541. }
  5542. if ( ! isRootObject ) {
  5543. meta.images[ this.uuid ] = output;
  5544. }
  5545. return output;
  5546. }
  5547. }
  5548. function serializeImage( image ) {
  5549. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5550. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5551. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5552. // default images
  5553. return ImageUtils.getDataURL( image );
  5554. } else {
  5555. if ( image.data ) {
  5556. // images of DataTexture
  5557. return {
  5558. data: Array.from( image.data ),
  5559. width: image.width,
  5560. height: image.height,
  5561. type: image.data.constructor.name
  5562. };
  5563. } else {
  5564. warn( 'Texture: Unable to serialize Texture.' );
  5565. return {};
  5566. }
  5567. }
  5568. }
  5569. let _textureId = 0;
  5570. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5571. /**
  5572. * Base class for all textures.
  5573. *
  5574. * Note: After the initial use of a texture, its dimensions, format, and type
  5575. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5576. *
  5577. * @augments EventDispatcher
  5578. */
  5579. class Texture extends EventDispatcher {
  5580. /**
  5581. * Constructs a new texture.
  5582. *
  5583. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5584. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5585. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5586. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5587. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5588. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5589. * @param {number} [format=RGBAFormat] - The texture format.
  5590. * @param {number} [type=UnsignedByteType] - The texture type.
  5591. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5592. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5593. */
  5594. 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 ) {
  5595. super();
  5596. /**
  5597. * This flag can be used for type testing.
  5598. *
  5599. * @type {boolean}
  5600. * @readonly
  5601. * @default true
  5602. */
  5603. this.isTexture = true;
  5604. /**
  5605. * The ID of the texture.
  5606. *
  5607. * @name Texture#id
  5608. * @type {number}
  5609. * @readonly
  5610. */
  5611. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5612. /**
  5613. * The UUID of the texture.
  5614. *
  5615. * @type {string}
  5616. * @readonly
  5617. */
  5618. this.uuid = generateUUID();
  5619. /**
  5620. * The name of the texture.
  5621. *
  5622. * @type {string}
  5623. */
  5624. this.name = '';
  5625. /**
  5626. * The data definition of a texture. A reference to the data source can be
  5627. * shared across textures. This is often useful in context of spritesheets
  5628. * where multiple textures render the same data but with different texture
  5629. * transformations.
  5630. *
  5631. * @type {Source}
  5632. */
  5633. this.source = new Source( image );
  5634. /**
  5635. * An array holding user-defined mipmaps.
  5636. *
  5637. * @type {Array<Object>}
  5638. */
  5639. this.mipmaps = [];
  5640. /**
  5641. * How the texture is applied to the object. The value `UVMapping`
  5642. * is the default, where texture or uv coordinates are used to apply the map.
  5643. *
  5644. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5645. * @default UVMapping
  5646. */
  5647. this.mapping = mapping;
  5648. /**
  5649. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5650. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5651. *
  5652. * @type {number}
  5653. * @default 0
  5654. */
  5655. this.channel = 0;
  5656. /**
  5657. * This defines how the texture is wrapped horizontally and corresponds to
  5658. * *U* in UV mapping.
  5659. *
  5660. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5661. * @default ClampToEdgeWrapping
  5662. */
  5663. this.wrapS = wrapS;
  5664. /**
  5665. * This defines how the texture is wrapped horizontally and corresponds to
  5666. * *V* in UV mapping.
  5667. *
  5668. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5669. * @default ClampToEdgeWrapping
  5670. */
  5671. this.wrapT = wrapT;
  5672. /**
  5673. * How the texture is sampled when a texel covers more than one pixel.
  5674. *
  5675. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5676. * @default LinearFilter
  5677. */
  5678. this.magFilter = magFilter;
  5679. /**
  5680. * How the texture is sampled when a texel covers less than one pixel.
  5681. *
  5682. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5683. * @default LinearMipmapLinearFilter
  5684. */
  5685. this.minFilter = minFilter;
  5686. /**
  5687. * The number of samples taken along the axis through the pixel that has the
  5688. * highest density of texels. By default, this value is `1`. A higher value
  5689. * gives a less blurry result than a basic mipmap, at the cost of more
  5690. * texture samples being used.
  5691. *
  5692. * @type {number}
  5693. * @default Texture.DEFAULT_ANISOTROPY
  5694. */
  5695. this.anisotropy = anisotropy;
  5696. /**
  5697. * The format of the texture.
  5698. *
  5699. * @type {number}
  5700. * @default RGBAFormat
  5701. */
  5702. this.format = format;
  5703. /**
  5704. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5705. * defines how the texture data is going to be stored on the GPU.
  5706. *
  5707. * This property allows to overwrite the default format.
  5708. *
  5709. * @type {?string}
  5710. * @default null
  5711. */
  5712. this.internalFormat = null;
  5713. /**
  5714. * The data type of the texture.
  5715. *
  5716. * @type {number}
  5717. * @default UnsignedByteType
  5718. */
  5719. this.type = type;
  5720. /**
  5721. * How much a single repetition of the texture is offset from the beginning,
  5722. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5723. *
  5724. * @type {Vector2}
  5725. * @default (0,0)
  5726. */
  5727. this.offset = new Vector2( 0, 0 );
  5728. /**
  5729. * How many times the texture is repeated across the surface, in each
  5730. * direction U and V. If repeat is set greater than `1` in either direction,
  5731. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5732. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5733. *
  5734. * @type {Vector2}
  5735. * @default (1,1)
  5736. */
  5737. this.repeat = new Vector2( 1, 1 );
  5738. /**
  5739. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5740. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5741. *
  5742. * @type {Vector2}
  5743. * @default (0,0)
  5744. */
  5745. this.center = new Vector2( 0, 0 );
  5746. /**
  5747. * How much the texture is rotated around the center point, in radians.
  5748. * Positive values are counter-clockwise.
  5749. *
  5750. * @type {number}
  5751. * @default 0
  5752. */
  5753. this.rotation = 0;
  5754. /**
  5755. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5756. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5757. * {@link Texture#rotation}, and {@link Texture#center}.
  5758. *
  5759. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5760. *
  5761. * @type {boolean}
  5762. * @default true
  5763. */
  5764. this.matrixAutoUpdate = true;
  5765. /**
  5766. * The uv-transformation matrix of the texture.
  5767. *
  5768. * @type {Matrix3}
  5769. */
  5770. this.matrix = new Matrix3();
  5771. /**
  5772. * Whether to generate mipmaps (if possible) for a texture.
  5773. *
  5774. * Set this to `false` if you are creating mipmaps manually.
  5775. *
  5776. * @type {boolean}
  5777. * @default true
  5778. */
  5779. this.generateMipmaps = true;
  5780. /**
  5781. * If set to `true`, the alpha channel, if present, is multiplied into the
  5782. * color channels when the texture is uploaded to the GPU.
  5783. *
  5784. * Note that this property has no effect when using `ImageBitmap`. You need to
  5785. * configure premultiply alpha on bitmap creation instead.
  5786. *
  5787. * @type {boolean}
  5788. * @default false
  5789. */
  5790. this.premultiplyAlpha = false;
  5791. /**
  5792. * If set to `true`, the texture is flipped along the vertical axis when
  5793. * uploaded to the GPU.
  5794. *
  5795. * Note that this property has no effect when using `ImageBitmap`. You need to
  5796. * configure the flip on bitmap creation instead.
  5797. *
  5798. * @type {boolean}
  5799. * @default true
  5800. */
  5801. this.flipY = true;
  5802. /**
  5803. * Specifies the alignment requirements for the start of each pixel row in memory.
  5804. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5805. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5806. *
  5807. * @type {number}
  5808. * @default 4
  5809. */
  5810. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5811. /**
  5812. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5813. *
  5814. * @type {string}
  5815. * @default NoColorSpace
  5816. */
  5817. this.colorSpace = colorSpace;
  5818. /**
  5819. * An object that can be used to store custom data about the texture. It
  5820. * should not hold references to functions as these will not be cloned.
  5821. *
  5822. * @type {Object}
  5823. */
  5824. this.userData = {};
  5825. /**
  5826. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5827. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5828. *
  5829. * @type {Array<Object>}
  5830. */
  5831. this.updateRanges = [];
  5832. /**
  5833. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5834. *
  5835. * @type {number}
  5836. * @readonly
  5837. * @default 0
  5838. */
  5839. this.version = 0;
  5840. /**
  5841. * A callback function, called when the texture is updated (e.g., when
  5842. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5843. *
  5844. * @type {?Function}
  5845. * @default null
  5846. */
  5847. this.onUpdate = null;
  5848. /**
  5849. * An optional back reference to the textures render target.
  5850. *
  5851. * @type {?(RenderTarget|WebGLRenderTarget)}
  5852. * @default null
  5853. */
  5854. this.renderTarget = null;
  5855. /**
  5856. * Indicates whether a texture belongs to a render target or not.
  5857. *
  5858. * @type {boolean}
  5859. * @readonly
  5860. * @default false
  5861. */
  5862. this.isRenderTargetTexture = false;
  5863. /**
  5864. * Indicates if a texture should be handled like a texture array.
  5865. *
  5866. * @type {boolean}
  5867. * @readonly
  5868. * @default false
  5869. */
  5870. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5871. /**
  5872. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5873. * (only relevant for render target textures).
  5874. *
  5875. * @type {number}
  5876. * @readonly
  5877. * @default 0
  5878. */
  5879. this.pmremVersion = 0;
  5880. }
  5881. /**
  5882. * The width of the texture in pixels.
  5883. */
  5884. get width() {
  5885. return this.source.getSize( _tempVec3 ).x;
  5886. }
  5887. /**
  5888. * The height of the texture in pixels.
  5889. */
  5890. get height() {
  5891. return this.source.getSize( _tempVec3 ).y;
  5892. }
  5893. /**
  5894. * The depth of the texture in pixels.
  5895. */
  5896. get depth() {
  5897. return this.source.getSize( _tempVec3 ).z;
  5898. }
  5899. /**
  5900. * The image object holding the texture data.
  5901. *
  5902. * @type {?Object}
  5903. */
  5904. get image() {
  5905. return this.source.data;
  5906. }
  5907. set image( value = null ) {
  5908. this.source.data = value;
  5909. }
  5910. /**
  5911. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5912. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5913. */
  5914. updateMatrix() {
  5915. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5916. }
  5917. /**
  5918. * Adds a range of data in the data texture to be updated on the GPU.
  5919. *
  5920. * @param {number} start - Position at which to start update.
  5921. * @param {number} count - The number of components to update.
  5922. */
  5923. addUpdateRange( start, count ) {
  5924. this.updateRanges.push( { start, count } );
  5925. }
  5926. /**
  5927. * Clears the update ranges.
  5928. */
  5929. clearUpdateRanges() {
  5930. this.updateRanges.length = 0;
  5931. }
  5932. /**
  5933. * Returns a new texture with copied values from this instance.
  5934. *
  5935. * @return {Texture} A clone of this instance.
  5936. */
  5937. clone() {
  5938. return new this.constructor().copy( this );
  5939. }
  5940. /**
  5941. * Copies the values of the given texture to this instance.
  5942. *
  5943. * @param {Texture} source - The texture to copy.
  5944. * @return {Texture} A reference to this instance.
  5945. */
  5946. copy( source ) {
  5947. this.name = source.name;
  5948. this.source = source.source;
  5949. this.mipmaps = source.mipmaps.slice( 0 );
  5950. this.mapping = source.mapping;
  5951. this.channel = source.channel;
  5952. this.wrapS = source.wrapS;
  5953. this.wrapT = source.wrapT;
  5954. this.magFilter = source.magFilter;
  5955. this.minFilter = source.minFilter;
  5956. this.anisotropy = source.anisotropy;
  5957. this.format = source.format;
  5958. this.internalFormat = source.internalFormat;
  5959. this.type = source.type;
  5960. this.offset.copy( source.offset );
  5961. this.repeat.copy( source.repeat );
  5962. this.center.copy( source.center );
  5963. this.rotation = source.rotation;
  5964. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5965. this.matrix.copy( source.matrix );
  5966. this.generateMipmaps = source.generateMipmaps;
  5967. this.premultiplyAlpha = source.premultiplyAlpha;
  5968. this.flipY = source.flipY;
  5969. this.unpackAlignment = source.unpackAlignment;
  5970. this.colorSpace = source.colorSpace;
  5971. this.renderTarget = source.renderTarget;
  5972. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5973. this.isArrayTexture = source.isArrayTexture;
  5974. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5975. this.needsUpdate = true;
  5976. return this;
  5977. }
  5978. /**
  5979. * Sets this texture's properties based on `values`.
  5980. * @param {Object} values - A container with texture parameters.
  5981. */
  5982. setValues( values ) {
  5983. for ( const key in values ) {
  5984. const newValue = values[ key ];
  5985. if ( newValue === undefined ) {
  5986. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5987. continue;
  5988. }
  5989. const currentValue = this[ key ];
  5990. if ( currentValue === undefined ) {
  5991. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  5992. continue;
  5993. }
  5994. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5995. currentValue.copy( newValue );
  5996. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5997. currentValue.copy( newValue );
  5998. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5999. currentValue.copy( newValue );
  6000. } else {
  6001. this[ key ] = newValue;
  6002. }
  6003. }
  6004. }
  6005. /**
  6006. * Serializes the texture into JSON.
  6007. *
  6008. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  6009. * @return {Object} A JSON object representing the serialized texture.
  6010. * @see {@link ObjectLoader#parse}
  6011. */
  6012. toJSON( meta ) {
  6013. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  6014. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  6015. return meta.textures[ this.uuid ];
  6016. }
  6017. const output = {
  6018. metadata: {
  6019. version: 4.7,
  6020. type: 'Texture',
  6021. generator: 'Texture.toJSON'
  6022. },
  6023. uuid: this.uuid,
  6024. name: this.name,
  6025. image: this.source.toJSON( meta ).uuid,
  6026. mapping: this.mapping,
  6027. channel: this.channel,
  6028. repeat: [ this.repeat.x, this.repeat.y ],
  6029. offset: [ this.offset.x, this.offset.y ],
  6030. center: [ this.center.x, this.center.y ],
  6031. rotation: this.rotation,
  6032. wrap: [ this.wrapS, this.wrapT ],
  6033. format: this.format,
  6034. internalFormat: this.internalFormat,
  6035. type: this.type,
  6036. colorSpace: this.colorSpace,
  6037. minFilter: this.minFilter,
  6038. magFilter: this.magFilter,
  6039. anisotropy: this.anisotropy,
  6040. flipY: this.flipY,
  6041. generateMipmaps: this.generateMipmaps,
  6042. premultiplyAlpha: this.premultiplyAlpha,
  6043. unpackAlignment: this.unpackAlignment
  6044. };
  6045. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  6046. if ( ! isRootObject ) {
  6047. meta.textures[ this.uuid ] = output;
  6048. }
  6049. return output;
  6050. }
  6051. /**
  6052. * Frees the GPU-related resources allocated by this instance. Call this
  6053. * method whenever this instance is no longer used in your app.
  6054. *
  6055. * @fires Texture#dispose
  6056. */
  6057. dispose() {
  6058. /**
  6059. * Fires when the texture has been disposed of.
  6060. *
  6061. * @event Texture#dispose
  6062. * @type {Object}
  6063. */
  6064. this.dispatchEvent( { type: 'dispose' } );
  6065. }
  6066. /**
  6067. * Transforms the given uv vector with the textures uv transformation matrix.
  6068. *
  6069. * @param {Vector2} uv - The uv vector.
  6070. * @return {Vector2} The transformed uv vector.
  6071. */
  6072. transformUv( uv ) {
  6073. if ( this.mapping !== UVMapping ) return uv;
  6074. uv.applyMatrix3( this.matrix );
  6075. if ( uv.x < 0 || uv.x > 1 ) {
  6076. switch ( this.wrapS ) {
  6077. case RepeatWrapping:
  6078. uv.x = uv.x - Math.floor( uv.x );
  6079. break;
  6080. case ClampToEdgeWrapping:
  6081. uv.x = uv.x < 0 ? 0 : 1;
  6082. break;
  6083. case MirroredRepeatWrapping:
  6084. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6085. uv.x = Math.ceil( uv.x ) - uv.x;
  6086. } else {
  6087. uv.x = uv.x - Math.floor( uv.x );
  6088. }
  6089. break;
  6090. }
  6091. }
  6092. if ( uv.y < 0 || uv.y > 1 ) {
  6093. switch ( this.wrapT ) {
  6094. case RepeatWrapping:
  6095. uv.y = uv.y - Math.floor( uv.y );
  6096. break;
  6097. case ClampToEdgeWrapping:
  6098. uv.y = uv.y < 0 ? 0 : 1;
  6099. break;
  6100. case MirroredRepeatWrapping:
  6101. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6102. uv.y = Math.ceil( uv.y ) - uv.y;
  6103. } else {
  6104. uv.y = uv.y - Math.floor( uv.y );
  6105. }
  6106. break;
  6107. }
  6108. }
  6109. if ( this.flipY ) {
  6110. uv.y = 1 - uv.y;
  6111. }
  6112. return uv;
  6113. }
  6114. /**
  6115. * Setting this property to `true` indicates the engine the texture
  6116. * must be updated in the next render. This triggers a texture upload
  6117. * to the GPU and ensures correct texture parameter configuration.
  6118. *
  6119. * @type {boolean}
  6120. * @default false
  6121. * @param {boolean} value
  6122. */
  6123. set needsUpdate( value ) {
  6124. if ( value === true ) {
  6125. this.version ++;
  6126. this.source.needsUpdate = true;
  6127. }
  6128. }
  6129. /**
  6130. * Setting this property to `true` indicates the engine the PMREM
  6131. * must be regenerated.
  6132. *
  6133. * @type {boolean}
  6134. * @default false
  6135. * @param {boolean} value
  6136. */
  6137. set needsPMREMUpdate( value ) {
  6138. if ( value === true ) {
  6139. this.pmremVersion ++;
  6140. }
  6141. }
  6142. }
  6143. /**
  6144. * The default image for all textures.
  6145. *
  6146. * @static
  6147. * @type {?Image}
  6148. * @default null
  6149. */
  6150. Texture.DEFAULT_IMAGE = null;
  6151. /**
  6152. * The default mapping for all textures.
  6153. *
  6154. * @static
  6155. * @type {number}
  6156. * @default UVMapping
  6157. */
  6158. Texture.DEFAULT_MAPPING = UVMapping;
  6159. /**
  6160. * The default anisotropy value for all textures.
  6161. *
  6162. * @static
  6163. * @type {number}
  6164. * @default 1
  6165. */
  6166. Texture.DEFAULT_ANISOTROPY = 1;
  6167. /**
  6168. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  6169. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  6170. *
  6171. * - A point in 4D space.
  6172. * - A direction and length in 4D space. In three.js the length will
  6173. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  6174. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  6175. * - Any arbitrary ordered quadruplet of numbers.
  6176. *
  6177. * There are other things a 4D vector can be used to represent, however these
  6178. * are the most common uses in *three.js*.
  6179. *
  6180. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6181. * the corresponding order.
  6182. * ```js
  6183. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6184. *
  6185. * //no arguments; will be initialised to (0, 0, 0, 1)
  6186. * const b = new THREE.Vector4( );
  6187. *
  6188. * const d = a.dot( b );
  6189. * ```
  6190. */
  6191. class Vector4 {
  6192. /**
  6193. * Constructs a new 4D vector.
  6194. *
  6195. * @param {number} [x=0] - The x value of this vector.
  6196. * @param {number} [y=0] - The y value of this vector.
  6197. * @param {number} [z=0] - The z value of this vector.
  6198. * @param {number} [w=1] - The w value of this vector.
  6199. */
  6200. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6201. /**
  6202. * This flag can be used for type testing.
  6203. *
  6204. * @type {boolean}
  6205. * @readonly
  6206. * @default true
  6207. */
  6208. Vector4.prototype.isVector4 = true;
  6209. /**
  6210. * The x value of this vector.
  6211. *
  6212. * @type {number}
  6213. */
  6214. this.x = x;
  6215. /**
  6216. * The y value of this vector.
  6217. *
  6218. * @type {number}
  6219. */
  6220. this.y = y;
  6221. /**
  6222. * The z value of this vector.
  6223. *
  6224. * @type {number}
  6225. */
  6226. this.z = z;
  6227. /**
  6228. * The w value of this vector.
  6229. *
  6230. * @type {number}
  6231. */
  6232. this.w = w;
  6233. }
  6234. /**
  6235. * Alias for {@link Vector4#z}.
  6236. *
  6237. * @type {number}
  6238. */
  6239. get width() {
  6240. return this.z;
  6241. }
  6242. set width( value ) {
  6243. this.z = value;
  6244. }
  6245. /**
  6246. * Alias for {@link Vector4#w}.
  6247. *
  6248. * @type {number}
  6249. */
  6250. get height() {
  6251. return this.w;
  6252. }
  6253. set height( value ) {
  6254. this.w = value;
  6255. }
  6256. /**
  6257. * Sets the vector components.
  6258. *
  6259. * @param {number} x - The value of the x component.
  6260. * @param {number} y - The value of the y component.
  6261. * @param {number} z - The value of the z component.
  6262. * @param {number} w - The value of the w component.
  6263. * @return {Vector4} A reference to this vector.
  6264. */
  6265. set( x, y, z, w ) {
  6266. this.x = x;
  6267. this.y = y;
  6268. this.z = z;
  6269. this.w = w;
  6270. return this;
  6271. }
  6272. /**
  6273. * Sets the vector components to the same value.
  6274. *
  6275. * @param {number} scalar - The value to set for all vector components.
  6276. * @return {Vector4} A reference to this vector.
  6277. */
  6278. setScalar( scalar ) {
  6279. this.x = scalar;
  6280. this.y = scalar;
  6281. this.z = scalar;
  6282. this.w = scalar;
  6283. return this;
  6284. }
  6285. /**
  6286. * Sets the vector's x component to the given value
  6287. *
  6288. * @param {number} x - The value to set.
  6289. * @return {Vector4} A reference to this vector.
  6290. */
  6291. setX( x ) {
  6292. this.x = x;
  6293. return this;
  6294. }
  6295. /**
  6296. * Sets the vector's y component to the given value
  6297. *
  6298. * @param {number} y - The value to set.
  6299. * @return {Vector4} A reference to this vector.
  6300. */
  6301. setY( y ) {
  6302. this.y = y;
  6303. return this;
  6304. }
  6305. /**
  6306. * Sets the vector's z component to the given value
  6307. *
  6308. * @param {number} z - The value to set.
  6309. * @return {Vector4} A reference to this vector.
  6310. */
  6311. setZ( z ) {
  6312. this.z = z;
  6313. return this;
  6314. }
  6315. /**
  6316. * Sets the vector's w component to the given value
  6317. *
  6318. * @param {number} w - The value to set.
  6319. * @return {Vector4} A reference to this vector.
  6320. */
  6321. setW( w ) {
  6322. this.w = w;
  6323. return this;
  6324. }
  6325. /**
  6326. * Allows to set a vector component with an index.
  6327. *
  6328. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6329. * `2` equals to z, `3` equals to w.
  6330. * @param {number} value - The value to set.
  6331. * @return {Vector4} A reference to this vector.
  6332. */
  6333. setComponent( index, value ) {
  6334. switch ( index ) {
  6335. case 0: this.x = value; break;
  6336. case 1: this.y = value; break;
  6337. case 2: this.z = value; break;
  6338. case 3: this.w = value; break;
  6339. default: throw new Error( 'index is out of range: ' + index );
  6340. }
  6341. return this;
  6342. }
  6343. /**
  6344. * Returns the value of the vector component which matches the given index.
  6345. *
  6346. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6347. * `2` equals to z, `3` equals to w.
  6348. * @return {number} A vector component value.
  6349. */
  6350. getComponent( index ) {
  6351. switch ( index ) {
  6352. case 0: return this.x;
  6353. case 1: return this.y;
  6354. case 2: return this.z;
  6355. case 3: return this.w;
  6356. default: throw new Error( 'index is out of range: ' + index );
  6357. }
  6358. }
  6359. /**
  6360. * Returns a new vector with copied values from this instance.
  6361. *
  6362. * @return {Vector4} A clone of this instance.
  6363. */
  6364. clone() {
  6365. return new this.constructor( this.x, this.y, this.z, this.w );
  6366. }
  6367. /**
  6368. * Copies the values of the given vector to this instance.
  6369. *
  6370. * @param {Vector3|Vector4} v - The vector to copy.
  6371. * @return {Vector4} A reference to this vector.
  6372. */
  6373. copy( v ) {
  6374. this.x = v.x;
  6375. this.y = v.y;
  6376. this.z = v.z;
  6377. this.w = ( v.w !== undefined ) ? v.w : 1;
  6378. return this;
  6379. }
  6380. /**
  6381. * Adds the given vector to this instance.
  6382. *
  6383. * @param {Vector4} v - The vector to add.
  6384. * @return {Vector4} A reference to this vector.
  6385. */
  6386. add( v ) {
  6387. this.x += v.x;
  6388. this.y += v.y;
  6389. this.z += v.z;
  6390. this.w += v.w;
  6391. return this;
  6392. }
  6393. /**
  6394. * Adds the given scalar value to all components of this instance.
  6395. *
  6396. * @param {number} s - The scalar to add.
  6397. * @return {Vector4} A reference to this vector.
  6398. */
  6399. addScalar( s ) {
  6400. this.x += s;
  6401. this.y += s;
  6402. this.z += s;
  6403. this.w += s;
  6404. return this;
  6405. }
  6406. /**
  6407. * Adds the given vectors and stores the result in this instance.
  6408. *
  6409. * @param {Vector4} a - The first vector.
  6410. * @param {Vector4} b - The second vector.
  6411. * @return {Vector4} A reference to this vector.
  6412. */
  6413. addVectors( a, b ) {
  6414. this.x = a.x + b.x;
  6415. this.y = a.y + b.y;
  6416. this.z = a.z + b.z;
  6417. this.w = a.w + b.w;
  6418. return this;
  6419. }
  6420. /**
  6421. * Adds the given vector scaled by the given factor to this instance.
  6422. *
  6423. * @param {Vector4} v - The vector.
  6424. * @param {number} s - The factor that scales `v`.
  6425. * @return {Vector4} A reference to this vector.
  6426. */
  6427. addScaledVector( v, s ) {
  6428. this.x += v.x * s;
  6429. this.y += v.y * s;
  6430. this.z += v.z * s;
  6431. this.w += v.w * s;
  6432. return this;
  6433. }
  6434. /**
  6435. * Subtracts the given vector from this instance.
  6436. *
  6437. * @param {Vector4} v - The vector to subtract.
  6438. * @return {Vector4} A reference to this vector.
  6439. */
  6440. sub( v ) {
  6441. this.x -= v.x;
  6442. this.y -= v.y;
  6443. this.z -= v.z;
  6444. this.w -= v.w;
  6445. return this;
  6446. }
  6447. /**
  6448. * Subtracts the given scalar value from all components of this instance.
  6449. *
  6450. * @param {number} s - The scalar to subtract.
  6451. * @return {Vector4} A reference to this vector.
  6452. */
  6453. subScalar( s ) {
  6454. this.x -= s;
  6455. this.y -= s;
  6456. this.z -= s;
  6457. this.w -= s;
  6458. return this;
  6459. }
  6460. /**
  6461. * Subtracts the given vectors and stores the result in this instance.
  6462. *
  6463. * @param {Vector4} a - The first vector.
  6464. * @param {Vector4} b - The second vector.
  6465. * @return {Vector4} A reference to this vector.
  6466. */
  6467. subVectors( a, b ) {
  6468. this.x = a.x - b.x;
  6469. this.y = a.y - b.y;
  6470. this.z = a.z - b.z;
  6471. this.w = a.w - b.w;
  6472. return this;
  6473. }
  6474. /**
  6475. * Multiplies the given vector with this instance.
  6476. *
  6477. * @param {Vector4} v - The vector to multiply.
  6478. * @return {Vector4} A reference to this vector.
  6479. */
  6480. multiply( v ) {
  6481. this.x *= v.x;
  6482. this.y *= v.y;
  6483. this.z *= v.z;
  6484. this.w *= v.w;
  6485. return this;
  6486. }
  6487. /**
  6488. * Multiplies the given scalar value with all components of this instance.
  6489. *
  6490. * @param {number} scalar - The scalar to multiply.
  6491. * @return {Vector4} A reference to this vector.
  6492. */
  6493. multiplyScalar( scalar ) {
  6494. this.x *= scalar;
  6495. this.y *= scalar;
  6496. this.z *= scalar;
  6497. this.w *= scalar;
  6498. return this;
  6499. }
  6500. /**
  6501. * Multiplies this vector with the given 4x4 matrix.
  6502. *
  6503. * @param {Matrix4} m - The 4x4 matrix.
  6504. * @return {Vector4} A reference to this vector.
  6505. */
  6506. applyMatrix4( m ) {
  6507. const x = this.x, y = this.y, z = this.z, w = this.w;
  6508. const e = m.elements;
  6509. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6510. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6511. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6512. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6513. return this;
  6514. }
  6515. /**
  6516. * Divides this instance by the given vector.
  6517. *
  6518. * @param {Vector4} v - The vector to divide.
  6519. * @return {Vector4} A reference to this vector.
  6520. */
  6521. divide( v ) {
  6522. this.x /= v.x;
  6523. this.y /= v.y;
  6524. this.z /= v.z;
  6525. this.w /= v.w;
  6526. return this;
  6527. }
  6528. /**
  6529. * Divides this vector by the given scalar.
  6530. *
  6531. * @param {number} scalar - The scalar to divide.
  6532. * @return {Vector4} A reference to this vector.
  6533. */
  6534. divideScalar( scalar ) {
  6535. return this.multiplyScalar( 1 / scalar );
  6536. }
  6537. /**
  6538. * Sets the x, y and z components of this
  6539. * vector to the quaternion's axis and w to the angle.
  6540. *
  6541. * @param {Quaternion} q - The Quaternion to set.
  6542. * @return {Vector4} A reference to this vector.
  6543. */
  6544. setAxisAngleFromQuaternion( q ) {
  6545. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6546. // q is assumed to be normalized
  6547. this.w = 2 * Math.acos( q.w );
  6548. const s = Math.sqrt( 1 - q.w * q.w );
  6549. if ( s < 0.0001 ) {
  6550. this.x = 1;
  6551. this.y = 0;
  6552. this.z = 0;
  6553. } else {
  6554. this.x = q.x / s;
  6555. this.y = q.y / s;
  6556. this.z = q.z / s;
  6557. }
  6558. return this;
  6559. }
  6560. /**
  6561. * Sets the x, y and z components of this
  6562. * vector to the axis of rotation and w to the angle.
  6563. *
  6564. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6565. * @return {Vector4} A reference to this vector.
  6566. */
  6567. setAxisAngleFromRotationMatrix( m ) {
  6568. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6569. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6570. let angle, x, y, z; // variables for result
  6571. const epsilon = 0.01, // margin to allow for rounding errors
  6572. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6573. te = m.elements,
  6574. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6575. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6576. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6577. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6578. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6579. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6580. // singularity found
  6581. // first check for identity matrix which must have +1 for all terms
  6582. // in leading diagonal and zero in other terms
  6583. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6584. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6585. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6586. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6587. // this singularity is identity matrix so angle = 0
  6588. this.set( 1, 0, 0, 0 );
  6589. return this; // zero angle, arbitrary axis
  6590. }
  6591. // otherwise this singularity is angle = 180
  6592. angle = Math.PI;
  6593. const xx = ( m11 + 1 ) / 2;
  6594. const yy = ( m22 + 1 ) / 2;
  6595. const zz = ( m33 + 1 ) / 2;
  6596. const xy = ( m12 + m21 ) / 4;
  6597. const xz = ( m13 + m31 ) / 4;
  6598. const yz = ( m23 + m32 ) / 4;
  6599. if ( ( xx > yy ) && ( xx > zz ) ) {
  6600. // m11 is the largest diagonal term
  6601. if ( xx < epsilon ) {
  6602. x = 0;
  6603. y = 0.707106781;
  6604. z = 0.707106781;
  6605. } else {
  6606. x = Math.sqrt( xx );
  6607. y = xy / x;
  6608. z = xz / x;
  6609. }
  6610. } else if ( yy > zz ) {
  6611. // m22 is the largest diagonal term
  6612. if ( yy < epsilon ) {
  6613. x = 0.707106781;
  6614. y = 0;
  6615. z = 0.707106781;
  6616. } else {
  6617. y = Math.sqrt( yy );
  6618. x = xy / y;
  6619. z = yz / y;
  6620. }
  6621. } else {
  6622. // m33 is the largest diagonal term so base result on this
  6623. if ( zz < epsilon ) {
  6624. x = 0.707106781;
  6625. y = 0.707106781;
  6626. z = 0;
  6627. } else {
  6628. z = Math.sqrt( zz );
  6629. x = xz / z;
  6630. y = yz / z;
  6631. }
  6632. }
  6633. this.set( x, y, z, angle );
  6634. return this; // return 180 deg rotation
  6635. }
  6636. // as we have reached here there are no singularities so we can handle normally
  6637. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6638. ( m13 - m31 ) * ( m13 - m31 ) +
  6639. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6640. if ( Math.abs( s ) < 0.001 ) s = 1;
  6641. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6642. // caught by singularity test above, but I've left it in just in case
  6643. this.x = ( m32 - m23 ) / s;
  6644. this.y = ( m13 - m31 ) / s;
  6645. this.z = ( m21 - m12 ) / s;
  6646. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6647. return this;
  6648. }
  6649. /**
  6650. * Sets the vector components to the position elements of the
  6651. * given transformation matrix.
  6652. *
  6653. * @param {Matrix4} m - The 4x4 matrix.
  6654. * @return {Vector4} A reference to this vector.
  6655. */
  6656. setFromMatrixPosition( m ) {
  6657. const e = m.elements;
  6658. this.x = e[ 12 ];
  6659. this.y = e[ 13 ];
  6660. this.z = e[ 14 ];
  6661. this.w = e[ 15 ];
  6662. return this;
  6663. }
  6664. /**
  6665. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6666. * value, replace that value with the corresponding min value.
  6667. *
  6668. * @param {Vector4} v - The vector.
  6669. * @return {Vector4} A reference to this vector.
  6670. */
  6671. min( v ) {
  6672. this.x = Math.min( this.x, v.x );
  6673. this.y = Math.min( this.y, v.y );
  6674. this.z = Math.min( this.z, v.z );
  6675. this.w = Math.min( this.w, v.w );
  6676. return this;
  6677. }
  6678. /**
  6679. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6680. * value, replace that value with the corresponding max value.
  6681. *
  6682. * @param {Vector4} v - The vector.
  6683. * @return {Vector4} A reference to this vector.
  6684. */
  6685. max( v ) {
  6686. this.x = Math.max( this.x, v.x );
  6687. this.y = Math.max( this.y, v.y );
  6688. this.z = Math.max( this.z, v.z );
  6689. this.w = Math.max( this.w, v.w );
  6690. return this;
  6691. }
  6692. /**
  6693. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6694. * value, it is replaced by the corresponding value.
  6695. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6696. * it is replaced by the corresponding value.
  6697. *
  6698. * @param {Vector4} min - The minimum x, y and z values.
  6699. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6700. * @return {Vector4} A reference to this vector.
  6701. */
  6702. clamp( min, max ) {
  6703. // assumes min < max, componentwise
  6704. this.x = clamp( this.x, min.x, max.x );
  6705. this.y = clamp( this.y, min.y, max.y );
  6706. this.z = clamp( this.z, min.z, max.z );
  6707. this.w = clamp( this.w, min.w, max.w );
  6708. return this;
  6709. }
  6710. /**
  6711. * If this vector's x, y, z or w values are greater than the max value, they are
  6712. * replaced by the max value.
  6713. * If this vector's x, y, z or w values are less than the min value, they are
  6714. * replaced by the min value.
  6715. *
  6716. * @param {number} minVal - The minimum value the components will be clamped to.
  6717. * @param {number} maxVal - The maximum value the components will be clamped to.
  6718. * @return {Vector4} A reference to this vector.
  6719. */
  6720. clampScalar( minVal, maxVal ) {
  6721. this.x = clamp( this.x, minVal, maxVal );
  6722. this.y = clamp( this.y, minVal, maxVal );
  6723. this.z = clamp( this.z, minVal, maxVal );
  6724. this.w = clamp( this.w, minVal, maxVal );
  6725. return this;
  6726. }
  6727. /**
  6728. * If this vector's length is greater than the max value, it is replaced by
  6729. * the max value.
  6730. * If this vector's length is less than the min value, it is replaced by the
  6731. * min value.
  6732. *
  6733. * @param {number} min - The minimum value the vector length will be clamped to.
  6734. * @param {number} max - The maximum value the vector length will be clamped to.
  6735. * @return {Vector4} A reference to this vector.
  6736. */
  6737. clampLength( min, max ) {
  6738. const length = this.length();
  6739. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6740. }
  6741. /**
  6742. * The components of this vector are rounded down to the nearest integer value.
  6743. *
  6744. * @return {Vector4} A reference to this vector.
  6745. */
  6746. floor() {
  6747. this.x = Math.floor( this.x );
  6748. this.y = Math.floor( this.y );
  6749. this.z = Math.floor( this.z );
  6750. this.w = Math.floor( this.w );
  6751. return this;
  6752. }
  6753. /**
  6754. * The components of this vector are rounded up to the nearest integer value.
  6755. *
  6756. * @return {Vector4} A reference to this vector.
  6757. */
  6758. ceil() {
  6759. this.x = Math.ceil( this.x );
  6760. this.y = Math.ceil( this.y );
  6761. this.z = Math.ceil( this.z );
  6762. this.w = Math.ceil( this.w );
  6763. return this;
  6764. }
  6765. /**
  6766. * The components of this vector are rounded to the nearest integer value
  6767. *
  6768. * @return {Vector4} A reference to this vector.
  6769. */
  6770. round() {
  6771. this.x = Math.round( this.x );
  6772. this.y = Math.round( this.y );
  6773. this.z = Math.round( this.z );
  6774. this.w = Math.round( this.w );
  6775. return this;
  6776. }
  6777. /**
  6778. * The components of this vector are rounded towards zero (up if negative,
  6779. * down if positive) to an integer value.
  6780. *
  6781. * @return {Vector4} A reference to this vector.
  6782. */
  6783. roundToZero() {
  6784. this.x = Math.trunc( this.x );
  6785. this.y = Math.trunc( this.y );
  6786. this.z = Math.trunc( this.z );
  6787. this.w = Math.trunc( this.w );
  6788. return this;
  6789. }
  6790. /**
  6791. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6792. *
  6793. * @return {Vector4} A reference to this vector.
  6794. */
  6795. negate() {
  6796. this.x = - this.x;
  6797. this.y = - this.y;
  6798. this.z = - this.z;
  6799. this.w = - this.w;
  6800. return this;
  6801. }
  6802. /**
  6803. * Calculates the dot product of the given vector with this instance.
  6804. *
  6805. * @param {Vector4} v - The vector to compute the dot product with.
  6806. * @return {number} The result of the dot product.
  6807. */
  6808. dot( v ) {
  6809. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6810. }
  6811. /**
  6812. * Computes the square of the Euclidean length (straight-line length) from
  6813. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6814. * compare the length squared instead as it is slightly more efficient to calculate.
  6815. *
  6816. * @return {number} The square length of this vector.
  6817. */
  6818. lengthSq() {
  6819. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6820. }
  6821. /**
  6822. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6823. *
  6824. * @return {number} The length of this vector.
  6825. */
  6826. length() {
  6827. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6828. }
  6829. /**
  6830. * Computes the Manhattan length of this vector.
  6831. *
  6832. * @return {number} The length of this vector.
  6833. */
  6834. manhattanLength() {
  6835. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6836. }
  6837. /**
  6838. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6839. * with the same direction as this one, but with a vector length of `1`.
  6840. *
  6841. * @return {Vector4} A reference to this vector.
  6842. */
  6843. normalize() {
  6844. return this.divideScalar( this.length() || 1 );
  6845. }
  6846. /**
  6847. * Sets this vector to a vector with the same direction as this one, but
  6848. * with the specified length.
  6849. *
  6850. * @param {number} length - The new length of this vector.
  6851. * @return {Vector4} A reference to this vector.
  6852. */
  6853. setLength( length ) {
  6854. return this.normalize().multiplyScalar( length );
  6855. }
  6856. /**
  6857. * Linearly interpolates between the given vector and this instance, where
  6858. * alpha is the percent distance along the line - alpha = 0 will be this
  6859. * vector, and alpha = 1 will be the given one.
  6860. *
  6861. * @param {Vector4} v - The vector to interpolate towards.
  6862. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6863. * @return {Vector4} A reference to this vector.
  6864. */
  6865. lerp( v, alpha ) {
  6866. this.x += ( v.x - this.x ) * alpha;
  6867. this.y += ( v.y - this.y ) * alpha;
  6868. this.z += ( v.z - this.z ) * alpha;
  6869. this.w += ( v.w - this.w ) * alpha;
  6870. return this;
  6871. }
  6872. /**
  6873. * Linearly interpolates between the given vectors, where alpha is the percent
  6874. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6875. * be the second one. The result is stored in this instance.
  6876. *
  6877. * @param {Vector4} v1 - The first vector.
  6878. * @param {Vector4} v2 - The second vector.
  6879. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6880. * @return {Vector4} A reference to this vector.
  6881. */
  6882. lerpVectors( v1, v2, alpha ) {
  6883. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6884. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6885. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6886. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6887. return this;
  6888. }
  6889. /**
  6890. * Returns `true` if this vector is equal with the given one.
  6891. *
  6892. * @param {Vector4} v - The vector to test for equality.
  6893. * @return {boolean} Whether this vector is equal with the given one.
  6894. */
  6895. equals( v ) {
  6896. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6897. }
  6898. /**
  6899. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6900. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6901. *
  6902. * @param {Array<number>} array - An array holding the vector component values.
  6903. * @param {number} [offset=0] - The offset into the array.
  6904. * @return {Vector4} A reference to this vector.
  6905. */
  6906. fromArray( array, offset = 0 ) {
  6907. this.x = array[ offset ];
  6908. this.y = array[ offset + 1 ];
  6909. this.z = array[ offset + 2 ];
  6910. this.w = array[ offset + 3 ];
  6911. return this;
  6912. }
  6913. /**
  6914. * Writes the components of this vector to the given array. If no array is provided,
  6915. * the method returns a new instance.
  6916. *
  6917. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6918. * @param {number} [offset=0] - Index of the first element in the array.
  6919. * @return {Array<number>} The vector components.
  6920. */
  6921. toArray( array = [], offset = 0 ) {
  6922. array[ offset ] = this.x;
  6923. array[ offset + 1 ] = this.y;
  6924. array[ offset + 2 ] = this.z;
  6925. array[ offset + 3 ] = this.w;
  6926. return array;
  6927. }
  6928. /**
  6929. * Sets the components of this vector from the given buffer attribute.
  6930. *
  6931. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6932. * @param {number} index - The index into the attribute.
  6933. * @return {Vector4} A reference to this vector.
  6934. */
  6935. fromBufferAttribute( attribute, index ) {
  6936. this.x = attribute.getX( index );
  6937. this.y = attribute.getY( index );
  6938. this.z = attribute.getZ( index );
  6939. this.w = attribute.getW( index );
  6940. return this;
  6941. }
  6942. /**
  6943. * Sets each component of this vector to a pseudo-random value between `0` and
  6944. * `1`, excluding `1`.
  6945. *
  6946. * @return {Vector4} A reference to this vector.
  6947. */
  6948. random() {
  6949. this.x = Math.random();
  6950. this.y = Math.random();
  6951. this.z = Math.random();
  6952. this.w = Math.random();
  6953. return this;
  6954. }
  6955. *[ Symbol.iterator ]() {
  6956. yield this.x;
  6957. yield this.y;
  6958. yield this.z;
  6959. yield this.w;
  6960. }
  6961. }
  6962. /**
  6963. * A render target is a buffer where the video card draws pixels for a scene
  6964. * that is being rendered in the background. It is used in different effects,
  6965. * such as applying postprocessing to a rendered image before displaying it
  6966. * on the screen.
  6967. *
  6968. * @augments EventDispatcher
  6969. */
  6970. class RenderTarget extends EventDispatcher {
  6971. /**
  6972. * Render target options.
  6973. *
  6974. * @typedef {Object} RenderTarget~Options
  6975. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6976. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6977. * @property {number} [minFilter=LinearFilter] - The min filter.
  6978. * @property {number} [format=RGBAFormat] - The texture format.
  6979. * @property {number} [type=UnsignedByteType] - The texture type.
  6980. * @property {?string} [internalFormat=null] - The texture's internal format.
  6981. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6982. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6983. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6984. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6985. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6986. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6987. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6988. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6989. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6990. * @property {number} [samples=0] - The MSAA samples count.
  6991. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6992. * @property {number} [depth=1] - The texture depth.
  6993. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6994. */
  6995. /**
  6996. * Constructs a new render target.
  6997. *
  6998. * @param {number} [width=1] - The width of the render target.
  6999. * @param {number} [height=1] - The height of the render target.
  7000. * @param {RenderTarget~Options} [options] - The configuration object.
  7001. */
  7002. constructor( width = 1, height = 1, options = {} ) {
  7003. super();
  7004. options = Object.assign( {
  7005. generateMipmaps: false,
  7006. internalFormat: null,
  7007. minFilter: LinearFilter,
  7008. depthBuffer: true,
  7009. stencilBuffer: false,
  7010. resolveDepthBuffer: true,
  7011. resolveStencilBuffer: true,
  7012. depthTexture: null,
  7013. samples: 0,
  7014. count: 1,
  7015. depth: 1,
  7016. multiview: false
  7017. }, options );
  7018. /**
  7019. * This flag can be used for type testing.
  7020. *
  7021. * @type {boolean}
  7022. * @readonly
  7023. * @default true
  7024. */
  7025. this.isRenderTarget = true;
  7026. /**
  7027. * The width of the render target.
  7028. *
  7029. * @type {number}
  7030. * @default 1
  7031. */
  7032. this.width = width;
  7033. /**
  7034. * The height of the render target.
  7035. *
  7036. * @type {number}
  7037. * @default 1
  7038. */
  7039. this.height = height;
  7040. /**
  7041. * The depth of the render target.
  7042. *
  7043. * @type {number}
  7044. * @default 1
  7045. */
  7046. this.depth = options.depth;
  7047. /**
  7048. * A rectangular area inside the render target's viewport. Fragments that are
  7049. * outside the area will be discarded.
  7050. *
  7051. * @type {Vector4}
  7052. * @default (0,0,width,height)
  7053. */
  7054. this.scissor = new Vector4( 0, 0, width, height );
  7055. /**
  7056. * Indicates whether the scissor test should be enabled when rendering into
  7057. * this render target or not.
  7058. *
  7059. * @type {boolean}
  7060. * @default false
  7061. */
  7062. this.scissorTest = false;
  7063. /**
  7064. * A rectangular area representing the render target's viewport.
  7065. *
  7066. * @type {Vector4}
  7067. * @default (0,0,width,height)
  7068. */
  7069. this.viewport = new Vector4( 0, 0, width, height );
  7070. const image = { width: width, height: height, depth: options.depth };
  7071. const texture = new Texture( image );
  7072. /**
  7073. * An array of textures. Each color attachment is represented as a separate texture.
  7074. * Has at least a single entry for the default color attachment.
  7075. *
  7076. * @type {Array<Texture>}
  7077. */
  7078. this.textures = [];
  7079. const count = options.count;
  7080. for ( let i = 0; i < count; i ++ ) {
  7081. this.textures[ i ] = texture.clone();
  7082. this.textures[ i ].isRenderTargetTexture = true;
  7083. this.textures[ i ].renderTarget = this;
  7084. }
  7085. this._setTextureOptions( options );
  7086. /**
  7087. * Whether to allocate a depth buffer or not.
  7088. *
  7089. * @type {boolean}
  7090. * @default true
  7091. */
  7092. this.depthBuffer = options.depthBuffer;
  7093. /**
  7094. * Whether to allocate a stencil buffer or not.
  7095. *
  7096. * @type {boolean}
  7097. * @default false
  7098. */
  7099. this.stencilBuffer = options.stencilBuffer;
  7100. /**
  7101. * Whether to resolve the depth buffer or not.
  7102. *
  7103. * @type {boolean}
  7104. * @default true
  7105. */
  7106. this.resolveDepthBuffer = options.resolveDepthBuffer;
  7107. /**
  7108. * Whether to resolve the stencil buffer or not.
  7109. *
  7110. * @type {boolean}
  7111. * @default true
  7112. */
  7113. this.resolveStencilBuffer = options.resolveStencilBuffer;
  7114. this._depthTexture = null;
  7115. this.depthTexture = options.depthTexture;
  7116. /**
  7117. * The number of MSAA samples.
  7118. *
  7119. * A value of `0` disables MSAA.
  7120. *
  7121. * @type {number}
  7122. * @default 0
  7123. */
  7124. this.samples = options.samples;
  7125. /**
  7126. * Whether to this target is used in multiview rendering.
  7127. *
  7128. * @type {boolean}
  7129. * @default false
  7130. */
  7131. this.multiview = options.multiview;
  7132. }
  7133. _setTextureOptions( options = {} ) {
  7134. const values = {
  7135. minFilter: LinearFilter,
  7136. generateMipmaps: false,
  7137. flipY: false,
  7138. internalFormat: null
  7139. };
  7140. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  7141. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  7142. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  7143. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  7144. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  7145. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  7146. if ( options.format !== undefined ) values.format = options.format;
  7147. if ( options.type !== undefined ) values.type = options.type;
  7148. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  7149. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  7150. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  7151. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  7152. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  7153. for ( let i = 0; i < this.textures.length; i ++ ) {
  7154. const texture = this.textures[ i ];
  7155. texture.setValues( values );
  7156. }
  7157. }
  7158. /**
  7159. * The texture representing the default color attachment.
  7160. *
  7161. * @type {Texture}
  7162. */
  7163. get texture() {
  7164. return this.textures[ 0 ];
  7165. }
  7166. set texture( value ) {
  7167. this.textures[ 0 ] = value;
  7168. }
  7169. set depthTexture( current ) {
  7170. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  7171. if ( current !== null ) current.renderTarget = this;
  7172. this._depthTexture = current;
  7173. }
  7174. /**
  7175. * Instead of saving the depth in a renderbuffer, a texture
  7176. * can be used instead which is useful for further processing
  7177. * e.g. in context of post-processing.
  7178. *
  7179. * @type {?DepthTexture}
  7180. * @default null
  7181. */
  7182. get depthTexture() {
  7183. return this._depthTexture;
  7184. }
  7185. /**
  7186. * Sets the size of this render target.
  7187. *
  7188. * @param {number} width - The width.
  7189. * @param {number} height - The height.
  7190. * @param {number} [depth=1] - The depth.
  7191. */
  7192. setSize( width, height, depth = 1 ) {
  7193. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7194. this.width = width;
  7195. this.height = height;
  7196. this.depth = depth;
  7197. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7198. this.textures[ i ].image.width = width;
  7199. this.textures[ i ].image.height = height;
  7200. this.textures[ i ].image.depth = depth;
  7201. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7202. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7203. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7204. // both are evaluated on each call?
  7205. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7206. }
  7207. }
  7208. this.dispose();
  7209. }
  7210. this.viewport.set( 0, 0, width, height );
  7211. this.scissor.set( 0, 0, width, height );
  7212. }
  7213. /**
  7214. * Returns a new render target with copied values from this instance.
  7215. *
  7216. * @return {RenderTarget} A clone of this instance.
  7217. */
  7218. clone() {
  7219. return new this.constructor().copy( this );
  7220. }
  7221. /**
  7222. * Copies the settings of the given render target. This is a structural copy so
  7223. * no resources are shared between render targets after the copy. That includes
  7224. * all MRT textures and the depth texture.
  7225. *
  7226. * @param {RenderTarget} source - The render target to copy.
  7227. * @return {RenderTarget} A reference to this instance.
  7228. */
  7229. copy( source ) {
  7230. this.width = source.width;
  7231. this.height = source.height;
  7232. this.depth = source.depth;
  7233. this.scissor.copy( source.scissor );
  7234. this.scissorTest = source.scissorTest;
  7235. this.viewport.copy( source.viewport );
  7236. this.textures.length = 0;
  7237. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7238. this.textures[ i ] = source.textures[ i ].clone();
  7239. this.textures[ i ].isRenderTargetTexture = true;
  7240. this.textures[ i ].renderTarget = this;
  7241. // ensure image object is not shared, see #20328
  7242. const image = Object.assign( {}, source.textures[ i ].image );
  7243. this.textures[ i ].source = new Source( image );
  7244. }
  7245. this.depthBuffer = source.depthBuffer;
  7246. this.stencilBuffer = source.stencilBuffer;
  7247. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7248. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7249. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7250. this.samples = source.samples;
  7251. return this;
  7252. }
  7253. /**
  7254. * Frees the GPU-related resources allocated by this instance. Call this
  7255. * method whenever this instance is no longer used in your app.
  7256. *
  7257. * @fires RenderTarget#dispose
  7258. */
  7259. dispose() {
  7260. this.dispatchEvent( { type: 'dispose' } );
  7261. }
  7262. }
  7263. /**
  7264. * A render target used in context of {@link WebGLRenderer}.
  7265. *
  7266. * @augments RenderTarget
  7267. */
  7268. class WebGLRenderTarget extends RenderTarget {
  7269. /**
  7270. * Constructs a new 3D render target.
  7271. *
  7272. * @param {number} [width=1] - The width of the render target.
  7273. * @param {number} [height=1] - The height of the render target.
  7274. * @param {RenderTarget~Options} [options] - The configuration object.
  7275. */
  7276. constructor( width = 1, height = 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.isWebGLRenderTarget = true;
  7286. }
  7287. }
  7288. /**
  7289. * Creates an array of textures directly from raw buffer data.
  7290. *
  7291. * @augments Texture
  7292. */
  7293. class DataArrayTexture extends Texture {
  7294. /**
  7295. * Constructs a new data array texture.
  7296. *
  7297. * @param {?TypedArray} [data=null] - The buffer data.
  7298. * @param {number} [width=1] - The width of the texture.
  7299. * @param {number} [height=1] - The height of the texture.
  7300. * @param {number} [depth=1] - The depth of the texture.
  7301. */
  7302. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7303. super( null );
  7304. /**
  7305. * This flag can be used for type testing.
  7306. *
  7307. * @type {boolean}
  7308. * @readonly
  7309. * @default true
  7310. */
  7311. this.isDataArrayTexture = true;
  7312. /**
  7313. * The image definition of a data texture.
  7314. *
  7315. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7316. */
  7317. this.image = { data, width, height, depth };
  7318. /**
  7319. * How the texture is sampled when a texel covers more than one pixel.
  7320. *
  7321. * Overwritten and set to `NearestFilter` by default.
  7322. *
  7323. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7324. * @default NearestFilter
  7325. */
  7326. this.magFilter = NearestFilter;
  7327. /**
  7328. * How the texture is sampled when a texel covers less than one pixel.
  7329. *
  7330. * Overwritten and set to `NearestFilter` by default.
  7331. *
  7332. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7333. * @default NearestFilter
  7334. */
  7335. this.minFilter = NearestFilter;
  7336. /**
  7337. * This defines how the texture is wrapped in the depth and corresponds to
  7338. * *W* in UVW mapping.
  7339. *
  7340. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7341. * @default ClampToEdgeWrapping
  7342. */
  7343. this.wrapR = ClampToEdgeWrapping;
  7344. /**
  7345. * Whether to generate mipmaps (if possible) for a texture.
  7346. *
  7347. * Overwritten and set to `false` by default.
  7348. *
  7349. * @type {boolean}
  7350. * @default false
  7351. */
  7352. this.generateMipmaps = false;
  7353. /**
  7354. * If set to `true`, the texture is flipped along the vertical axis when
  7355. * uploaded to the GPU.
  7356. *
  7357. * Overwritten and set to `false` by default.
  7358. *
  7359. * @type {boolean}
  7360. * @default false
  7361. */
  7362. this.flipY = false;
  7363. /**
  7364. * Specifies the alignment requirements for the start of each pixel row in memory.
  7365. *
  7366. * Overwritten and set to `1` by default.
  7367. *
  7368. * @type {boolean}
  7369. * @default 1
  7370. */
  7371. this.unpackAlignment = 1;
  7372. /**
  7373. * A set of all layers which need to be updated in the texture.
  7374. *
  7375. * @type {Set<number>}
  7376. */
  7377. this.layerUpdates = new Set();
  7378. }
  7379. /**
  7380. * Describes that a specific layer of the texture needs to be updated.
  7381. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7382. * entire data texture array is sent to the GPU. Marking specific
  7383. * layers will only transmit subsets of all mipmaps associated with a
  7384. * specific depth in the array which is often much more performant.
  7385. *
  7386. * @param {number} layerIndex - The layer index that should be updated.
  7387. */
  7388. addLayerUpdate( layerIndex ) {
  7389. this.layerUpdates.add( layerIndex );
  7390. }
  7391. /**
  7392. * Resets the layer updates registry.
  7393. */
  7394. clearLayerUpdates() {
  7395. this.layerUpdates.clear();
  7396. }
  7397. }
  7398. /**
  7399. * An array render target used in context of {@link WebGLRenderer}.
  7400. *
  7401. * @augments WebGLRenderTarget
  7402. */
  7403. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7404. /**
  7405. * Constructs a new array render target.
  7406. *
  7407. * @param {number} [width=1] - The width of the render target.
  7408. * @param {number} [height=1] - The height of the render target.
  7409. * @param {number} [depth=1] - The height of the render target.
  7410. * @param {RenderTarget~Options} [options] - The configuration object.
  7411. */
  7412. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7413. super( width, height, options );
  7414. /**
  7415. * This flag can be used for type testing.
  7416. *
  7417. * @type {boolean}
  7418. * @readonly
  7419. * @default true
  7420. */
  7421. this.isWebGLArrayRenderTarget = true;
  7422. this.depth = depth;
  7423. /**
  7424. * Overwritten with a different texture type.
  7425. *
  7426. * @type {DataArrayTexture}
  7427. */
  7428. this.texture = new DataArrayTexture( null, width, height, depth );
  7429. this._setTextureOptions( options );
  7430. this.texture.isRenderTargetTexture = true;
  7431. }
  7432. }
  7433. /**
  7434. * Creates a three-dimensional texture from raw data, with parameters to
  7435. * divide it into width, height, and depth.
  7436. *
  7437. * @augments Texture
  7438. */
  7439. class Data3DTexture extends Texture {
  7440. /**
  7441. * Constructs a new data array texture.
  7442. *
  7443. * @param {?TypedArray} [data=null] - The buffer data.
  7444. * @param {number} [width=1] - The width of the texture.
  7445. * @param {number} [height=1] - The height of the texture.
  7446. * @param {number} [depth=1] - The depth of the texture.
  7447. */
  7448. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7449. // We're going to add .setXXX() methods for setting properties later.
  7450. // Users can still set in Data3DTexture directly.
  7451. //
  7452. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7453. // texture.anisotropy = 16;
  7454. //
  7455. // See #14839
  7456. super( null );
  7457. /**
  7458. * This flag can be used for type testing.
  7459. *
  7460. * @type {boolean}
  7461. * @readonly
  7462. * @default true
  7463. */
  7464. this.isData3DTexture = true;
  7465. /**
  7466. * The image definition of a data texture.
  7467. *
  7468. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7469. */
  7470. this.image = { data, width, height, depth };
  7471. /**
  7472. * How the texture is sampled when a texel covers more than one pixel.
  7473. *
  7474. * Overwritten and set to `NearestFilter` by default.
  7475. *
  7476. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7477. * @default NearestFilter
  7478. */
  7479. this.magFilter = NearestFilter;
  7480. /**
  7481. * How the texture is sampled when a texel covers less than one pixel.
  7482. *
  7483. * Overwritten and set to `NearestFilter` by default.
  7484. *
  7485. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7486. * @default NearestFilter
  7487. */
  7488. this.minFilter = NearestFilter;
  7489. /**
  7490. * This defines how the texture is wrapped in the depth and corresponds to
  7491. * *W* in UVW mapping.
  7492. *
  7493. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7494. * @default ClampToEdgeWrapping
  7495. */
  7496. this.wrapR = ClampToEdgeWrapping;
  7497. /**
  7498. * Whether to generate mipmaps (if possible) for a texture.
  7499. *
  7500. * Overwritten and set to `false` by default.
  7501. *
  7502. * @type {boolean}
  7503. * @default false
  7504. */
  7505. this.generateMipmaps = false;
  7506. /**
  7507. * If set to `true`, the texture is flipped along the vertical axis when
  7508. * uploaded to the GPU.
  7509. *
  7510. * Overwritten and set to `false` by default.
  7511. *
  7512. * @type {boolean}
  7513. * @default false
  7514. */
  7515. this.flipY = false;
  7516. /**
  7517. * Specifies the alignment requirements for the start of each pixel row in memory.
  7518. *
  7519. * Overwritten and set to `1` by default.
  7520. *
  7521. * @type {boolean}
  7522. * @default 1
  7523. */
  7524. this.unpackAlignment = 1;
  7525. }
  7526. }
  7527. /**
  7528. * A 3D render target used in context of {@link WebGLRenderer}.
  7529. *
  7530. * @augments WebGLRenderTarget
  7531. */
  7532. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7533. /**
  7534. * Constructs a new 3D render target.
  7535. *
  7536. * @param {number} [width=1] - The width of the render target.
  7537. * @param {number} [height=1] - The height of the render target.
  7538. * @param {number} [depth=1] - The height of the render target.
  7539. * @param {RenderTarget~Options} [options] - The configuration object.
  7540. */
  7541. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7542. super( width, height, options );
  7543. /**
  7544. * This flag can be used for type testing.
  7545. *
  7546. * @type {boolean}
  7547. * @readonly
  7548. * @default true
  7549. */
  7550. this.isWebGL3DRenderTarget = true;
  7551. this.depth = depth;
  7552. /**
  7553. * Overwritten with a different texture type.
  7554. *
  7555. * @type {Data3DTexture}
  7556. */
  7557. this.texture = new Data3DTexture( null, width, height, depth );
  7558. this._setTextureOptions( options );
  7559. this.texture.isRenderTargetTexture = true;
  7560. }
  7561. }
  7562. /**
  7563. * Represents a 4x4 matrix.
  7564. *
  7565. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  7566. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  7567. *
  7568. * This allows a 3D vector representing a point in 3D space to undergo
  7569. * transformations such as translation, rotation, shear, scale, reflection,
  7570. * orthogonal or perspective projection and so on, by being multiplied by the
  7571. * matrix. This is known as `applying` the matrix to the vector.
  7572. *
  7573. * A Note on Row-Major and Column-Major Ordering:
  7574. *
  7575. * The constructor and {@link Matrix3#set} method take arguments in
  7576. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  7577. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  7578. * This means that calling:
  7579. * ```js
  7580. * const m = new THREE.Matrix4();
  7581. * m.set( 11, 12, 13, 14,
  7582. * 21, 22, 23, 24,
  7583. * 31, 32, 33, 34,
  7584. * 41, 42, 43, 44 );
  7585. * ```
  7586. * will result in the elements array containing:
  7587. * ```js
  7588. * m.elements = [ 11, 21, 31, 41,
  7589. * 12, 22, 32, 42,
  7590. * 13, 23, 33, 43,
  7591. * 14, 24, 34, 44 ];
  7592. * ```
  7593. * and internally all calculations are performed using column-major ordering.
  7594. * However, as the actual ordering makes no difference mathematically and
  7595. * most people are used to thinking about matrices in row-major order, the
  7596. * three.js documentation shows matrices in row-major order. Just bear in
  7597. * mind that if you are reading the source code, you'll have to take the
  7598. * transpose of any matrices outlined here to make sense of the calculations.
  7599. */
  7600. class Matrix4 {
  7601. /**
  7602. * Constructs a new 4x4 matrix. The arguments are supposed to be
  7603. * in row-major order. If no arguments are provided, the constructor
  7604. * initializes the matrix as an identity matrix.
  7605. *
  7606. * @param {number} [n11] - 1-1 matrix element.
  7607. * @param {number} [n12] - 1-2 matrix element.
  7608. * @param {number} [n13] - 1-3 matrix element.
  7609. * @param {number} [n14] - 1-4 matrix element.
  7610. * @param {number} [n21] - 2-1 matrix element.
  7611. * @param {number} [n22] - 2-2 matrix element.
  7612. * @param {number} [n23] - 2-3 matrix element.
  7613. * @param {number} [n24] - 2-4 matrix element.
  7614. * @param {number} [n31] - 3-1 matrix element.
  7615. * @param {number} [n32] - 3-2 matrix element.
  7616. * @param {number} [n33] - 3-3 matrix element.
  7617. * @param {number} [n34] - 3-4 matrix element.
  7618. * @param {number} [n41] - 4-1 matrix element.
  7619. * @param {number} [n42] - 4-2 matrix element.
  7620. * @param {number} [n43] - 4-3 matrix element.
  7621. * @param {number} [n44] - 4-4 matrix element.
  7622. */
  7623. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7624. /**
  7625. * This flag can be used for type testing.
  7626. *
  7627. * @type {boolean}
  7628. * @readonly
  7629. * @default true
  7630. */
  7631. Matrix4.prototype.isMatrix4 = true;
  7632. /**
  7633. * A column-major list of matrix values.
  7634. *
  7635. * @type {Array<number>}
  7636. */
  7637. this.elements = [
  7638. 1, 0, 0, 0,
  7639. 0, 1, 0, 0,
  7640. 0, 0, 1, 0,
  7641. 0, 0, 0, 1
  7642. ];
  7643. if ( n11 !== undefined ) {
  7644. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  7645. }
  7646. }
  7647. /**
  7648. * Sets the elements of the matrix.The arguments are supposed to be
  7649. * in row-major order.
  7650. *
  7651. * @param {number} [n11] - 1-1 matrix element.
  7652. * @param {number} [n12] - 1-2 matrix element.
  7653. * @param {number} [n13] - 1-3 matrix element.
  7654. * @param {number} [n14] - 1-4 matrix element.
  7655. * @param {number} [n21] - 2-1 matrix element.
  7656. * @param {number} [n22] - 2-2 matrix element.
  7657. * @param {number} [n23] - 2-3 matrix element.
  7658. * @param {number} [n24] - 2-4 matrix element.
  7659. * @param {number} [n31] - 3-1 matrix element.
  7660. * @param {number} [n32] - 3-2 matrix element.
  7661. * @param {number} [n33] - 3-3 matrix element.
  7662. * @param {number} [n34] - 3-4 matrix element.
  7663. * @param {number} [n41] - 4-1 matrix element.
  7664. * @param {number} [n42] - 4-2 matrix element.
  7665. * @param {number} [n43] - 4-3 matrix element.
  7666. * @param {number} [n44] - 4-4 matrix element.
  7667. * @return {Matrix4} A reference to this matrix.
  7668. */
  7669. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7670. const te = this.elements;
  7671. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  7672. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  7673. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  7674. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  7675. return this;
  7676. }
  7677. /**
  7678. * Sets this matrix to the 4x4 identity matrix.
  7679. *
  7680. * @return {Matrix4} A reference to this matrix.
  7681. */
  7682. identity() {
  7683. this.set(
  7684. 1, 0, 0, 0,
  7685. 0, 1, 0, 0,
  7686. 0, 0, 1, 0,
  7687. 0, 0, 0, 1
  7688. );
  7689. return this;
  7690. }
  7691. /**
  7692. * Returns a matrix with copied values from this instance.
  7693. *
  7694. * @return {Matrix4} A clone of this instance.
  7695. */
  7696. clone() {
  7697. return new Matrix4().fromArray( this.elements );
  7698. }
  7699. /**
  7700. * Copies the values of the given matrix to this instance.
  7701. *
  7702. * @param {Matrix4} m - The matrix to copy.
  7703. * @return {Matrix4} A reference to this matrix.
  7704. */
  7705. copy( m ) {
  7706. const te = this.elements;
  7707. const me = m.elements;
  7708. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  7709. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  7710. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  7711. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  7712. return this;
  7713. }
  7714. /**
  7715. * Copies the translation component of the given matrix
  7716. * into this matrix's translation component.
  7717. *
  7718. * @param {Matrix4} m - The matrix to copy the translation component.
  7719. * @return {Matrix4} A reference to this matrix.
  7720. */
  7721. copyPosition( m ) {
  7722. const te = this.elements, me = m.elements;
  7723. te[ 12 ] = me[ 12 ];
  7724. te[ 13 ] = me[ 13 ];
  7725. te[ 14 ] = me[ 14 ];
  7726. return this;
  7727. }
  7728. /**
  7729. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  7730. *
  7731. * @param {Matrix3} m - The 3x3 matrix.
  7732. * @return {Matrix4} A reference to this matrix.
  7733. */
  7734. setFromMatrix3( m ) {
  7735. const me = m.elements;
  7736. this.set(
  7737. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  7738. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  7739. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  7740. 0, 0, 0, 1
  7741. );
  7742. return this;
  7743. }
  7744. /**
  7745. * Extracts the basis of this matrix into the three axis vectors provided.
  7746. *
  7747. * @param {Vector3} xAxis - The basis's x axis.
  7748. * @param {Vector3} yAxis - The basis's y axis.
  7749. * @param {Vector3} zAxis - The basis's z axis.
  7750. * @return {Matrix4} A reference to this matrix.
  7751. */
  7752. extractBasis( xAxis, yAxis, zAxis ) {
  7753. if ( this.determinant() === 0 ) {
  7754. xAxis.set( 1, 0, 0 );
  7755. yAxis.set( 0, 1, 0 );
  7756. zAxis.set( 0, 0, 1 );
  7757. return this;
  7758. }
  7759. xAxis.setFromMatrixColumn( this, 0 );
  7760. yAxis.setFromMatrixColumn( this, 1 );
  7761. zAxis.setFromMatrixColumn( this, 2 );
  7762. return this;
  7763. }
  7764. /**
  7765. * Sets the given basis vectors to this matrix.
  7766. *
  7767. * @param {Vector3} xAxis - The basis's x axis.
  7768. * @param {Vector3} yAxis - The basis's y axis.
  7769. * @param {Vector3} zAxis - The basis's z axis.
  7770. * @return {Matrix4} A reference to this matrix.
  7771. */
  7772. makeBasis( xAxis, yAxis, zAxis ) {
  7773. this.set(
  7774. xAxis.x, yAxis.x, zAxis.x, 0,
  7775. xAxis.y, yAxis.y, zAxis.y, 0,
  7776. xAxis.z, yAxis.z, zAxis.z, 0,
  7777. 0, 0, 0, 1
  7778. );
  7779. return this;
  7780. }
  7781. /**
  7782. * Extracts the rotation component of the given matrix
  7783. * into this matrix's rotation component.
  7784. *
  7785. * Note: This method does not support reflection matrices.
  7786. *
  7787. * @param {Matrix4} m - The matrix.
  7788. * @return {Matrix4} A reference to this matrix.
  7789. */
  7790. extractRotation( m ) {
  7791. if ( m.determinant() === 0 ) {
  7792. return this.identity();
  7793. }
  7794. const te = this.elements;
  7795. const me = m.elements;
  7796. const scaleX = 1 / _v1$7.setFromMatrixColumn( m, 0 ).length();
  7797. const scaleY = 1 / _v1$7.setFromMatrixColumn( m, 1 ).length();
  7798. const scaleZ = 1 / _v1$7.setFromMatrixColumn( m, 2 ).length();
  7799. te[ 0 ] = me[ 0 ] * scaleX;
  7800. te[ 1 ] = me[ 1 ] * scaleX;
  7801. te[ 2 ] = me[ 2 ] * scaleX;
  7802. te[ 3 ] = 0;
  7803. te[ 4 ] = me[ 4 ] * scaleY;
  7804. te[ 5 ] = me[ 5 ] * scaleY;
  7805. te[ 6 ] = me[ 6 ] * scaleY;
  7806. te[ 7 ] = 0;
  7807. te[ 8 ] = me[ 8 ] * scaleZ;
  7808. te[ 9 ] = me[ 9 ] * scaleZ;
  7809. te[ 10 ] = me[ 10 ] * scaleZ;
  7810. te[ 11 ] = 0;
  7811. te[ 12 ] = 0;
  7812. te[ 13 ] = 0;
  7813. te[ 14 ] = 0;
  7814. te[ 15 ] = 1;
  7815. return this;
  7816. }
  7817. /**
  7818. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  7819. * the rotation specified by the given Euler angles. The rest of
  7820. * the matrix is set to the identity. Depending on the {@link Euler#order},
  7821. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  7822. * for a complete list.
  7823. *
  7824. * @param {Euler} euler - The Euler angles.
  7825. * @return {Matrix4} A reference to this matrix.
  7826. */
  7827. makeRotationFromEuler( euler ) {
  7828. const te = this.elements;
  7829. const x = euler.x, y = euler.y, z = euler.z;
  7830. const a = Math.cos( x ), b = Math.sin( x );
  7831. const c = Math.cos( y ), d = Math.sin( y );
  7832. const e = Math.cos( z ), f = Math.sin( z );
  7833. if ( euler.order === 'XYZ' ) {
  7834. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  7835. te[ 0 ] = c * e;
  7836. te[ 4 ] = - c * f;
  7837. te[ 8 ] = d;
  7838. te[ 1 ] = af + be * d;
  7839. te[ 5 ] = ae - bf * d;
  7840. te[ 9 ] = - b * c;
  7841. te[ 2 ] = bf - ae * d;
  7842. te[ 6 ] = be + af * d;
  7843. te[ 10 ] = a * c;
  7844. } else if ( euler.order === 'YXZ' ) {
  7845. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  7846. te[ 0 ] = ce + df * b;
  7847. te[ 4 ] = de * b - cf;
  7848. te[ 8 ] = a * d;
  7849. te[ 1 ] = a * f;
  7850. te[ 5 ] = a * e;
  7851. te[ 9 ] = - b;
  7852. te[ 2 ] = cf * b - de;
  7853. te[ 6 ] = df + ce * b;
  7854. te[ 10 ] = a * c;
  7855. } else if ( euler.order === 'ZXY' ) {
  7856. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  7857. te[ 0 ] = ce - df * b;
  7858. te[ 4 ] = - a * f;
  7859. te[ 8 ] = de + cf * b;
  7860. te[ 1 ] = cf + de * b;
  7861. te[ 5 ] = a * e;
  7862. te[ 9 ] = df - ce * b;
  7863. te[ 2 ] = - a * d;
  7864. te[ 6 ] = b;
  7865. te[ 10 ] = a * c;
  7866. } else if ( euler.order === 'ZYX' ) {
  7867. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  7868. te[ 0 ] = c * e;
  7869. te[ 4 ] = be * d - af;
  7870. te[ 8 ] = ae * d + bf;
  7871. te[ 1 ] = c * f;
  7872. te[ 5 ] = bf * d + ae;
  7873. te[ 9 ] = af * d - be;
  7874. te[ 2 ] = - d;
  7875. te[ 6 ] = b * c;
  7876. te[ 10 ] = a * c;
  7877. } else if ( euler.order === 'YZX' ) {
  7878. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  7879. te[ 0 ] = c * e;
  7880. te[ 4 ] = bd - ac * f;
  7881. te[ 8 ] = bc * f + ad;
  7882. te[ 1 ] = f;
  7883. te[ 5 ] = a * e;
  7884. te[ 9 ] = - b * e;
  7885. te[ 2 ] = - d * e;
  7886. te[ 6 ] = ad * f + bc;
  7887. te[ 10 ] = ac - bd * f;
  7888. } else if ( euler.order === 'XZY' ) {
  7889. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  7890. te[ 0 ] = c * e;
  7891. te[ 4 ] = - f;
  7892. te[ 8 ] = d * e;
  7893. te[ 1 ] = ac * f + bd;
  7894. te[ 5 ] = a * e;
  7895. te[ 9 ] = ad * f - bc;
  7896. te[ 2 ] = bc * f - ad;
  7897. te[ 6 ] = b * e;
  7898. te[ 10 ] = bd * f + ac;
  7899. }
  7900. // bottom row
  7901. te[ 3 ] = 0;
  7902. te[ 7 ] = 0;
  7903. te[ 11 ] = 0;
  7904. // last column
  7905. te[ 12 ] = 0;
  7906. te[ 13 ] = 0;
  7907. te[ 14 ] = 0;
  7908. te[ 15 ] = 1;
  7909. return this;
  7910. }
  7911. /**
  7912. * Sets the rotation component of this matrix to the rotation specified by
  7913. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  7914. * The rest of the matrix is set to the identity.
  7915. *
  7916. * @param {Quaternion} q - The Quaternion.
  7917. * @return {Matrix4} A reference to this matrix.
  7918. */
  7919. makeRotationFromQuaternion( q ) {
  7920. return this.compose( _zero, q, _one );
  7921. }
  7922. /**
  7923. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  7924. * `target`, and oriented by the up-direction.
  7925. *
  7926. * @param {Vector3} eye - The eye vector.
  7927. * @param {Vector3} target - The target vector.
  7928. * @param {Vector3} up - The up vector.
  7929. * @return {Matrix4} A reference to this matrix.
  7930. */
  7931. lookAt( eye, target, up ) {
  7932. const te = this.elements;
  7933. _z.subVectors( eye, target );
  7934. if ( _z.lengthSq() === 0 ) {
  7935. // eye and target are in the same position
  7936. _z.z = 1;
  7937. }
  7938. _z.normalize();
  7939. _x.crossVectors( up, _z );
  7940. if ( _x.lengthSq() === 0 ) {
  7941. // up and z are parallel
  7942. if ( Math.abs( up.z ) === 1 ) {
  7943. _z.x += 0.0001;
  7944. } else {
  7945. _z.z += 0.0001;
  7946. }
  7947. _z.normalize();
  7948. _x.crossVectors( up, _z );
  7949. }
  7950. _x.normalize();
  7951. _y.crossVectors( _z, _x );
  7952. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  7953. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  7954. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  7955. return this;
  7956. }
  7957. /**
  7958. * Post-multiplies this matrix by the given 4x4 matrix.
  7959. *
  7960. * @param {Matrix4} m - The matrix to multiply with.
  7961. * @return {Matrix4} A reference to this matrix.
  7962. */
  7963. multiply( m ) {
  7964. return this.multiplyMatrices( this, m );
  7965. }
  7966. /**
  7967. * Pre-multiplies this matrix by the given 4x4 matrix.
  7968. *
  7969. * @param {Matrix4} m - The matrix to multiply with.
  7970. * @return {Matrix4} A reference to this matrix.
  7971. */
  7972. premultiply( m ) {
  7973. return this.multiplyMatrices( m, this );
  7974. }
  7975. /**
  7976. * Multiples the given 4x4 matrices and stores the result
  7977. * in this matrix.
  7978. *
  7979. * @param {Matrix4} a - The first matrix.
  7980. * @param {Matrix4} b - The second matrix.
  7981. * @return {Matrix4} A reference to this matrix.
  7982. */
  7983. multiplyMatrices( a, b ) {
  7984. const ae = a.elements;
  7985. const be = b.elements;
  7986. const te = this.elements;
  7987. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  7988. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  7989. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  7990. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  7991. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  7992. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  7993. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  7994. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  7995. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  7996. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  7997. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  7998. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  7999. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  8000. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  8001. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  8002. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  8003. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  8004. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  8005. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  8006. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  8007. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  8008. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  8009. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  8010. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  8011. return this;
  8012. }
  8013. /**
  8014. * Multiplies every component of the matrix by the given scalar.
  8015. *
  8016. * @param {number} s - The scalar.
  8017. * @return {Matrix4} A reference to this matrix.
  8018. */
  8019. multiplyScalar( s ) {
  8020. const te = this.elements;
  8021. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  8022. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  8023. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  8024. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  8025. return this;
  8026. }
  8027. /**
  8028. * Computes and returns the determinant of this matrix.
  8029. *
  8030. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  8031. *
  8032. * @return {number} The determinant.
  8033. */
  8034. determinant() {
  8035. const te = this.elements;
  8036. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  8037. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  8038. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  8039. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  8040. const t11 = n23 * n34 - n24 * n33;
  8041. const t12 = n22 * n34 - n24 * n32;
  8042. const t13 = n22 * n33 - n23 * n32;
  8043. const t21 = n21 * n34 - n24 * n31;
  8044. const t22 = n21 * n33 - n23 * n31;
  8045. const t23 = n21 * n32 - n22 * n31;
  8046. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  8047. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  8048. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  8049. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  8050. }
  8051. /**
  8052. * Transposes this matrix in place.
  8053. *
  8054. * @return {Matrix4} A reference to this matrix.
  8055. */
  8056. transpose() {
  8057. const te = this.elements;
  8058. let tmp;
  8059. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  8060. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  8061. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  8062. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  8063. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  8064. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  8065. return this;
  8066. }
  8067. /**
  8068. * Sets the position component for this matrix from the given vector,
  8069. * without affecting the rest of the matrix.
  8070. *
  8071. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  8072. * @param {number} y - The y component of the vector.
  8073. * @param {number} z - The z component of the vector.
  8074. * @return {Matrix4} A reference to this matrix.
  8075. */
  8076. setPosition( x, y, z ) {
  8077. const te = this.elements;
  8078. if ( x.isVector3 ) {
  8079. te[ 12 ] = x.x;
  8080. te[ 13 ] = x.y;
  8081. te[ 14 ] = x.z;
  8082. } else {
  8083. te[ 12 ] = x;
  8084. te[ 13 ] = y;
  8085. te[ 14 ] = z;
  8086. }
  8087. return this;
  8088. }
  8089. /**
  8090. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  8091. * You can not invert with a determinant of zero. If you attempt this, the method produces
  8092. * a zero matrix instead.
  8093. *
  8094. * @return {Matrix4} A reference to this matrix.
  8095. */
  8096. invert() {
  8097. // based on https://github.com/toji/gl-matrix
  8098. const te = this.elements,
  8099. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  8100. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  8101. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  8102. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  8103. t1 = n11 * n22 - n21 * n12,
  8104. t2 = n11 * n32 - n31 * n12,
  8105. t3 = n11 * n42 - n41 * n12,
  8106. t4 = n21 * n32 - n31 * n22,
  8107. t5 = n21 * n42 - n41 * n22,
  8108. t6 = n31 * n42 - n41 * n32,
  8109. t7 = n13 * n24 - n23 * n14,
  8110. t8 = n13 * n34 - n33 * n14,
  8111. t9 = n13 * n44 - n43 * n14,
  8112. t10 = n23 * n34 - n33 * n24,
  8113. t11 = n23 * n44 - n43 * n24,
  8114. t12 = n33 * n44 - n43 * n34;
  8115. const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7;
  8116. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  8117. const detInv = 1 / det;
  8118. te[ 0 ] = ( n22 * t12 - n32 * t11 + n42 * t10 ) * detInv;
  8119. te[ 1 ] = ( n31 * t11 - n21 * t12 - n41 * t10 ) * detInv;
  8120. te[ 2 ] = ( n24 * t6 - n34 * t5 + n44 * t4 ) * detInv;
  8121. te[ 3 ] = ( n33 * t5 - n23 * t6 - n43 * t4 ) * detInv;
  8122. te[ 4 ] = ( n32 * t9 - n12 * t12 - n42 * t8 ) * detInv;
  8123. te[ 5 ] = ( n11 * t12 - n31 * t9 + n41 * t8 ) * detInv;
  8124. te[ 6 ] = ( n34 * t3 - n14 * t6 - n44 * t2 ) * detInv;
  8125. te[ 7 ] = ( n13 * t6 - n33 * t3 + n43 * t2 ) * detInv;
  8126. te[ 8 ] = ( n12 * t11 - n22 * t9 + n42 * t7 ) * detInv;
  8127. te[ 9 ] = ( n21 * t9 - n11 * t11 - n41 * t7 ) * detInv;
  8128. te[ 10 ] = ( n14 * t5 - n24 * t3 + n44 * t1 ) * detInv;
  8129. te[ 11 ] = ( n23 * t3 - n13 * t5 - n43 * t1 ) * detInv;
  8130. te[ 12 ] = ( n22 * t8 - n12 * t10 - n32 * t7 ) * detInv;
  8131. te[ 13 ] = ( n11 * t10 - n21 * t8 + n31 * t7 ) * detInv;
  8132. te[ 14 ] = ( n24 * t2 - n14 * t4 - n34 * t1 ) * detInv;
  8133. te[ 15 ] = ( n13 * t4 - n23 * t2 + n33 * t1 ) * detInv;
  8134. return this;
  8135. }
  8136. /**
  8137. * Multiplies the columns of this matrix by the given vector.
  8138. *
  8139. * @param {Vector3} v - The scale vector.
  8140. * @return {Matrix4} A reference to this matrix.
  8141. */
  8142. scale( v ) {
  8143. const te = this.elements;
  8144. const x = v.x, y = v.y, z = v.z;
  8145. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  8146. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  8147. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  8148. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  8149. return this;
  8150. }
  8151. /**
  8152. * Gets the maximum scale value of the three axes.
  8153. *
  8154. * @return {number} The maximum scale.
  8155. */
  8156. getMaxScaleOnAxis() {
  8157. const te = this.elements;
  8158. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  8159. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  8160. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  8161. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  8162. }
  8163. /**
  8164. * Sets this matrix as a translation transform from the given vector.
  8165. *
  8166. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  8167. * @param {number} y - The amount to translate in the Y axis.
  8168. * @param {number} z - The amount to translate in the z axis.
  8169. * @return {Matrix4} A reference to this matrix.
  8170. */
  8171. makeTranslation( x, y, z ) {
  8172. if ( x.isVector3 ) {
  8173. this.set(
  8174. 1, 0, 0, x.x,
  8175. 0, 1, 0, x.y,
  8176. 0, 0, 1, x.z,
  8177. 0, 0, 0, 1
  8178. );
  8179. } else {
  8180. this.set(
  8181. 1, 0, 0, x,
  8182. 0, 1, 0, y,
  8183. 0, 0, 1, z,
  8184. 0, 0, 0, 1
  8185. );
  8186. }
  8187. return this;
  8188. }
  8189. /**
  8190. * Sets this matrix as a rotational transformation around the X axis by
  8191. * the given angle.
  8192. *
  8193. * @param {number} theta - The rotation in radians.
  8194. * @return {Matrix4} A reference to this matrix.
  8195. */
  8196. makeRotationX( theta ) {
  8197. const c = Math.cos( theta ), s = Math.sin( theta );
  8198. this.set(
  8199. 1, 0, 0, 0,
  8200. 0, c, - s, 0,
  8201. 0, s, c, 0,
  8202. 0, 0, 0, 1
  8203. );
  8204. return this;
  8205. }
  8206. /**
  8207. * Sets this matrix as a rotational transformation around the Y axis by
  8208. * the given angle.
  8209. *
  8210. * @param {number} theta - The rotation in radians.
  8211. * @return {Matrix4} A reference to this matrix.
  8212. */
  8213. makeRotationY( theta ) {
  8214. const c = Math.cos( theta ), s = Math.sin( theta );
  8215. this.set(
  8216. c, 0, s, 0,
  8217. 0, 1, 0, 0,
  8218. - s, 0, c, 0,
  8219. 0, 0, 0, 1
  8220. );
  8221. return this;
  8222. }
  8223. /**
  8224. * Sets this matrix as a rotational transformation around the Z axis by
  8225. * the given angle.
  8226. *
  8227. * @param {number} theta - The rotation in radians.
  8228. * @return {Matrix4} A reference to this matrix.
  8229. */
  8230. makeRotationZ( theta ) {
  8231. const c = Math.cos( theta ), s = Math.sin( theta );
  8232. this.set(
  8233. c, - s, 0, 0,
  8234. s, c, 0, 0,
  8235. 0, 0, 1, 0,
  8236. 0, 0, 0, 1
  8237. );
  8238. return this;
  8239. }
  8240. /**
  8241. * Sets this matrix as a rotational transformation around the given axis by
  8242. * the given angle.
  8243. *
  8244. * This is a somewhat controversial but mathematically sound alternative to
  8245. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  8246. *
  8247. * @param {Vector3} axis - The normalized rotation axis.
  8248. * @param {number} angle - The rotation in radians.
  8249. * @return {Matrix4} A reference to this matrix.
  8250. */
  8251. makeRotationAxis( axis, angle ) {
  8252. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  8253. const c = Math.cos( angle );
  8254. const s = Math.sin( angle );
  8255. const t = 1 - c;
  8256. const x = axis.x, y = axis.y, z = axis.z;
  8257. const tx = t * x, ty = t * y;
  8258. this.set(
  8259. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  8260. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  8261. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  8262. 0, 0, 0, 1
  8263. );
  8264. return this;
  8265. }
  8266. /**
  8267. * Sets this matrix as a scale transformation.
  8268. *
  8269. * @param {number} x - The amount to scale in the X axis.
  8270. * @param {number} y - The amount to scale in the Y axis.
  8271. * @param {number} z - The amount to scale in the Z axis.
  8272. * @return {Matrix4} A reference to this matrix.
  8273. */
  8274. makeScale( x, y, z ) {
  8275. this.set(
  8276. x, 0, 0, 0,
  8277. 0, y, 0, 0,
  8278. 0, 0, z, 0,
  8279. 0, 0, 0, 1
  8280. );
  8281. return this;
  8282. }
  8283. /**
  8284. * Sets this matrix as a shear transformation.
  8285. *
  8286. * @param {number} xy - The amount to shear X by Y.
  8287. * @param {number} xz - The amount to shear X by Z.
  8288. * @param {number} yx - The amount to shear Y by X.
  8289. * @param {number} yz - The amount to shear Y by Z.
  8290. * @param {number} zx - The amount to shear Z by X.
  8291. * @param {number} zy - The amount to shear Z by Y.
  8292. * @return {Matrix4} A reference to this matrix.
  8293. */
  8294. makeShear( xy, xz, yx, yz, zx, zy ) {
  8295. this.set(
  8296. 1, yx, zx, 0,
  8297. xy, 1, zy, 0,
  8298. xz, yz, 1, 0,
  8299. 0, 0, 0, 1
  8300. );
  8301. return this;
  8302. }
  8303. /**
  8304. * Sets this matrix to the transformation composed of the given position,
  8305. * rotation (Quaternion) and scale.
  8306. *
  8307. * @param {Vector3} position - The position vector.
  8308. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  8309. * @param {Vector3} scale - The scale vector.
  8310. * @return {Matrix4} A reference to this matrix.
  8311. */
  8312. compose( position, quaternion, scale ) {
  8313. const te = this.elements;
  8314. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  8315. const x2 = x + x, y2 = y + y, z2 = z + z;
  8316. const xx = x * x2, xy = x * y2, xz = x * z2;
  8317. const yy = y * y2, yz = y * z2, zz = z * z2;
  8318. const wx = w * x2, wy = w * y2, wz = w * z2;
  8319. const sx = scale.x, sy = scale.y, sz = scale.z;
  8320. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  8321. te[ 1 ] = ( xy + wz ) * sx;
  8322. te[ 2 ] = ( xz - wy ) * sx;
  8323. te[ 3 ] = 0;
  8324. te[ 4 ] = ( xy - wz ) * sy;
  8325. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  8326. te[ 6 ] = ( yz + wx ) * sy;
  8327. te[ 7 ] = 0;
  8328. te[ 8 ] = ( xz + wy ) * sz;
  8329. te[ 9 ] = ( yz - wx ) * sz;
  8330. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  8331. te[ 11 ] = 0;
  8332. te[ 12 ] = position.x;
  8333. te[ 13 ] = position.y;
  8334. te[ 14 ] = position.z;
  8335. te[ 15 ] = 1;
  8336. return this;
  8337. }
  8338. /**
  8339. * Decomposes this matrix into its position, rotation and scale components
  8340. * and provides the result in the given objects.
  8341. *
  8342. * Note: Not all matrices are decomposable in this way. For example, if an
  8343. * object has a non-uniformly scaled parent, then the object's world matrix
  8344. * may not be decomposable, and this method may not be appropriate.
  8345. *
  8346. * @param {Vector3} position - The position vector.
  8347. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  8348. * @param {Vector3} scale - The scale vector.
  8349. * @return {Matrix4} A reference to this matrix.
  8350. */
  8351. decompose( position, quaternion, scale ) {
  8352. const te = this.elements;
  8353. position.x = te[ 12 ];
  8354. position.y = te[ 13 ];
  8355. position.z = te[ 14 ];
  8356. const det = this.determinant();
  8357. if ( det === 0 ) {
  8358. scale.set( 1, 1, 1 );
  8359. quaternion.identity();
  8360. return this;
  8361. }
  8362. let sx = _v1$7.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  8363. const sy = _v1$7.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  8364. const sz = _v1$7.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  8365. // if determinant is negative, we need to invert one scale
  8366. if ( det < 0 ) sx = - sx;
  8367. // scale the rotation part
  8368. _m1$2.copy( this );
  8369. const invSX = 1 / sx;
  8370. const invSY = 1 / sy;
  8371. const invSZ = 1 / sz;
  8372. _m1$2.elements[ 0 ] *= invSX;
  8373. _m1$2.elements[ 1 ] *= invSX;
  8374. _m1$2.elements[ 2 ] *= invSX;
  8375. _m1$2.elements[ 4 ] *= invSY;
  8376. _m1$2.elements[ 5 ] *= invSY;
  8377. _m1$2.elements[ 6 ] *= invSY;
  8378. _m1$2.elements[ 8 ] *= invSZ;
  8379. _m1$2.elements[ 9 ] *= invSZ;
  8380. _m1$2.elements[ 10 ] *= invSZ;
  8381. quaternion.setFromRotationMatrix( _m1$2 );
  8382. scale.x = sx;
  8383. scale.y = sy;
  8384. scale.z = sz;
  8385. return this;
  8386. }
  8387. /**
  8388. * Creates a perspective projection matrix. This is used internally by
  8389. * {@link PerspectiveCamera#updateProjectionMatrix}.
  8390. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  8391. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  8392. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  8393. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  8394. * @param {number} near - The distance from the camera to the near plane.
  8395. * @param {number} far - The distance from the camera to the far plane.
  8396. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  8397. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  8398. * @return {Matrix4} A reference to this matrix.
  8399. */
  8400. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  8401. const te = this.elements;
  8402. const x = 2 * near / ( right - left );
  8403. const y = 2 * near / ( top - bottom );
  8404. const a = ( right + left ) / ( right - left );
  8405. const b = ( top + bottom ) / ( top - bottom );
  8406. let c, d;
  8407. if ( reversedDepth ) {
  8408. c = near / ( far - near );
  8409. d = ( far * near ) / ( far - near );
  8410. } else {
  8411. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8412. c = - ( far + near ) / ( far - near );
  8413. d = ( -2 * far * near ) / ( far - near );
  8414. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8415. c = - far / ( far - near );
  8416. d = ( - far * near ) / ( far - near );
  8417. } else {
  8418. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  8419. }
  8420. }
  8421. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  8422. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  8423. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8424. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  8425. return this;
  8426. }
  8427. /**
  8428. * Creates a orthographic projection matrix. This is used internally by
  8429. * {@link OrthographicCamera#updateProjectionMatrix}.
  8430. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  8431. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  8432. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  8433. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  8434. * @param {number} near - The distance from the camera to the near plane.
  8435. * @param {number} far - The distance from the camera to the far plane.
  8436. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  8437. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  8438. * @return {Matrix4} A reference to this matrix.
  8439. */
  8440. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  8441. const te = this.elements;
  8442. const x = 2 / ( right - left );
  8443. const y = 2 / ( top - bottom );
  8444. const a = - ( right + left ) / ( right - left );
  8445. const b = - ( top + bottom ) / ( top - bottom );
  8446. let c, d;
  8447. if ( reversedDepth ) {
  8448. c = 1 / ( far - near );
  8449. d = far / ( far - near );
  8450. } else {
  8451. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8452. c = -2 / ( far - near );
  8453. d = - ( far + near ) / ( far - near );
  8454. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8455. c = -1 / ( far - near );
  8456. d = - near / ( far - near );
  8457. } else {
  8458. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  8459. }
  8460. }
  8461. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  8462. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  8463. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8464. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  8465. return this;
  8466. }
  8467. /**
  8468. * Returns `true` if this matrix is equal with the given one.
  8469. *
  8470. * @param {Matrix4} matrix - The matrix to test for equality.
  8471. * @return {boolean} Whether this matrix is equal with the given one.
  8472. */
  8473. equals( matrix ) {
  8474. const te = this.elements;
  8475. const me = matrix.elements;
  8476. for ( let i = 0; i < 16; i ++ ) {
  8477. if ( te[ i ] !== me[ i ] ) return false;
  8478. }
  8479. return true;
  8480. }
  8481. /**
  8482. * Sets the elements of the matrix from the given array.
  8483. *
  8484. * @param {Array<number>} array - The matrix elements in column-major order.
  8485. * @param {number} [offset=0] - Index of the first element in the array.
  8486. * @return {Matrix4} A reference to this matrix.
  8487. */
  8488. fromArray( array, offset = 0 ) {
  8489. for ( let i = 0; i < 16; i ++ ) {
  8490. this.elements[ i ] = array[ i + offset ];
  8491. }
  8492. return this;
  8493. }
  8494. /**
  8495. * Writes the elements of this matrix to the given array. If no array is provided,
  8496. * the method returns a new instance.
  8497. *
  8498. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  8499. * @param {number} [offset=0] - Index of the first element in the array.
  8500. * @return {Array<number>} The matrix elements in column-major order.
  8501. */
  8502. toArray( array = [], offset = 0 ) {
  8503. const te = this.elements;
  8504. array[ offset ] = te[ 0 ];
  8505. array[ offset + 1 ] = te[ 1 ];
  8506. array[ offset + 2 ] = te[ 2 ];
  8507. array[ offset + 3 ] = te[ 3 ];
  8508. array[ offset + 4 ] = te[ 4 ];
  8509. array[ offset + 5 ] = te[ 5 ];
  8510. array[ offset + 6 ] = te[ 6 ];
  8511. array[ offset + 7 ] = te[ 7 ];
  8512. array[ offset + 8 ] = te[ 8 ];
  8513. array[ offset + 9 ] = te[ 9 ];
  8514. array[ offset + 10 ] = te[ 10 ];
  8515. array[ offset + 11 ] = te[ 11 ];
  8516. array[ offset + 12 ] = te[ 12 ];
  8517. array[ offset + 13 ] = te[ 13 ];
  8518. array[ offset + 14 ] = te[ 14 ];
  8519. array[ offset + 15 ] = te[ 15 ];
  8520. return array;
  8521. }
  8522. }
  8523. const _v1$7 = /*@__PURE__*/ new Vector3();
  8524. const _m1$2 = /*@__PURE__*/ new Matrix4();
  8525. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  8526. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  8527. const _x = /*@__PURE__*/ new Vector3();
  8528. const _y = /*@__PURE__*/ new Vector3();
  8529. const _z = /*@__PURE__*/ new Vector3();
  8530. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  8531. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  8532. /**
  8533. * A class representing Euler angles.
  8534. *
  8535. * Euler angles describe a rotational transformation by rotating an object on
  8536. * its various axes in specified amounts per axis, and a specified axis
  8537. * order.
  8538. *
  8539. * Iterating through an instance will yield its components (x, y, z,
  8540. * order) in the corresponding order.
  8541. *
  8542. * ```js
  8543. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  8544. * const b = new THREE.Vector3( 1, 0, 1 );
  8545. * b.applyEuler(a);
  8546. * ```
  8547. */
  8548. class Euler {
  8549. /**
  8550. * Constructs a new euler instance.
  8551. *
  8552. * @param {number} [x=0] - The angle of the x axis in radians.
  8553. * @param {number} [y=0] - The angle of the y axis in radians.
  8554. * @param {number} [z=0] - The angle of the z axis in radians.
  8555. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  8556. */
  8557. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  8558. /**
  8559. * This flag can be used for type testing.
  8560. *
  8561. * @type {boolean}
  8562. * @readonly
  8563. * @default true
  8564. */
  8565. this.isEuler = true;
  8566. this._x = x;
  8567. this._y = y;
  8568. this._z = z;
  8569. this._order = order;
  8570. }
  8571. /**
  8572. * The angle of the x axis in radians.
  8573. *
  8574. * @type {number}
  8575. * @default 0
  8576. */
  8577. get x() {
  8578. return this._x;
  8579. }
  8580. set x( value ) {
  8581. this._x = value;
  8582. this._onChangeCallback();
  8583. }
  8584. /**
  8585. * The angle of the y axis in radians.
  8586. *
  8587. * @type {number}
  8588. * @default 0
  8589. */
  8590. get y() {
  8591. return this._y;
  8592. }
  8593. set y( value ) {
  8594. this._y = value;
  8595. this._onChangeCallback();
  8596. }
  8597. /**
  8598. * The angle of the z axis in radians.
  8599. *
  8600. * @type {number}
  8601. * @default 0
  8602. */
  8603. get z() {
  8604. return this._z;
  8605. }
  8606. set z( value ) {
  8607. this._z = value;
  8608. this._onChangeCallback();
  8609. }
  8610. /**
  8611. * A string representing the order that the rotations are applied.
  8612. *
  8613. * @type {string}
  8614. * @default 'XYZ'
  8615. */
  8616. get order() {
  8617. return this._order;
  8618. }
  8619. set order( value ) {
  8620. this._order = value;
  8621. this._onChangeCallback();
  8622. }
  8623. /**
  8624. * Sets the Euler components.
  8625. *
  8626. * @param {number} x - The angle of the x axis in radians.
  8627. * @param {number} y - The angle of the y axis in radians.
  8628. * @param {number} z - The angle of the z axis in radians.
  8629. * @param {string} [order] - A string representing the order that the rotations are applied.
  8630. * @return {Euler} A reference to this Euler instance.
  8631. */
  8632. set( x, y, z, order = this._order ) {
  8633. this._x = x;
  8634. this._y = y;
  8635. this._z = z;
  8636. this._order = order;
  8637. this._onChangeCallback();
  8638. return this;
  8639. }
  8640. /**
  8641. * Returns a new Euler instance with copied values from this instance.
  8642. *
  8643. * @return {Euler} A clone of this instance.
  8644. */
  8645. clone() {
  8646. return new this.constructor( this._x, this._y, this._z, this._order );
  8647. }
  8648. /**
  8649. * Copies the values of the given Euler instance to this instance.
  8650. *
  8651. * @param {Euler} euler - The Euler instance to copy.
  8652. * @return {Euler} A reference to this Euler instance.
  8653. */
  8654. copy( euler ) {
  8655. this._x = euler._x;
  8656. this._y = euler._y;
  8657. this._z = euler._z;
  8658. this._order = euler._order;
  8659. this._onChangeCallback();
  8660. return this;
  8661. }
  8662. /**
  8663. * Sets the angles of this Euler instance from a pure rotation matrix.
  8664. *
  8665. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  8666. * @param {string} [order] - A string representing the order that the rotations are applied.
  8667. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  8668. * @return {Euler} A reference to this Euler instance.
  8669. */
  8670. setFromRotationMatrix( m, order = this._order, update = true ) {
  8671. const te = m.elements;
  8672. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  8673. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  8674. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  8675. switch ( order ) {
  8676. case 'XYZ':
  8677. this._y = Math.asin( clamp( m13, -1, 1 ) );
  8678. if ( Math.abs( m13 ) < 0.9999999 ) {
  8679. this._x = Math.atan2( - m23, m33 );
  8680. this._z = Math.atan2( - m12, m11 );
  8681. } else {
  8682. this._x = Math.atan2( m32, m22 );
  8683. this._z = 0;
  8684. }
  8685. break;
  8686. case 'YXZ':
  8687. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  8688. if ( Math.abs( m23 ) < 0.9999999 ) {
  8689. this._y = Math.atan2( m13, m33 );
  8690. this._z = Math.atan2( m21, m22 );
  8691. } else {
  8692. this._y = Math.atan2( - m31, m11 );
  8693. this._z = 0;
  8694. }
  8695. break;
  8696. case 'ZXY':
  8697. this._x = Math.asin( clamp( m32, -1, 1 ) );
  8698. if ( Math.abs( m32 ) < 0.9999999 ) {
  8699. this._y = Math.atan2( - m31, m33 );
  8700. this._z = Math.atan2( - m12, m22 );
  8701. } else {
  8702. this._y = 0;
  8703. this._z = Math.atan2( m21, m11 );
  8704. }
  8705. break;
  8706. case 'ZYX':
  8707. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  8708. if ( Math.abs( m31 ) < 0.9999999 ) {
  8709. this._x = Math.atan2( m32, m33 );
  8710. this._z = Math.atan2( m21, m11 );
  8711. } else {
  8712. this._x = 0;
  8713. this._z = Math.atan2( - m12, m22 );
  8714. }
  8715. break;
  8716. case 'YZX':
  8717. this._z = Math.asin( clamp( m21, -1, 1 ) );
  8718. if ( Math.abs( m21 ) < 0.9999999 ) {
  8719. this._x = Math.atan2( - m23, m22 );
  8720. this._y = Math.atan2( - m31, m11 );
  8721. } else {
  8722. this._x = 0;
  8723. this._y = Math.atan2( m13, m33 );
  8724. }
  8725. break;
  8726. case 'XZY':
  8727. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  8728. if ( Math.abs( m12 ) < 0.9999999 ) {
  8729. this._x = Math.atan2( m32, m22 );
  8730. this._y = Math.atan2( m13, m11 );
  8731. } else {
  8732. this._x = Math.atan2( - m23, m33 );
  8733. this._y = 0;
  8734. }
  8735. break;
  8736. default:
  8737. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  8738. }
  8739. this._order = order;
  8740. if ( update === true ) this._onChangeCallback();
  8741. return this;
  8742. }
  8743. /**
  8744. * Sets the angles of this Euler instance from a normalized quaternion.
  8745. *
  8746. * @param {Quaternion} q - A normalized Quaternion.
  8747. * @param {string} [order] - A string representing the order that the rotations are applied.
  8748. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  8749. * @return {Euler} A reference to this Euler instance.
  8750. */
  8751. setFromQuaternion( q, order, update ) {
  8752. _matrix$2.makeRotationFromQuaternion( q );
  8753. return this.setFromRotationMatrix( _matrix$2, order, update );
  8754. }
  8755. /**
  8756. * Sets the angles of this Euler instance from the given vector.
  8757. *
  8758. * @param {Vector3} v - The vector.
  8759. * @param {string} [order] - A string representing the order that the rotations are applied.
  8760. * @return {Euler} A reference to this Euler instance.
  8761. */
  8762. setFromVector3( v, order = this._order ) {
  8763. return this.set( v.x, v.y, v.z, order );
  8764. }
  8765. /**
  8766. * Resets the euler angle with a new order by creating a quaternion from this
  8767. * euler angle and then setting this euler angle with the quaternion and the
  8768. * new order.
  8769. *
  8770. * Warning: This discards revolution information.
  8771. *
  8772. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  8773. * @return {Euler} A reference to this Euler instance.
  8774. */
  8775. reorder( newOrder ) {
  8776. _quaternion$4.setFromEuler( this );
  8777. return this.setFromQuaternion( _quaternion$4, newOrder );
  8778. }
  8779. /**
  8780. * Returns `true` if this Euler instance is equal with the given one.
  8781. *
  8782. * @param {Euler} euler - The Euler instance to test for equality.
  8783. * @return {boolean} Whether this Euler instance is equal with the given one.
  8784. */
  8785. equals( euler ) {
  8786. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  8787. }
  8788. /**
  8789. * Sets this Euler instance's components to values from the given array. The first three
  8790. * entries of the array are assign to the x,y and z components. An optional fourth entry
  8791. * defines the Euler order.
  8792. *
  8793. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  8794. * @return {Euler} A reference to this Euler instance.
  8795. */
  8796. fromArray( array ) {
  8797. this._x = array[ 0 ];
  8798. this._y = array[ 1 ];
  8799. this._z = array[ 2 ];
  8800. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  8801. this._onChangeCallback();
  8802. return this;
  8803. }
  8804. /**
  8805. * Writes the components of this Euler instance to the given array. If no array is provided,
  8806. * the method returns a new instance.
  8807. *
  8808. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  8809. * @param {number} [offset=0] - Index of the first element in the array.
  8810. * @return {Array<number,number,number,string>} The Euler components.
  8811. */
  8812. toArray( array = [], offset = 0 ) {
  8813. array[ offset ] = this._x;
  8814. array[ offset + 1 ] = this._y;
  8815. array[ offset + 2 ] = this._z;
  8816. array[ offset + 3 ] = this._order;
  8817. return array;
  8818. }
  8819. _onChange( callback ) {
  8820. this._onChangeCallback = callback;
  8821. return this;
  8822. }
  8823. _onChangeCallback() {}
  8824. *[ Symbol.iterator ]() {
  8825. yield this._x;
  8826. yield this._y;
  8827. yield this._z;
  8828. yield this._order;
  8829. }
  8830. }
  8831. /**
  8832. * The default Euler angle order.
  8833. *
  8834. * @static
  8835. * @type {string}
  8836. * @default 'XYZ'
  8837. */
  8838. Euler.DEFAULT_ORDER = 'XYZ';
  8839. /**
  8840. * A layers object assigns an 3D object to 1 or more of 32
  8841. * layers numbered `0` to `31` - internally the layers are stored as a
  8842. * bit mask], and by default all 3D objects are a member of layer `0`.
  8843. *
  8844. * This can be used to control visibility - an object must share a layer with
  8845. * a camera to be visible when that camera's view is
  8846. * rendered.
  8847. *
  8848. * All classes that inherit from {@link Object3D} have an `layers` property which
  8849. * is an instance of this class.
  8850. */
  8851. class Layers {
  8852. /**
  8853. * Constructs a new layers instance, with membership
  8854. * initially set to layer `0`.
  8855. */
  8856. constructor() {
  8857. /**
  8858. * A bit mask storing which of the 32 layers this layers object is currently
  8859. * a member of.
  8860. *
  8861. * @type {number}
  8862. */
  8863. this.mask = 1 | 0;
  8864. }
  8865. /**
  8866. * Sets membership to the given layer, and remove membership all other layers.
  8867. *
  8868. * @param {number} layer - The layer to set.
  8869. */
  8870. set( layer ) {
  8871. this.mask = ( 1 << layer | 0 ) >>> 0;
  8872. }
  8873. /**
  8874. * Adds membership of the given layer.
  8875. *
  8876. * @param {number} layer - The layer to enable.
  8877. */
  8878. enable( layer ) {
  8879. this.mask |= 1 << layer | 0;
  8880. }
  8881. /**
  8882. * Adds membership to all layers.
  8883. */
  8884. enableAll() {
  8885. this.mask = 0xffffffff | 0;
  8886. }
  8887. /**
  8888. * Toggles the membership of the given layer.
  8889. *
  8890. * @param {number} layer - The layer to toggle.
  8891. */
  8892. toggle( layer ) {
  8893. this.mask ^= 1 << layer | 0;
  8894. }
  8895. /**
  8896. * Removes membership of the given layer.
  8897. *
  8898. * @param {number} layer - The layer to enable.
  8899. */
  8900. disable( layer ) {
  8901. this.mask &= ~ ( 1 << layer | 0 );
  8902. }
  8903. /**
  8904. * Removes the membership from all layers.
  8905. */
  8906. disableAll() {
  8907. this.mask = 0;
  8908. }
  8909. /**
  8910. * Returns `true` if this and the given layers object have at least one
  8911. * layer in common.
  8912. *
  8913. * @param {Layers} layers - The layers to test.
  8914. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  8915. */
  8916. test( layers ) {
  8917. return ( this.mask & layers.mask ) !== 0;
  8918. }
  8919. /**
  8920. * Returns `true` if the given layer is enabled.
  8921. *
  8922. * @param {number} layer - The layer to test.
  8923. * @return {boolean } Whether the given layer is enabled or not.
  8924. */
  8925. isEnabled( layer ) {
  8926. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  8927. }
  8928. }
  8929. let _object3DId = 0;
  8930. const _v1$6 = /*@__PURE__*/ new Vector3();
  8931. const _q1 = /*@__PURE__*/ new Quaternion();
  8932. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8933. const _target = /*@__PURE__*/ new Vector3();
  8934. const _position$4 = /*@__PURE__*/ new Vector3();
  8935. const _scale$3 = /*@__PURE__*/ new Vector3();
  8936. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  8937. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  8938. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  8939. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  8940. /**
  8941. * Fires when the object has been added to its parent object.
  8942. *
  8943. * @event Object3D#added
  8944. * @type {Object}
  8945. */
  8946. const _addedEvent = { type: 'added' };
  8947. /**
  8948. * Fires when the object has been removed from its parent object.
  8949. *
  8950. * @event Object3D#removed
  8951. * @type {Object}
  8952. */
  8953. const _removedEvent = { type: 'removed' };
  8954. /**
  8955. * Fires when a new child object has been added.
  8956. *
  8957. * @event Object3D#childadded
  8958. * @type {Object}
  8959. */
  8960. const _childaddedEvent = { type: 'childadded', child: null };
  8961. /**
  8962. * Fires when a child object has been removed.
  8963. *
  8964. * @event Object3D#childremoved
  8965. * @type {Object}
  8966. */
  8967. const _childremovedEvent = { type: 'childremoved', child: null };
  8968. /**
  8969. * This is the base class for most objects in three.js and provides a set of
  8970. * properties and methods for manipulating objects in 3D space.
  8971. *
  8972. * @augments EventDispatcher
  8973. */
  8974. class Object3D extends EventDispatcher {
  8975. /**
  8976. * Constructs a new 3D object.
  8977. */
  8978. constructor() {
  8979. super();
  8980. /**
  8981. * This flag can be used for type testing.
  8982. *
  8983. * @type {boolean}
  8984. * @readonly
  8985. * @default true
  8986. */
  8987. this.isObject3D = true;
  8988. /**
  8989. * The ID of the 3D object.
  8990. *
  8991. * @name Object3D#id
  8992. * @type {number}
  8993. * @readonly
  8994. */
  8995. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  8996. /**
  8997. * The UUID of the 3D object.
  8998. *
  8999. * @type {string}
  9000. * @readonly
  9001. */
  9002. this.uuid = generateUUID();
  9003. /**
  9004. * The name of the 3D object.
  9005. *
  9006. * @type {string}
  9007. */
  9008. this.name = '';
  9009. /**
  9010. * The type property is used for detecting the object type
  9011. * in context of serialization/deserialization.
  9012. *
  9013. * @type {string}
  9014. * @readonly
  9015. */
  9016. this.type = 'Object3D';
  9017. /**
  9018. * A reference to the parent object.
  9019. *
  9020. * @type {?Object3D}
  9021. * @default null
  9022. */
  9023. this.parent = null;
  9024. /**
  9025. * An array holding the child 3D objects of this instance.
  9026. *
  9027. * @type {Array<Object3D>}
  9028. */
  9029. this.children = [];
  9030. /**
  9031. * Defines the `up` direction of the 3D object which influences
  9032. * the orientation via methods like {@link Object3D#lookAt}.
  9033. *
  9034. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  9035. *
  9036. * @type {Vector3}
  9037. */
  9038. this.up = Object3D.DEFAULT_UP.clone();
  9039. const position = new Vector3();
  9040. const rotation = new Euler();
  9041. const quaternion = new Quaternion();
  9042. const scale = new Vector3( 1, 1, 1 );
  9043. function onRotationChange() {
  9044. quaternion.setFromEuler( rotation, false );
  9045. }
  9046. function onQuaternionChange() {
  9047. rotation.setFromQuaternion( quaternion, undefined, false );
  9048. }
  9049. rotation._onChange( onRotationChange );
  9050. quaternion._onChange( onQuaternionChange );
  9051. Object.defineProperties( this, {
  9052. /**
  9053. * Represents the object's local position.
  9054. *
  9055. * @name Object3D#position
  9056. * @type {Vector3}
  9057. * @default (0,0,0)
  9058. */
  9059. position: {
  9060. configurable: true,
  9061. enumerable: true,
  9062. value: position
  9063. },
  9064. /**
  9065. * Represents the object's local rotation as Euler angles, in radians.
  9066. *
  9067. * @name Object3D#rotation
  9068. * @type {Euler}
  9069. * @default (0,0,0)
  9070. */
  9071. rotation: {
  9072. configurable: true,
  9073. enumerable: true,
  9074. value: rotation
  9075. },
  9076. /**
  9077. * Represents the object's local rotation as Quaternions.
  9078. *
  9079. * @name Object3D#quaternion
  9080. * @type {Quaternion}
  9081. */
  9082. quaternion: {
  9083. configurable: true,
  9084. enumerable: true,
  9085. value: quaternion
  9086. },
  9087. /**
  9088. * Represents the object's local scale.
  9089. *
  9090. * @name Object3D#scale
  9091. * @type {Vector3}
  9092. * @default (1,1,1)
  9093. */
  9094. scale: {
  9095. configurable: true,
  9096. enumerable: true,
  9097. value: scale
  9098. },
  9099. /**
  9100. * Represents the object's model-view matrix.
  9101. *
  9102. * @name Object3D#modelViewMatrix
  9103. * @type {Matrix4}
  9104. */
  9105. modelViewMatrix: {
  9106. value: new Matrix4()
  9107. },
  9108. /**
  9109. * Represents the object's normal matrix.
  9110. *
  9111. * @name Object3D#normalMatrix
  9112. * @type {Matrix3}
  9113. */
  9114. normalMatrix: {
  9115. value: new Matrix3()
  9116. }
  9117. } );
  9118. /**
  9119. * Represents the object's transformation matrix in local space.
  9120. *
  9121. * @type {Matrix4}
  9122. */
  9123. this.matrix = new Matrix4();
  9124. /**
  9125. * Represents the object's transformation matrix in world space.
  9126. * If the 3D object has no parent, then it's identical to the local transformation matrix
  9127. *
  9128. * @type {Matrix4}
  9129. */
  9130. this.matrixWorld = new Matrix4();
  9131. /**
  9132. * When set to `true`, the engine automatically computes the local matrix from position,
  9133. * rotation and scale every frame. If set to `false`, the app is responsible for recomputing
  9134. * the local matrix by calling `updateMatrix()`.
  9135. *
  9136. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  9137. *
  9138. * @type {boolean}
  9139. * @default true
  9140. */
  9141. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  9142. /**
  9143. * When set to `true`, the engine automatically computes the world matrix from the current local
  9144. * matrix and the object's transformation hierarchy. If set to `false`, the app is responsible for
  9145. * recomputing the world matrix by directly updating the `matrixWorld` property.
  9146. *
  9147. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  9148. *
  9149. * @type {boolean}
  9150. * @default true
  9151. */
  9152. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  9153. /**
  9154. * When set to `true`, it calculates the world matrix in that frame and resets this property
  9155. * to `false`.
  9156. *
  9157. * @type {boolean}
  9158. * @default false
  9159. */
  9160. this.matrixWorldNeedsUpdate = false;
  9161. /**
  9162. * The layer membership of the 3D object. The 3D object is only visible if it has
  9163. * at least one layer in common with the camera in use. This property can also be
  9164. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  9165. *
  9166. * @type {Layers}
  9167. */
  9168. this.layers = new Layers();
  9169. /**
  9170. * When set to `true`, the 3D object gets rendered.
  9171. *
  9172. * @type {boolean}
  9173. * @default true
  9174. */
  9175. this.visible = true;
  9176. /**
  9177. * When set to `true`, the 3D object gets rendered into shadow maps.
  9178. *
  9179. * @type {boolean}
  9180. * @default false
  9181. */
  9182. this.castShadow = false;
  9183. /**
  9184. * When set to `true`, the 3D object is affected by shadows in the scene.
  9185. *
  9186. * @type {boolean}
  9187. * @default false
  9188. */
  9189. this.receiveShadow = false;
  9190. /**
  9191. * When set to `true`, the 3D object is honored by view frustum culling.
  9192. *
  9193. * @type {boolean}
  9194. * @default true
  9195. */
  9196. this.frustumCulled = true;
  9197. /**
  9198. * This value allows the default rendering order of scene graph objects to be
  9199. * overridden although opaque and transparent objects remain sorted independently.
  9200. * When this property is set for an instance of {@link Group},all descendants
  9201. * objects will be sorted and rendered together. Sorting is from lowest to highest
  9202. * render order.
  9203. *
  9204. * @type {number}
  9205. * @default 0
  9206. */
  9207. this.renderOrder = 0;
  9208. /**
  9209. * An array holding the animation clips of the 3D object.
  9210. *
  9211. * @type {Array<AnimationClip>}
  9212. */
  9213. this.animations = [];
  9214. /**
  9215. * Custom depth material to be used when rendering to the depth map. Can only be used
  9216. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  9217. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  9218. * material for proper shadows.
  9219. *
  9220. * Only relevant in context of {@link WebGLRenderer}.
  9221. *
  9222. * @type {(Material|undefined)}
  9223. * @default undefined
  9224. */
  9225. this.customDepthMaterial = undefined;
  9226. /**
  9227. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  9228. *
  9229. * Only relevant in context of {@link WebGLRenderer}.
  9230. *
  9231. * @type {(Material|undefined)}
  9232. * @default undefined
  9233. */
  9234. this.customDistanceMaterial = undefined;
  9235. /**
  9236. * Whether the 3D object is supposed to be static or not. If set to `true`, it means
  9237. * the 3D object is not going to be changed after the initial renderer. This includes
  9238. * geometry and material settings. A static 3D object can be processed by the renderer
  9239. * slightly faster since certain state checks can be bypassed.
  9240. *
  9241. * Only relevant in context of {@link WebGPURenderer}.
  9242. *
  9243. * @type {boolean}
  9244. * @default false
  9245. */
  9246. this.static = false;
  9247. /**
  9248. * An object that can be used to store custom data about the 3D object. It
  9249. * should not hold references to functions as these will not be cloned.
  9250. *
  9251. * @type {Object}
  9252. */
  9253. this.userData = {};
  9254. /**
  9255. * The pivot point for rotation and scale transformations.
  9256. * When set, rotation and scale are applied around this point
  9257. * instead of the object's origin.
  9258. *
  9259. * @type {?Vector3}
  9260. * @default null
  9261. */
  9262. this.pivot = null;
  9263. }
  9264. /**
  9265. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  9266. *
  9267. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9268. * @param {Object3D} object - The 3D object.
  9269. * @param {Camera} camera - The camera that is used to render the scene.
  9270. * @param {Camera} shadowCamera - The shadow camera.
  9271. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9272. * @param {Material} depthMaterial - The depth material.
  9273. * @param {Object} group - The geometry group data.
  9274. */
  9275. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  9276. /**
  9277. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  9278. *
  9279. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9280. * @param {Object3D} object - The 3D object.
  9281. * @param {Camera} camera - The camera that is used to render the scene.
  9282. * @param {Camera} shadowCamera - The shadow camera.
  9283. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9284. * @param {Material} depthMaterial - The depth material.
  9285. * @param {Object} group - The geometry group data.
  9286. */
  9287. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  9288. /**
  9289. * A callback that is executed immediately before a 3D object is rendered.
  9290. *
  9291. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9292. * @param {Object3D} object - The 3D object.
  9293. * @param {Camera} camera - The camera that is used to render the scene.
  9294. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9295. * @param {Material} material - The 3D object's material.
  9296. * @param {Object} group - The geometry group data.
  9297. */
  9298. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  9299. /**
  9300. * A callback that is executed immediately after a 3D object is rendered.
  9301. *
  9302. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9303. * @param {Object3D} object - The 3D object.
  9304. * @param {Camera} camera - The camera that is used to render the scene.
  9305. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9306. * @param {Material} material - The 3D object's material.
  9307. * @param {Object} group - The geometry group data.
  9308. */
  9309. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  9310. /**
  9311. * Applies the given transformation matrix to the object and updates the object's position,
  9312. * rotation and scale.
  9313. *
  9314. * @param {Matrix4} matrix - The transformation matrix.
  9315. */
  9316. applyMatrix4( matrix ) {
  9317. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9318. this.matrix.premultiply( matrix );
  9319. this.matrix.decompose( this.position, this.quaternion, this.scale );
  9320. }
  9321. /**
  9322. * Applies a rotation represented by given the quaternion to the 3D object.
  9323. *
  9324. * @param {Quaternion} q - The quaternion.
  9325. * @return {Object3D} A reference to this instance.
  9326. */
  9327. applyQuaternion( q ) {
  9328. this.quaternion.premultiply( q );
  9329. return this;
  9330. }
  9331. /**
  9332. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  9333. *
  9334. * @param {Vector3} axis - The (normalized) axis vector.
  9335. * @param {number} angle - The angle in radians.
  9336. */
  9337. setRotationFromAxisAngle( axis, angle ) {
  9338. // assumes axis is normalized
  9339. this.quaternion.setFromAxisAngle( axis, angle );
  9340. }
  9341. /**
  9342. * Sets the given rotation represented as Euler angles to the 3D object.
  9343. *
  9344. * @param {Euler} euler - The Euler angles.
  9345. */
  9346. setRotationFromEuler( euler ) {
  9347. this.quaternion.setFromEuler( euler, true );
  9348. }
  9349. /**
  9350. * Sets the given rotation represented as rotation matrix to the 3D object.
  9351. *
  9352. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  9353. * a pure rotation matrix (i.e, unscaled).
  9354. */
  9355. setRotationFromMatrix( m ) {
  9356. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9357. this.quaternion.setFromRotationMatrix( m );
  9358. }
  9359. /**
  9360. * Sets the given rotation represented as a Quaternion to the 3D object.
  9361. *
  9362. * @param {Quaternion} q - The Quaternion
  9363. */
  9364. setRotationFromQuaternion( q ) {
  9365. // assumes q is normalized
  9366. this.quaternion.copy( q );
  9367. }
  9368. /**
  9369. * Rotates the 3D object along an axis in local space.
  9370. *
  9371. * @param {Vector3} axis - The (normalized) axis vector.
  9372. * @param {number} angle - The angle in radians.
  9373. * @return {Object3D} A reference to this instance.
  9374. */
  9375. rotateOnAxis( axis, angle ) {
  9376. // rotate object on axis in object space
  9377. // axis is assumed to be normalized
  9378. _q1.setFromAxisAngle( axis, angle );
  9379. this.quaternion.multiply( _q1 );
  9380. return this;
  9381. }
  9382. /**
  9383. * Rotates the 3D object along an axis in world space.
  9384. *
  9385. * @param {Vector3} axis - The (normalized) axis vector.
  9386. * @param {number} angle - The angle in radians.
  9387. * @return {Object3D} A reference to this instance.
  9388. */
  9389. rotateOnWorldAxis( axis, angle ) {
  9390. // rotate object on axis in world space
  9391. // axis is assumed to be normalized
  9392. // method assumes no rotated parent
  9393. _q1.setFromAxisAngle( axis, angle );
  9394. this.quaternion.premultiply( _q1 );
  9395. return this;
  9396. }
  9397. /**
  9398. * Rotates the 3D object around its X axis in local space.
  9399. *
  9400. * @param {number} angle - The angle in radians.
  9401. * @return {Object3D} A reference to this instance.
  9402. */
  9403. rotateX( angle ) {
  9404. return this.rotateOnAxis( _xAxis, angle );
  9405. }
  9406. /**
  9407. * Rotates the 3D object around its Y axis in local space.
  9408. *
  9409. * @param {number} angle - The angle in radians.
  9410. * @return {Object3D} A reference to this instance.
  9411. */
  9412. rotateY( angle ) {
  9413. return this.rotateOnAxis( _yAxis, angle );
  9414. }
  9415. /**
  9416. * Rotates the 3D object around its Z axis in local space.
  9417. *
  9418. * @param {number} angle - The angle in radians.
  9419. * @return {Object3D} A reference to this instance.
  9420. */
  9421. rotateZ( angle ) {
  9422. return this.rotateOnAxis( _zAxis, angle );
  9423. }
  9424. /**
  9425. * Translate the 3D object by a distance along the given axis in local space.
  9426. *
  9427. * @param {Vector3} axis - The (normalized) axis vector.
  9428. * @param {number} distance - The distance in world units.
  9429. * @return {Object3D} A reference to this instance.
  9430. */
  9431. translateOnAxis( axis, distance ) {
  9432. // translate object by distance along axis in object space
  9433. // axis is assumed to be normalized
  9434. _v1$6.copy( axis ).applyQuaternion( this.quaternion );
  9435. this.position.add( _v1$6.multiplyScalar( distance ) );
  9436. return this;
  9437. }
  9438. /**
  9439. * Translate the 3D object by a distance along its X-axis in local space.
  9440. *
  9441. * @param {number} distance - The distance in world units.
  9442. * @return {Object3D} A reference to this instance.
  9443. */
  9444. translateX( distance ) {
  9445. return this.translateOnAxis( _xAxis, distance );
  9446. }
  9447. /**
  9448. * Translate the 3D object by a distance along its Y-axis in local space.
  9449. *
  9450. * @param {number} distance - The distance in world units.
  9451. * @return {Object3D} A reference to this instance.
  9452. */
  9453. translateY( distance ) {
  9454. return this.translateOnAxis( _yAxis, distance );
  9455. }
  9456. /**
  9457. * Translate the 3D object by a distance along its Z-axis in local space.
  9458. *
  9459. * @param {number} distance - The distance in world units.
  9460. * @return {Object3D} A reference to this instance.
  9461. */
  9462. translateZ( distance ) {
  9463. return this.translateOnAxis( _zAxis, distance );
  9464. }
  9465. /**
  9466. * Converts the given vector from this 3D object's local space to world space.
  9467. *
  9468. * @param {Vector3} vector - The vector to convert.
  9469. * @return {Vector3} The converted vector.
  9470. */
  9471. localToWorld( vector ) {
  9472. this.updateWorldMatrix( true, false );
  9473. return vector.applyMatrix4( this.matrixWorld );
  9474. }
  9475. /**
  9476. * Converts the given vector from this 3D object's world space to local space.
  9477. *
  9478. * @param {Vector3} vector - The vector to convert.
  9479. * @return {Vector3} The converted vector.
  9480. */
  9481. worldToLocal( vector ) {
  9482. this.updateWorldMatrix( true, false );
  9483. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  9484. }
  9485. /**
  9486. * Rotates the object to face a point in world space.
  9487. *
  9488. * This method does not support objects having non-uniformly-scaled parent(s).
  9489. *
  9490. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  9491. * @param {number} [y] - The y coordinate in world space.
  9492. * @param {number} [z] - The z coordinate in world space.
  9493. */
  9494. lookAt( x, y, z ) {
  9495. // This method does not support objects having non-uniformly-scaled parent(s)
  9496. if ( x.isVector3 ) {
  9497. _target.copy( x );
  9498. } else {
  9499. _target.set( x, y, z );
  9500. }
  9501. const parent = this.parent;
  9502. this.updateWorldMatrix( true, false );
  9503. _position$4.setFromMatrixPosition( this.matrixWorld );
  9504. if ( this.isCamera || this.isLight ) {
  9505. _m1$1.lookAt( _position$4, _target, this.up );
  9506. } else {
  9507. _m1$1.lookAt( _target, _position$4, this.up );
  9508. }
  9509. this.quaternion.setFromRotationMatrix( _m1$1 );
  9510. if ( parent ) {
  9511. _m1$1.extractRotation( parent.matrixWorld );
  9512. _q1.setFromRotationMatrix( _m1$1 );
  9513. this.quaternion.premultiply( _q1.invert() );
  9514. }
  9515. }
  9516. /**
  9517. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  9518. * objects may be added. Any current parent on an object passed in here will be
  9519. * removed, since an object can have at most one parent.
  9520. *
  9521. * @fires Object3D#added
  9522. * @fires Object3D#childadded
  9523. * @param {Object3D} object - The 3D object to add.
  9524. * @return {Object3D} A reference to this instance.
  9525. */
  9526. add( object ) {
  9527. if ( arguments.length > 1 ) {
  9528. for ( let i = 0; i < arguments.length; i ++ ) {
  9529. this.add( arguments[ i ] );
  9530. }
  9531. return this;
  9532. }
  9533. if ( object === this ) {
  9534. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  9535. return this;
  9536. }
  9537. if ( object && object.isObject3D ) {
  9538. object.removeFromParent();
  9539. object.parent = this;
  9540. this.children.push( object );
  9541. object.dispatchEvent( _addedEvent );
  9542. _childaddedEvent.child = object;
  9543. this.dispatchEvent( _childaddedEvent );
  9544. _childaddedEvent.child = null;
  9545. } else {
  9546. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  9547. }
  9548. return this;
  9549. }
  9550. /**
  9551. * Removes the given 3D object as child from this 3D object.
  9552. * An arbitrary number of objects may be removed.
  9553. *
  9554. * @fires Object3D#removed
  9555. * @fires Object3D#childremoved
  9556. * @param {Object3D} object - The 3D object to remove.
  9557. * @return {Object3D} A reference to this instance.
  9558. */
  9559. remove( object ) {
  9560. if ( arguments.length > 1 ) {
  9561. for ( let i = 0; i < arguments.length; i ++ ) {
  9562. this.remove( arguments[ i ] );
  9563. }
  9564. return this;
  9565. }
  9566. const index = this.children.indexOf( object );
  9567. if ( index !== -1 ) {
  9568. object.parent = null;
  9569. this.children.splice( index, 1 );
  9570. object.dispatchEvent( _removedEvent );
  9571. _childremovedEvent.child = object;
  9572. this.dispatchEvent( _childremovedEvent );
  9573. _childremovedEvent.child = null;
  9574. }
  9575. return this;
  9576. }
  9577. /**
  9578. * Removes this 3D object from its current parent.
  9579. *
  9580. * @fires Object3D#removed
  9581. * @fires Object3D#childremoved
  9582. * @return {Object3D} A reference to this instance.
  9583. */
  9584. removeFromParent() {
  9585. const parent = this.parent;
  9586. if ( parent !== null ) {
  9587. parent.remove( this );
  9588. }
  9589. return this;
  9590. }
  9591. /**
  9592. * Removes all child objects.
  9593. *
  9594. * @fires Object3D#removed
  9595. * @fires Object3D#childremoved
  9596. * @return {Object3D} A reference to this instance.
  9597. */
  9598. clear() {
  9599. return this.remove( ... this.children );
  9600. }
  9601. /**
  9602. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  9603. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  9604. *
  9605. * @fires Object3D#added
  9606. * @fires Object3D#childadded
  9607. * @param {Object3D} object - The 3D object to attach.
  9608. * @return {Object3D} A reference to this instance.
  9609. */
  9610. attach( object ) {
  9611. // adds object as a child of this, while maintaining the object's world transform
  9612. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  9613. this.updateWorldMatrix( true, false );
  9614. _m1$1.copy( this.matrixWorld ).invert();
  9615. if ( object.parent !== null ) {
  9616. object.parent.updateWorldMatrix( true, false );
  9617. _m1$1.multiply( object.parent.matrixWorld );
  9618. }
  9619. object.applyMatrix4( _m1$1 );
  9620. object.removeFromParent();
  9621. object.parent = this;
  9622. this.children.push( object );
  9623. object.updateWorldMatrix( false, true );
  9624. object.dispatchEvent( _addedEvent );
  9625. _childaddedEvent.child = object;
  9626. this.dispatchEvent( _childaddedEvent );
  9627. _childaddedEvent.child = null;
  9628. return this;
  9629. }
  9630. /**
  9631. * Searches through the 3D object and its children, starting with the 3D object
  9632. * itself, and returns the first with a matching ID.
  9633. *
  9634. * @param {number} id - The id.
  9635. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9636. */
  9637. getObjectById( id ) {
  9638. return this.getObjectByProperty( 'id', id );
  9639. }
  9640. /**
  9641. * Searches through the 3D object and its children, starting with the 3D object
  9642. * itself, and returns the first with a matching name.
  9643. *
  9644. * @param {string} name - The name.
  9645. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9646. */
  9647. getObjectByName( name ) {
  9648. return this.getObjectByProperty( 'name', name );
  9649. }
  9650. /**
  9651. * Searches through the 3D object and its children, starting with the 3D object
  9652. * itself, and returns the first with a matching property value.
  9653. *
  9654. * @param {string} name - The name of the property.
  9655. * @param {any} value - The value.
  9656. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9657. */
  9658. getObjectByProperty( name, value ) {
  9659. if ( this[ name ] === value ) return this;
  9660. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  9661. const child = this.children[ i ];
  9662. const object = child.getObjectByProperty( name, value );
  9663. if ( object !== undefined ) {
  9664. return object;
  9665. }
  9666. }
  9667. return undefined;
  9668. }
  9669. /**
  9670. * Searches through the 3D object and its children, starting with the 3D object
  9671. * itself, and returns all 3D objects with a matching property value.
  9672. *
  9673. * @param {string} name - The name of the property.
  9674. * @param {any} value - The value.
  9675. * @param {Array<Object3D>} result - The method stores the result in this array.
  9676. * @return {Array<Object3D>} The found 3D objects.
  9677. */
  9678. getObjectsByProperty( name, value, result = [] ) {
  9679. if ( this[ name ] === value ) result.push( this );
  9680. const children = this.children;
  9681. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9682. children[ i ].getObjectsByProperty( name, value, result );
  9683. }
  9684. return result;
  9685. }
  9686. /**
  9687. * Returns a vector representing the position of the 3D object in world space.
  9688. *
  9689. * @param {Vector3} target - The target vector the result is stored to.
  9690. * @return {Vector3} The 3D object's position in world space.
  9691. */
  9692. getWorldPosition( target ) {
  9693. this.updateWorldMatrix( true, false );
  9694. return target.setFromMatrixPosition( this.matrixWorld );
  9695. }
  9696. /**
  9697. * Returns a Quaternion representing the position of the 3D object in world space.
  9698. *
  9699. * @param {Quaternion} target - The target Quaternion the result is stored to.
  9700. * @return {Quaternion} The 3D object's rotation in world space.
  9701. */
  9702. getWorldQuaternion( target ) {
  9703. this.updateWorldMatrix( true, false );
  9704. this.matrixWorld.decompose( _position$4, target, _scale$3 );
  9705. return target;
  9706. }
  9707. /**
  9708. * Returns a vector representing the scale of the 3D object in world space.
  9709. *
  9710. * @param {Vector3} target - The target vector the result is stored to.
  9711. * @return {Vector3} The 3D object's scale in world space.
  9712. */
  9713. getWorldScale( target ) {
  9714. this.updateWorldMatrix( true, false );
  9715. this.matrixWorld.decompose( _position$4, _quaternion$3, target );
  9716. return target;
  9717. }
  9718. /**
  9719. * Returns a vector representing the ("look") direction of the 3D object in world space.
  9720. *
  9721. * @param {Vector3} target - The target vector the result is stored to.
  9722. * @return {Vector3} The 3D object's direction in world space.
  9723. */
  9724. getWorldDirection( target ) {
  9725. this.updateWorldMatrix( true, false );
  9726. const e = this.matrixWorld.elements;
  9727. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  9728. }
  9729. /**
  9730. * Abstract method to get intersections between a casted ray and this
  9731. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  9732. * implement this method in order to use raycasting.
  9733. *
  9734. * @abstract
  9735. * @param {Raycaster} raycaster - The raycaster.
  9736. * @param {Array<Object>} intersects - An array holding the result of the method.
  9737. */
  9738. raycast( /* raycaster, intersects */ ) {}
  9739. /**
  9740. * Executes the callback on this 3D object and all descendants.
  9741. *
  9742. * Note: Modifying the scene graph inside the callback is discouraged.
  9743. *
  9744. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9745. */
  9746. traverse( callback ) {
  9747. callback( this );
  9748. const children = this.children;
  9749. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9750. children[ i ].traverse( callback );
  9751. }
  9752. }
  9753. /**
  9754. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  9755. * Descendants of invisible 3D objects are not traversed.
  9756. *
  9757. * Note: Modifying the scene graph inside the callback is discouraged.
  9758. *
  9759. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9760. */
  9761. traverseVisible( callback ) {
  9762. if ( this.visible === false ) return;
  9763. callback( this );
  9764. const children = this.children;
  9765. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9766. children[ i ].traverseVisible( callback );
  9767. }
  9768. }
  9769. /**
  9770. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  9771. *
  9772. * Note: Modifying the scene graph inside the callback is discouraged.
  9773. *
  9774. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9775. */
  9776. traverseAncestors( callback ) {
  9777. const parent = this.parent;
  9778. if ( parent !== null ) {
  9779. callback( parent );
  9780. parent.traverseAncestors( callback );
  9781. }
  9782. }
  9783. /**
  9784. * Updates the transformation matrix in local space by computing it from the current
  9785. * position, rotation and scale values.
  9786. */
  9787. updateMatrix() {
  9788. this.matrix.compose( this.position, this.quaternion, this.scale );
  9789. const pivot = this.pivot;
  9790. if ( pivot !== null ) {
  9791. const px = pivot.x, py = pivot.y, pz = pivot.z;
  9792. const te = this.matrix.elements;
  9793. te[ 12 ] += px - te[ 0 ] * px - te[ 4 ] * py - te[ 8 ] * pz;
  9794. te[ 13 ] += py - te[ 1 ] * px - te[ 5 ] * py - te[ 9 ] * pz;
  9795. te[ 14 ] += pz - te[ 2 ] * px - te[ 6 ] * py - te[ 10 ] * pz;
  9796. }
  9797. this.matrixWorldNeedsUpdate = true;
  9798. }
  9799. /**
  9800. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  9801. *
  9802. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  9803. * local space. The computation of the local and world matrix can be controlled with the
  9804. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  9805. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  9806. *
  9807. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  9808. * when {@link Object3D#matrixWorldNeedsUpdate} is `false`.
  9809. */
  9810. updateMatrixWorld( force ) {
  9811. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9812. if ( this.matrixWorldNeedsUpdate || force ) {
  9813. if ( this.matrixWorldAutoUpdate === true ) {
  9814. if ( this.parent === null ) {
  9815. this.matrixWorld.copy( this.matrix );
  9816. } else {
  9817. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9818. }
  9819. }
  9820. this.matrixWorldNeedsUpdate = false;
  9821. force = true;
  9822. }
  9823. // make sure descendants are updated if required
  9824. const children = this.children;
  9825. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9826. const child = children[ i ];
  9827. child.updateMatrixWorld( force );
  9828. }
  9829. }
  9830. /**
  9831. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  9832. * update of ancestor and descendant nodes.
  9833. *
  9834. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  9835. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  9836. */
  9837. updateWorldMatrix( updateParents, updateChildren ) {
  9838. const parent = this.parent;
  9839. if ( updateParents === true && parent !== null ) {
  9840. parent.updateWorldMatrix( true, false );
  9841. }
  9842. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9843. if ( this.matrixWorldAutoUpdate === true ) {
  9844. if ( this.parent === null ) {
  9845. this.matrixWorld.copy( this.matrix );
  9846. } else {
  9847. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9848. }
  9849. }
  9850. // make sure descendants are updated
  9851. if ( updateChildren === true ) {
  9852. const children = this.children;
  9853. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9854. const child = children[ i ];
  9855. child.updateWorldMatrix( false, true );
  9856. }
  9857. }
  9858. }
  9859. /**
  9860. * Serializes the 3D object into JSON.
  9861. *
  9862. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  9863. * @return {Object} A JSON object representing the serialized 3D object.
  9864. * @see {@link ObjectLoader#parse}
  9865. */
  9866. toJSON( meta ) {
  9867. // meta is a string when called from JSON.stringify
  9868. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  9869. const output = {};
  9870. // meta is a hash used to collect geometries, materials.
  9871. // not providing it implies that this is the root object
  9872. // being serialized.
  9873. if ( isRootObject ) {
  9874. // initialize meta obj
  9875. meta = {
  9876. geometries: {},
  9877. materials: {},
  9878. textures: {},
  9879. images: {},
  9880. shapes: {},
  9881. skeletons: {},
  9882. animations: {},
  9883. nodes: {}
  9884. };
  9885. output.metadata = {
  9886. version: 4.7,
  9887. type: 'Object',
  9888. generator: 'Object3D.toJSON'
  9889. };
  9890. }
  9891. // standard Object3D serialization
  9892. const object = {};
  9893. object.uuid = this.uuid;
  9894. object.type = this.type;
  9895. if ( this.name !== '' ) object.name = this.name;
  9896. if ( this.castShadow === true ) object.castShadow = true;
  9897. if ( this.receiveShadow === true ) object.receiveShadow = true;
  9898. if ( this.visible === false ) object.visible = false;
  9899. if ( this.frustumCulled === false ) object.frustumCulled = false;
  9900. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  9901. if ( this.static !== false ) object.static = this.static;
  9902. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  9903. object.layers = this.layers.mask;
  9904. object.matrix = this.matrix.toArray();
  9905. object.up = this.up.toArray();
  9906. if ( this.pivot !== null ) object.pivot = this.pivot.toArray();
  9907. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  9908. if ( this.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, this.morphTargetDictionary );
  9909. if ( this.morphTargetInfluences !== undefined ) object.morphTargetInfluences = this.morphTargetInfluences.slice();
  9910. // object specific properties
  9911. if ( this.isInstancedMesh ) {
  9912. object.type = 'InstancedMesh';
  9913. object.count = this.count;
  9914. object.instanceMatrix = this.instanceMatrix.toJSON();
  9915. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  9916. }
  9917. if ( this.isBatchedMesh ) {
  9918. object.type = 'BatchedMesh';
  9919. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  9920. object.sortObjects = this.sortObjects;
  9921. object.drawRanges = this._drawRanges;
  9922. object.reservedRanges = this._reservedRanges;
  9923. object.geometryInfo = this._geometryInfo.map( info => ( {
  9924. ...info,
  9925. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  9926. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  9927. } ) );
  9928. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  9929. object.availableInstanceIds = this._availableInstanceIds.slice();
  9930. object.availableGeometryIds = this._availableGeometryIds.slice();
  9931. object.nextIndexStart = this._nextIndexStart;
  9932. object.nextVertexStart = this._nextVertexStart;
  9933. object.geometryCount = this._geometryCount;
  9934. object.maxInstanceCount = this._maxInstanceCount;
  9935. object.maxVertexCount = this._maxVertexCount;
  9936. object.maxIndexCount = this._maxIndexCount;
  9937. object.geometryInitialized = this._geometryInitialized;
  9938. object.matricesTexture = this._matricesTexture.toJSON( meta );
  9939. object.indirectTexture = this._indirectTexture.toJSON( meta );
  9940. if ( this._colorsTexture !== null ) {
  9941. object.colorsTexture = this._colorsTexture.toJSON( meta );
  9942. }
  9943. if ( this.boundingSphere !== null ) {
  9944. object.boundingSphere = this.boundingSphere.toJSON();
  9945. }
  9946. if ( this.boundingBox !== null ) {
  9947. object.boundingBox = this.boundingBox.toJSON();
  9948. }
  9949. }
  9950. //
  9951. function serialize( library, element ) {
  9952. if ( library[ element.uuid ] === undefined ) {
  9953. library[ element.uuid ] = element.toJSON( meta );
  9954. }
  9955. return element.uuid;
  9956. }
  9957. if ( this.isScene ) {
  9958. if ( this.background ) {
  9959. if ( this.background.isColor ) {
  9960. object.background = this.background.toJSON();
  9961. } else if ( this.background.isTexture ) {
  9962. object.background = this.background.toJSON( meta ).uuid;
  9963. }
  9964. }
  9965. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  9966. object.environment = this.environment.toJSON( meta ).uuid;
  9967. }
  9968. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  9969. object.geometry = serialize( meta.geometries, this.geometry );
  9970. const parameters = this.geometry.parameters;
  9971. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  9972. const shapes = parameters.shapes;
  9973. if ( Array.isArray( shapes ) ) {
  9974. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  9975. const shape = shapes[ i ];
  9976. serialize( meta.shapes, shape );
  9977. }
  9978. } else {
  9979. serialize( meta.shapes, shapes );
  9980. }
  9981. }
  9982. }
  9983. if ( this.isSkinnedMesh ) {
  9984. object.bindMode = this.bindMode;
  9985. object.bindMatrix = this.bindMatrix.toArray();
  9986. if ( this.skeleton !== undefined ) {
  9987. serialize( meta.skeletons, this.skeleton );
  9988. object.skeleton = this.skeleton.uuid;
  9989. }
  9990. }
  9991. if ( this.material !== undefined ) {
  9992. if ( Array.isArray( this.material ) ) {
  9993. const uuids = [];
  9994. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  9995. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  9996. }
  9997. object.material = uuids;
  9998. } else {
  9999. object.material = serialize( meta.materials, this.material );
  10000. }
  10001. }
  10002. //
  10003. if ( this.children.length > 0 ) {
  10004. object.children = [];
  10005. for ( let i = 0; i < this.children.length; i ++ ) {
  10006. object.children.push( this.children[ i ].toJSON( meta ).object );
  10007. }
  10008. }
  10009. //
  10010. if ( this.animations.length > 0 ) {
  10011. object.animations = [];
  10012. for ( let i = 0; i < this.animations.length; i ++ ) {
  10013. const animation = this.animations[ i ];
  10014. object.animations.push( serialize( meta.animations, animation ) );
  10015. }
  10016. }
  10017. if ( isRootObject ) {
  10018. const geometries = extractFromCache( meta.geometries );
  10019. const materials = extractFromCache( meta.materials );
  10020. const textures = extractFromCache( meta.textures );
  10021. const images = extractFromCache( meta.images );
  10022. const shapes = extractFromCache( meta.shapes );
  10023. const skeletons = extractFromCache( meta.skeletons );
  10024. const animations = extractFromCache( meta.animations );
  10025. const nodes = extractFromCache( meta.nodes );
  10026. if ( geometries.length > 0 ) output.geometries = geometries;
  10027. if ( materials.length > 0 ) output.materials = materials;
  10028. if ( textures.length > 0 ) output.textures = textures;
  10029. if ( images.length > 0 ) output.images = images;
  10030. if ( shapes.length > 0 ) output.shapes = shapes;
  10031. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  10032. if ( animations.length > 0 ) output.animations = animations;
  10033. if ( nodes.length > 0 ) output.nodes = nodes;
  10034. }
  10035. output.object = object;
  10036. return output;
  10037. // extract data from the cache hash
  10038. // remove metadata on each item
  10039. // and return as array
  10040. function extractFromCache( cache ) {
  10041. const values = [];
  10042. for ( const key in cache ) {
  10043. const data = cache[ key ];
  10044. delete data.metadata;
  10045. values.push( data );
  10046. }
  10047. return values;
  10048. }
  10049. }
  10050. /**
  10051. * Returns a new 3D object with copied values from this instance.
  10052. *
  10053. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  10054. * @return {Object3D} A clone of this instance.
  10055. */
  10056. clone( recursive ) {
  10057. return new this.constructor().copy( this, recursive );
  10058. }
  10059. /**
  10060. * Copies the values of the given 3D object to this instance.
  10061. *
  10062. * @param {Object3D} source - The 3D object to copy.
  10063. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  10064. * @return {Object3D} A reference to this instance.
  10065. */
  10066. copy( source, recursive = true ) {
  10067. this.name = source.name;
  10068. this.up.copy( source.up );
  10069. this.position.copy( source.position );
  10070. this.rotation.order = source.rotation.order;
  10071. this.quaternion.copy( source.quaternion );
  10072. this.scale.copy( source.scale );
  10073. if ( source.pivot !== null ) {
  10074. this.pivot = source.pivot.clone();
  10075. }
  10076. this.matrix.copy( source.matrix );
  10077. this.matrixWorld.copy( source.matrixWorld );
  10078. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10079. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  10080. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10081. this.layers.mask = source.layers.mask;
  10082. this.visible = source.visible;
  10083. this.castShadow = source.castShadow;
  10084. this.receiveShadow = source.receiveShadow;
  10085. this.frustumCulled = source.frustumCulled;
  10086. this.renderOrder = source.renderOrder;
  10087. this.static = source.static;
  10088. this.animations = source.animations.slice();
  10089. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10090. if ( recursive === true ) {
  10091. for ( let i = 0; i < source.children.length; i ++ ) {
  10092. const child = source.children[ i ];
  10093. this.add( child.clone() );
  10094. }
  10095. }
  10096. return this;
  10097. }
  10098. }
  10099. /**
  10100. * The default up direction for objects, also used as the default
  10101. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  10102. *
  10103. * @static
  10104. * @type {Vector3}
  10105. * @default (0,1,0)
  10106. */
  10107. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10108. /**
  10109. * The default setting for {@link Object3D#matrixAutoUpdate} for
  10110. * newly created 3D objects.
  10111. *
  10112. * @static
  10113. * @type {boolean}
  10114. * @default true
  10115. */
  10116. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  10117. /**
  10118. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  10119. * newly created 3D objects.
  10120. *
  10121. * @static
  10122. * @type {boolean}
  10123. * @default true
  10124. */
  10125. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  10126. /**
  10127. * This is almost identical to an {@link Object3D}. Its purpose is to
  10128. * make working with groups of objects syntactically clearer.
  10129. *
  10130. * ```js
  10131. * // Create a group and add the two cubes.
  10132. * // These cubes can now be rotated / scaled etc as a group.
  10133. * const group = new THREE.Group();
  10134. *
  10135. * group.add( meshA );
  10136. * group.add( meshB );
  10137. *
  10138. * scene.add( group );
  10139. * ```
  10140. *
  10141. * @augments Object3D
  10142. */
  10143. class Group extends Object3D {
  10144. constructor() {
  10145. super();
  10146. /**
  10147. * This flag can be used for type testing.
  10148. *
  10149. * @type {boolean}
  10150. * @readonly
  10151. * @default true
  10152. */
  10153. this.isGroup = true;
  10154. this.type = 'Group';
  10155. }
  10156. }
  10157. const _moveEvent = { type: 'move' };
  10158. /**
  10159. * Class for representing a XR controller with its
  10160. * different coordinate systems.
  10161. *
  10162. * @private
  10163. */
  10164. class WebXRController {
  10165. /**
  10166. * Constructs a new XR controller.
  10167. */
  10168. constructor() {
  10169. /**
  10170. * A group representing the target ray space
  10171. * of the XR controller.
  10172. *
  10173. * @private
  10174. * @type {?Group}
  10175. * @default null
  10176. */
  10177. this._targetRay = null;
  10178. /**
  10179. * A group representing the grip space
  10180. * of the XR controller.
  10181. *
  10182. * @private
  10183. * @type {?Group}
  10184. * @default null
  10185. */
  10186. this._grip = null;
  10187. /**
  10188. * A group representing the hand space
  10189. * of the XR controller.
  10190. *
  10191. * @private
  10192. * @type {?Group}
  10193. * @default null
  10194. */
  10195. this._hand = null;
  10196. }
  10197. /**
  10198. * Returns a group representing the hand space of the XR controller.
  10199. *
  10200. * @return {Group} A group representing the hand space of the XR controller.
  10201. */
  10202. getHandSpace() {
  10203. if ( this._hand === null ) {
  10204. this._hand = new Group();
  10205. this._hand.matrixAutoUpdate = false;
  10206. this._hand.visible = false;
  10207. this._hand.joints = {};
  10208. this._hand.inputState = { pinching: false };
  10209. }
  10210. return this._hand;
  10211. }
  10212. /**
  10213. * Returns a group representing the target ray space of the XR controller.
  10214. *
  10215. * @return {Group} A group representing the target ray space of the XR controller.
  10216. */
  10217. getTargetRaySpace() {
  10218. if ( this._targetRay === null ) {
  10219. this._targetRay = new Group();
  10220. this._targetRay.matrixAutoUpdate = false;
  10221. this._targetRay.visible = false;
  10222. this._targetRay.hasLinearVelocity = false;
  10223. this._targetRay.linearVelocity = new Vector3();
  10224. this._targetRay.hasAngularVelocity = false;
  10225. this._targetRay.angularVelocity = new Vector3();
  10226. }
  10227. return this._targetRay;
  10228. }
  10229. /**
  10230. * Returns a group representing the grip space of the XR controller.
  10231. *
  10232. * @return {Group} A group representing the grip space of the XR controller.
  10233. */
  10234. getGripSpace() {
  10235. if ( this._grip === null ) {
  10236. this._grip = new Group();
  10237. this._grip.matrixAutoUpdate = false;
  10238. this._grip.visible = false;
  10239. this._grip.hasLinearVelocity = false;
  10240. this._grip.linearVelocity = new Vector3();
  10241. this._grip.hasAngularVelocity = false;
  10242. this._grip.angularVelocity = new Vector3();
  10243. }
  10244. return this._grip;
  10245. }
  10246. /**
  10247. * Dispatches the given event to the groups representing
  10248. * the different coordinate spaces of the XR controller.
  10249. *
  10250. * @param {Object} event - The event to dispatch.
  10251. * @return {WebXRController} A reference to this instance.
  10252. */
  10253. dispatchEvent( event ) {
  10254. if ( this._targetRay !== null ) {
  10255. this._targetRay.dispatchEvent( event );
  10256. }
  10257. if ( this._grip !== null ) {
  10258. this._grip.dispatchEvent( event );
  10259. }
  10260. if ( this._hand !== null ) {
  10261. this._hand.dispatchEvent( event );
  10262. }
  10263. return this;
  10264. }
  10265. /**
  10266. * Connects the controller with the given XR input source.
  10267. *
  10268. * @param {XRInputSource} inputSource - The input source.
  10269. * @return {WebXRController} A reference to this instance.
  10270. */
  10271. connect( inputSource ) {
  10272. if ( inputSource && inputSource.hand ) {
  10273. const hand = this._hand;
  10274. if ( hand ) {
  10275. for ( const inputjoint of inputSource.hand.values() ) {
  10276. // Initialize hand with joints when connected
  10277. this._getHandJoint( hand, inputjoint );
  10278. }
  10279. }
  10280. }
  10281. this.dispatchEvent( { type: 'connected', data: inputSource } );
  10282. return this;
  10283. }
  10284. /**
  10285. * Disconnects the controller from the given XR input source.
  10286. *
  10287. * @param {XRInputSource} inputSource - The input source.
  10288. * @return {WebXRController} A reference to this instance.
  10289. */
  10290. disconnect( inputSource ) {
  10291. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  10292. if ( this._targetRay !== null ) {
  10293. this._targetRay.visible = false;
  10294. }
  10295. if ( this._grip !== null ) {
  10296. this._grip.visible = false;
  10297. }
  10298. if ( this._hand !== null ) {
  10299. this._hand.visible = false;
  10300. }
  10301. return this;
  10302. }
  10303. /**
  10304. * Updates the controller with the given input source, XR frame and reference space.
  10305. * This updates the transformations of the groups that represent the different
  10306. * coordinate systems of the controller.
  10307. *
  10308. * @param {XRInputSource} inputSource - The input source.
  10309. * @param {XRFrame} frame - The XR frame.
  10310. * @param {XRReferenceSpace} referenceSpace - The reference space.
  10311. * @return {WebXRController} A reference to this instance.
  10312. */
  10313. update( inputSource, frame, referenceSpace ) {
  10314. let inputPose = null;
  10315. let gripPose = null;
  10316. let handPose = null;
  10317. const targetRay = this._targetRay;
  10318. const grip = this._grip;
  10319. const hand = this._hand;
  10320. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  10321. if ( hand && inputSource.hand ) {
  10322. handPose = true;
  10323. for ( const inputjoint of inputSource.hand.values() ) {
  10324. // Update the joints groups with the XRJoint poses
  10325. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  10326. // The transform of this joint will be updated with the joint pose on each frame
  10327. const joint = this._getHandJoint( hand, inputjoint );
  10328. if ( jointPose !== null ) {
  10329. joint.matrix.fromArray( jointPose.transform.matrix );
  10330. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  10331. joint.matrixWorldNeedsUpdate = true;
  10332. joint.jointRadius = jointPose.radius;
  10333. }
  10334. joint.visible = jointPose !== null;
  10335. }
  10336. // Custom events
  10337. // Check pinchz
  10338. const indexTip = hand.joints[ 'index-finger-tip' ];
  10339. const thumbTip = hand.joints[ 'thumb-tip' ];
  10340. const distance = indexTip.position.distanceTo( thumbTip.position );
  10341. const distanceToPinch = 0.02;
  10342. const threshold = 0.005;
  10343. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  10344. hand.inputState.pinching = false;
  10345. this.dispatchEvent( {
  10346. type: 'pinchend',
  10347. handedness: inputSource.handedness,
  10348. target: this
  10349. } );
  10350. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  10351. hand.inputState.pinching = true;
  10352. this.dispatchEvent( {
  10353. type: 'pinchstart',
  10354. handedness: inputSource.handedness,
  10355. target: this
  10356. } );
  10357. }
  10358. } else {
  10359. if ( grip !== null && inputSource.gripSpace ) {
  10360. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  10361. if ( gripPose !== null ) {
  10362. grip.matrix.fromArray( gripPose.transform.matrix );
  10363. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  10364. grip.matrixWorldNeedsUpdate = true;
  10365. if ( gripPose.linearVelocity ) {
  10366. grip.hasLinearVelocity = true;
  10367. grip.linearVelocity.copy( gripPose.linearVelocity );
  10368. } else {
  10369. grip.hasLinearVelocity = false;
  10370. }
  10371. if ( gripPose.angularVelocity ) {
  10372. grip.hasAngularVelocity = true;
  10373. grip.angularVelocity.copy( gripPose.angularVelocity );
  10374. } else {
  10375. grip.hasAngularVelocity = false;
  10376. }
  10377. }
  10378. }
  10379. }
  10380. if ( targetRay !== null ) {
  10381. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  10382. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  10383. if ( inputPose === null && gripPose !== null ) {
  10384. inputPose = gripPose;
  10385. }
  10386. if ( inputPose !== null ) {
  10387. targetRay.matrix.fromArray( inputPose.transform.matrix );
  10388. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  10389. targetRay.matrixWorldNeedsUpdate = true;
  10390. if ( inputPose.linearVelocity ) {
  10391. targetRay.hasLinearVelocity = true;
  10392. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  10393. } else {
  10394. targetRay.hasLinearVelocity = false;
  10395. }
  10396. if ( inputPose.angularVelocity ) {
  10397. targetRay.hasAngularVelocity = true;
  10398. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  10399. } else {
  10400. targetRay.hasAngularVelocity = false;
  10401. }
  10402. this.dispatchEvent( _moveEvent );
  10403. }
  10404. }
  10405. }
  10406. if ( targetRay !== null ) {
  10407. targetRay.visible = ( inputPose !== null );
  10408. }
  10409. if ( grip !== null ) {
  10410. grip.visible = ( gripPose !== null );
  10411. }
  10412. if ( hand !== null ) {
  10413. hand.visible = ( handPose !== null );
  10414. }
  10415. return this;
  10416. }
  10417. /**
  10418. * Returns a group representing the hand joint for the given input joint.
  10419. *
  10420. * @private
  10421. * @param {Group} hand - The group representing the hand space.
  10422. * @param {XRJointSpace} inputjoint - The hand joint data.
  10423. * @return {Group} A group representing the hand joint for the given input joint.
  10424. */
  10425. _getHandJoint( hand, inputjoint ) {
  10426. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  10427. const joint = new Group();
  10428. joint.matrixAutoUpdate = false;
  10429. joint.visible = false;
  10430. hand.joints[ inputjoint.jointName ] = joint;
  10431. hand.add( joint );
  10432. }
  10433. return hand.joints[ inputjoint.jointName ];
  10434. }
  10435. }
  10436. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  10437. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  10438. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  10439. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  10440. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  10441. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  10442. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  10443. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  10444. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  10445. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  10446. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  10447. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  10448. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  10449. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  10450. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  10451. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  10452. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  10453. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  10454. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  10455. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  10456. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  10457. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  10458. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  10459. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  10460. const _hslA = { h: 0, s: 0, l: 0 };
  10461. const _hslB = { h: 0, s: 0, l: 0 };
  10462. function hue2rgb( p, q, t ) {
  10463. if ( t < 0 ) t += 1;
  10464. if ( t > 1 ) t -= 1;
  10465. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  10466. if ( t < 1 / 2 ) return q;
  10467. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  10468. return p;
  10469. }
  10470. /**
  10471. * A Color instance is represented by RGB components in the linear <i>working
  10472. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  10473. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  10474. * strings) are converted to the working color space automatically.
  10475. *
  10476. * ```js
  10477. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  10478. * const color = new THREE.Color().setHex( 0x112233 );
  10479. * ```
  10480. * Source color spaces may be specified explicitly, to ensure correct conversions.
  10481. * ```js
  10482. * // assumed already LinearSRGBColorSpace; no conversion
  10483. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  10484. *
  10485. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  10486. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  10487. * ```
  10488. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  10489. * see <i>Color management</i>. Iterating through a Color instance will yield
  10490. * its components (r, g, b) in the corresponding order. A Color can be initialised
  10491. * in any of the following ways:
  10492. * ```js
  10493. * //empty constructor - will default white
  10494. * const color1 = new THREE.Color();
  10495. *
  10496. * //Hexadecimal color (recommended)
  10497. * const color2 = new THREE.Color( 0xff0000 );
  10498. *
  10499. * //RGB string
  10500. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  10501. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  10502. *
  10503. * //X11 color name - all 140 color names are supported.
  10504. * //Note the lack of CamelCase in the name
  10505. * const color5 = new THREE.Color( 'skyblue' );
  10506. * //HSL string
  10507. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  10508. *
  10509. * //Separate RGB values between 0 and 1
  10510. * const color7 = new THREE.Color( 1, 0, 0 );
  10511. * ```
  10512. */
  10513. class Color {
  10514. /**
  10515. * Constructs a new color.
  10516. *
  10517. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  10518. * and that method is used throughout the rest of the documentation.
  10519. *
  10520. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  10521. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  10522. * @param {number} [g] - The green component.
  10523. * @param {number} [b] - The blue component.
  10524. */
  10525. constructor( r, g, b ) {
  10526. /**
  10527. * This flag can be used for type testing.
  10528. *
  10529. * @type {boolean}
  10530. * @readonly
  10531. * @default true
  10532. */
  10533. this.isColor = true;
  10534. /**
  10535. * The red component.
  10536. *
  10537. * @type {number}
  10538. * @default 1
  10539. */
  10540. this.r = 1;
  10541. /**
  10542. * The green component.
  10543. *
  10544. * @type {number}
  10545. * @default 1
  10546. */
  10547. this.g = 1;
  10548. /**
  10549. * The blue component.
  10550. *
  10551. * @type {number}
  10552. * @default 1
  10553. */
  10554. this.b = 1;
  10555. return this.set( r, g, b );
  10556. }
  10557. /**
  10558. * Sets the colors's components from the given values.
  10559. *
  10560. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  10561. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  10562. * @param {number} [g] - The green component.
  10563. * @param {number} [b] - The blue component.
  10564. * @return {Color} A reference to this color.
  10565. */
  10566. set( r, g, b ) {
  10567. if ( g === undefined && b === undefined ) {
  10568. // r is THREE.Color, hex or string
  10569. const value = r;
  10570. if ( value && value.isColor ) {
  10571. this.copy( value );
  10572. } else if ( typeof value === 'number' ) {
  10573. this.setHex( value );
  10574. } else if ( typeof value === 'string' ) {
  10575. this.setStyle( value );
  10576. }
  10577. } else {
  10578. this.setRGB( r, g, b );
  10579. }
  10580. return this;
  10581. }
  10582. /**
  10583. * Sets the colors's components to the given scalar value.
  10584. *
  10585. * @param {number} scalar - The scalar value.
  10586. * @return {Color} A reference to this color.
  10587. */
  10588. setScalar( scalar ) {
  10589. this.r = scalar;
  10590. this.g = scalar;
  10591. this.b = scalar;
  10592. return this;
  10593. }
  10594. /**
  10595. * Sets this color from a hexadecimal value.
  10596. *
  10597. * @param {number} hex - The hexadecimal value.
  10598. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10599. * @return {Color} A reference to this color.
  10600. */
  10601. setHex( hex, colorSpace = SRGBColorSpace ) {
  10602. hex = Math.floor( hex );
  10603. this.r = ( hex >> 16 & 255 ) / 255;
  10604. this.g = ( hex >> 8 & 255 ) / 255;
  10605. this.b = ( hex & 255 ) / 255;
  10606. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10607. return this;
  10608. }
  10609. /**
  10610. * Sets this color from RGB values.
  10611. *
  10612. * @param {number} r - Red channel value between `0.0` and `1.0`.
  10613. * @param {number} g - Green channel value between `0.0` and `1.0`.
  10614. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  10615. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10616. * @return {Color} A reference to this color.
  10617. */
  10618. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  10619. this.r = r;
  10620. this.g = g;
  10621. this.b = b;
  10622. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10623. return this;
  10624. }
  10625. /**
  10626. * Sets this color from RGB values.
  10627. *
  10628. * @param {number} h - Hue value between `0.0` and `1.0`.
  10629. * @param {number} s - Saturation value between `0.0` and `1.0`.
  10630. * @param {number} l - Lightness value between `0.0` and `1.0`.
  10631. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10632. * @return {Color} A reference to this color.
  10633. */
  10634. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  10635. // h,s,l ranges are in 0.0 - 1.0
  10636. h = euclideanModulo( h, 1 );
  10637. s = clamp( s, 0, 1 );
  10638. l = clamp( l, 0, 1 );
  10639. if ( s === 0 ) {
  10640. this.r = this.g = this.b = l;
  10641. } else {
  10642. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  10643. const q = ( 2 * l ) - p;
  10644. this.r = hue2rgb( q, p, h + 1 / 3 );
  10645. this.g = hue2rgb( q, p, h );
  10646. this.b = hue2rgb( q, p, h - 1 / 3 );
  10647. }
  10648. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10649. return this;
  10650. }
  10651. /**
  10652. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  10653. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  10654. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  10655. * all 140 color names are supported).
  10656. *
  10657. * @param {string} style - Color as a CSS-style string.
  10658. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10659. * @return {Color} A reference to this color.
  10660. */
  10661. setStyle( style, colorSpace = SRGBColorSpace ) {
  10662. function handleAlpha( string ) {
  10663. if ( string === undefined ) return;
  10664. if ( parseFloat( string ) < 1 ) {
  10665. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  10666. }
  10667. }
  10668. let m;
  10669. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  10670. // rgb / hsl
  10671. let color;
  10672. const name = m[ 1 ];
  10673. const components = m[ 2 ];
  10674. switch ( name ) {
  10675. case 'rgb':
  10676. case 'rgba':
  10677. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10678. // rgb(255,0,0) rgba(255,0,0,0.5)
  10679. handleAlpha( color[ 4 ] );
  10680. return this.setRGB(
  10681. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  10682. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  10683. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  10684. colorSpace
  10685. );
  10686. }
  10687. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10688. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  10689. handleAlpha( color[ 4 ] );
  10690. return this.setRGB(
  10691. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  10692. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  10693. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  10694. colorSpace
  10695. );
  10696. }
  10697. break;
  10698. case 'hsl':
  10699. case 'hsla':
  10700. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10701. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  10702. handleAlpha( color[ 4 ] );
  10703. return this.setHSL(
  10704. parseFloat( color[ 1 ] ) / 360,
  10705. parseFloat( color[ 2 ] ) / 100,
  10706. parseFloat( color[ 3 ] ) / 100,
  10707. colorSpace
  10708. );
  10709. }
  10710. break;
  10711. default:
  10712. warn( 'Color: Unknown color model ' + style );
  10713. }
  10714. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  10715. // hex color
  10716. const hex = m[ 1 ];
  10717. const size = hex.length;
  10718. if ( size === 3 ) {
  10719. // #ff0
  10720. return this.setRGB(
  10721. parseInt( hex.charAt( 0 ), 16 ) / 15,
  10722. parseInt( hex.charAt( 1 ), 16 ) / 15,
  10723. parseInt( hex.charAt( 2 ), 16 ) / 15,
  10724. colorSpace
  10725. );
  10726. } else if ( size === 6 ) {
  10727. // #ff0000
  10728. return this.setHex( parseInt( hex, 16 ), colorSpace );
  10729. } else {
  10730. warn( 'Color: Invalid hex color ' + style );
  10731. }
  10732. } else if ( style && style.length > 0 ) {
  10733. return this.setColorName( style, colorSpace );
  10734. }
  10735. return this;
  10736. }
  10737. /**
  10738. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  10739. * you don't need the other CSS-style formats.
  10740. *
  10741. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  10742. * ```js
  10743. * Color.NAMES.aliceblue // returns 0xF0F8FF
  10744. * ```
  10745. *
  10746. * @param {string} style - The color name.
  10747. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10748. * @return {Color} A reference to this color.
  10749. */
  10750. setColorName( style, colorSpace = SRGBColorSpace ) {
  10751. // color keywords
  10752. const hex = _colorKeywords[ style.toLowerCase() ];
  10753. if ( hex !== undefined ) {
  10754. // red
  10755. this.setHex( hex, colorSpace );
  10756. } else {
  10757. // unknown color
  10758. warn( 'Color: Unknown color ' + style );
  10759. }
  10760. return this;
  10761. }
  10762. /**
  10763. * Returns a new color with copied values from this instance.
  10764. *
  10765. * @return {Color} A clone of this instance.
  10766. */
  10767. clone() {
  10768. return new this.constructor( this.r, this.g, this.b );
  10769. }
  10770. /**
  10771. * Copies the values of the given color to this instance.
  10772. *
  10773. * @param {Color} color - The color to copy.
  10774. * @return {Color} A reference to this color.
  10775. */
  10776. copy( color ) {
  10777. this.r = color.r;
  10778. this.g = color.g;
  10779. this.b = color.b;
  10780. return this;
  10781. }
  10782. /**
  10783. * Copies the given color into this color, and then converts this color from
  10784. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  10785. *
  10786. * @param {Color} color - The color to copy/convert.
  10787. * @return {Color} A reference to this color.
  10788. */
  10789. copySRGBToLinear( color ) {
  10790. this.r = SRGBToLinear( color.r );
  10791. this.g = SRGBToLinear( color.g );
  10792. this.b = SRGBToLinear( color.b );
  10793. return this;
  10794. }
  10795. /**
  10796. * Copies the given color into this color, and then converts this color from
  10797. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  10798. *
  10799. * @param {Color} color - The color to copy/convert.
  10800. * @return {Color} A reference to this color.
  10801. */
  10802. copyLinearToSRGB( color ) {
  10803. this.r = LinearToSRGB( color.r );
  10804. this.g = LinearToSRGB( color.g );
  10805. this.b = LinearToSRGB( color.b );
  10806. return this;
  10807. }
  10808. /**
  10809. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  10810. *
  10811. * @return {Color} A reference to this color.
  10812. */
  10813. convertSRGBToLinear() {
  10814. this.copySRGBToLinear( this );
  10815. return this;
  10816. }
  10817. /**
  10818. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  10819. *
  10820. * @return {Color} A reference to this color.
  10821. */
  10822. convertLinearToSRGB() {
  10823. this.copyLinearToSRGB( this );
  10824. return this;
  10825. }
  10826. /**
  10827. * Returns the hexadecimal value of this color.
  10828. *
  10829. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10830. * @return {number} The hexadecimal value.
  10831. */
  10832. getHex( colorSpace = SRGBColorSpace ) {
  10833. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10834. 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 ) );
  10835. }
  10836. /**
  10837. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  10838. *
  10839. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10840. * @return {string} The hexadecimal value as a string.
  10841. */
  10842. getHexString( colorSpace = SRGBColorSpace ) {
  10843. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  10844. }
  10845. /**
  10846. * Converts the colors RGB values into the HSL format and stores them into the
  10847. * given target object.
  10848. *
  10849. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  10850. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10851. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  10852. */
  10853. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  10854. // h,s,l ranges are in 0.0 - 1.0
  10855. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10856. const r = _color.r, g = _color.g, b = _color.b;
  10857. const max = Math.max( r, g, b );
  10858. const min = Math.min( r, g, b );
  10859. let hue, saturation;
  10860. const lightness = ( min + max ) / 2.0;
  10861. if ( min === max ) {
  10862. hue = 0;
  10863. saturation = 0;
  10864. } else {
  10865. const delta = max - min;
  10866. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  10867. switch ( max ) {
  10868. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  10869. case g: hue = ( b - r ) / delta + 2; break;
  10870. case b: hue = ( r - g ) / delta + 4; break;
  10871. }
  10872. hue /= 6;
  10873. }
  10874. target.h = hue;
  10875. target.s = saturation;
  10876. target.l = lightness;
  10877. return target;
  10878. }
  10879. /**
  10880. * Returns the RGB values of this color and stores them into the given target object.
  10881. *
  10882. * @param {Color} target - The target color that is used to store the method's result.
  10883. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10884. * @return {Color} The RGB representation of this color.
  10885. */
  10886. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  10887. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10888. target.r = _color.r;
  10889. target.g = _color.g;
  10890. target.b = _color.b;
  10891. return target;
  10892. }
  10893. /**
  10894. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  10895. *
  10896. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10897. * @return {string} The CSS representation of this color.
  10898. */
  10899. getStyle( colorSpace = SRGBColorSpace ) {
  10900. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10901. const r = _color.r, g = _color.g, b = _color.b;
  10902. if ( colorSpace !== SRGBColorSpace ) {
  10903. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  10904. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  10905. }
  10906. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  10907. }
  10908. /**
  10909. * Adds the given HSL values to this color's values.
  10910. * Internally, this converts the color's RGB values to HSL, adds HSL
  10911. * and then converts the color back to RGB.
  10912. *
  10913. * @param {number} h - Hue value between `0.0` and `1.0`.
  10914. * @param {number} s - Saturation value between `0.0` and `1.0`.
  10915. * @param {number} l - Lightness value between `0.0` and `1.0`.
  10916. * @return {Color} A reference to this color.
  10917. */
  10918. offsetHSL( h, s, l ) {
  10919. this.getHSL( _hslA );
  10920. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  10921. }
  10922. /**
  10923. * Adds the RGB values of the given color to the RGB values of this color.
  10924. *
  10925. * @param {Color} color - The color to add.
  10926. * @return {Color} A reference to this color.
  10927. */
  10928. add( color ) {
  10929. this.r += color.r;
  10930. this.g += color.g;
  10931. this.b += color.b;
  10932. return this;
  10933. }
  10934. /**
  10935. * Adds the RGB values of the given colors and stores the result in this instance.
  10936. *
  10937. * @param {Color} color1 - The first color.
  10938. * @param {Color} color2 - The second color.
  10939. * @return {Color} A reference to this color.
  10940. */
  10941. addColors( color1, color2 ) {
  10942. this.r = color1.r + color2.r;
  10943. this.g = color1.g + color2.g;
  10944. this.b = color1.b + color2.b;
  10945. return this;
  10946. }
  10947. /**
  10948. * Adds the given scalar value to the RGB values of this color.
  10949. *
  10950. * @param {number} s - The scalar to add.
  10951. * @return {Color} A reference to this color.
  10952. */
  10953. addScalar( s ) {
  10954. this.r += s;
  10955. this.g += s;
  10956. this.b += s;
  10957. return this;
  10958. }
  10959. /**
  10960. * Subtracts the RGB values of the given color from the RGB values of this color.
  10961. *
  10962. * @param {Color} color - The color to subtract.
  10963. * @return {Color} A reference to this color.
  10964. */
  10965. sub( color ) {
  10966. this.r = Math.max( 0, this.r - color.r );
  10967. this.g = Math.max( 0, this.g - color.g );
  10968. this.b = Math.max( 0, this.b - color.b );
  10969. return this;
  10970. }
  10971. /**
  10972. * Multiplies the RGB values of the given color with the RGB values of this color.
  10973. *
  10974. * @param {Color} color - The color to multiply.
  10975. * @return {Color} A reference to this color.
  10976. */
  10977. multiply( color ) {
  10978. this.r *= color.r;
  10979. this.g *= color.g;
  10980. this.b *= color.b;
  10981. return this;
  10982. }
  10983. /**
  10984. * Multiplies the given scalar value with the RGB values of this color.
  10985. *
  10986. * @param {number} s - The scalar to multiply.
  10987. * @return {Color} A reference to this color.
  10988. */
  10989. multiplyScalar( s ) {
  10990. this.r *= s;
  10991. this.g *= s;
  10992. this.b *= s;
  10993. return this;
  10994. }
  10995. /**
  10996. * Linearly interpolates this color's RGB values toward the RGB values of the
  10997. * given color. The alpha argument can be thought of as the ratio between
  10998. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  10999. *
  11000. * @param {Color} color - The color to converge on.
  11001. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11002. * @return {Color} A reference to this color.
  11003. */
  11004. lerp( color, alpha ) {
  11005. this.r += ( color.r - this.r ) * alpha;
  11006. this.g += ( color.g - this.g ) * alpha;
  11007. this.b += ( color.b - this.b ) * alpha;
  11008. return this;
  11009. }
  11010. /**
  11011. * Linearly interpolates between the given colors and stores the result in this instance.
  11012. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  11013. * is the first and `1.0` is the second color.
  11014. *
  11015. * @param {Color} color1 - The first color.
  11016. * @param {Color} color2 - The second color.
  11017. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11018. * @return {Color} A reference to this color.
  11019. */
  11020. lerpColors( color1, color2, alpha ) {
  11021. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  11022. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  11023. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  11024. return this;
  11025. }
  11026. /**
  11027. * Linearly interpolates this color's HSL values toward the HSL values of the
  11028. * given color. It differs from {@link Color#lerp} by not interpolating straight
  11029. * from one color to the other, but instead going through all the hues in between
  11030. * those two colors. The alpha argument can be thought of as the ratio between
  11031. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  11032. *
  11033. * @param {Color} color - The color to converge on.
  11034. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11035. * @return {Color} A reference to this color.
  11036. */
  11037. lerpHSL( color, alpha ) {
  11038. this.getHSL( _hslA );
  11039. color.getHSL( _hslB );
  11040. const h = lerp( _hslA.h, _hslB.h, alpha );
  11041. const s = lerp( _hslA.s, _hslB.s, alpha );
  11042. const l = lerp( _hslA.l, _hslB.l, alpha );
  11043. this.setHSL( h, s, l );
  11044. return this;
  11045. }
  11046. /**
  11047. * Sets the color's RGB components from the given 3D vector.
  11048. *
  11049. * @param {Vector3} v - The vector to set.
  11050. * @return {Color} A reference to this color.
  11051. */
  11052. setFromVector3( v ) {
  11053. this.r = v.x;
  11054. this.g = v.y;
  11055. this.b = v.z;
  11056. return this;
  11057. }
  11058. /**
  11059. * Transforms this color with the given 3x3 matrix.
  11060. *
  11061. * @param {Matrix3} m - The matrix.
  11062. * @return {Color} A reference to this color.
  11063. */
  11064. applyMatrix3( m ) {
  11065. const r = this.r, g = this.g, b = this.b;
  11066. const e = m.elements;
  11067. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  11068. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  11069. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  11070. return this;
  11071. }
  11072. /**
  11073. * Returns `true` if this color is equal with the given one.
  11074. *
  11075. * @param {Color} c - The color to test for equality.
  11076. * @return {boolean} Whether this bounding color is equal with the given one.
  11077. */
  11078. equals( c ) {
  11079. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  11080. }
  11081. /**
  11082. * Sets this color's RGB components from the given array.
  11083. *
  11084. * @param {Array<number>} array - An array holding the RGB values.
  11085. * @param {number} [offset=0] - The offset into the array.
  11086. * @return {Color} A reference to this color.
  11087. */
  11088. fromArray( array, offset = 0 ) {
  11089. this.r = array[ offset ];
  11090. this.g = array[ offset + 1 ];
  11091. this.b = array[ offset + 2 ];
  11092. return this;
  11093. }
  11094. /**
  11095. * Writes the RGB components of this color to the given array. If no array is provided,
  11096. * the method returns a new instance.
  11097. *
  11098. * @param {Array<number>} [array=[]] - The target array holding the color components.
  11099. * @param {number} [offset=0] - Index of the first element in the array.
  11100. * @return {Array<number>} The color components.
  11101. */
  11102. toArray( array = [], offset = 0 ) {
  11103. array[ offset ] = this.r;
  11104. array[ offset + 1 ] = this.g;
  11105. array[ offset + 2 ] = this.b;
  11106. return array;
  11107. }
  11108. /**
  11109. * Sets the components of this color from the given buffer attribute.
  11110. *
  11111. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  11112. * @param {number} index - The index into the attribute.
  11113. * @return {Color} A reference to this color.
  11114. */
  11115. fromBufferAttribute( attribute, index ) {
  11116. this.r = attribute.getX( index );
  11117. this.g = attribute.getY( index );
  11118. this.b = attribute.getZ( index );
  11119. return this;
  11120. }
  11121. /**
  11122. * This methods defines the serialization result of this class. Returns the color
  11123. * as a hexadecimal value.
  11124. *
  11125. * @return {number} The hexadecimal value.
  11126. */
  11127. toJSON() {
  11128. return this.getHex();
  11129. }
  11130. *[ Symbol.iterator ]() {
  11131. yield this.r;
  11132. yield this.g;
  11133. yield this.b;
  11134. }
  11135. }
  11136. const _color = /*@__PURE__*/ new Color();
  11137. /**
  11138. * A dictionary with X11 color names.
  11139. *
  11140. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  11141. *
  11142. * @static
  11143. * @type {Object}
  11144. */
  11145. Color.NAMES = _colorKeywords;
  11146. /**
  11147. * This class can be used to define an exponential squared fog,
  11148. * which gives a clear view near the camera and a faster than exponentially
  11149. * densening fog farther from the camera.
  11150. *
  11151. * ```js
  11152. * const scene = new THREE.Scene();
  11153. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  11154. * ```
  11155. */
  11156. class FogExp2 {
  11157. /**
  11158. * Constructs a new fog.
  11159. *
  11160. * @param {number|Color} color - The fog's color.
  11161. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  11162. */
  11163. constructor( color, density = 0.00025 ) {
  11164. /**
  11165. * This flag can be used for type testing.
  11166. *
  11167. * @type {boolean}
  11168. * @readonly
  11169. * @default true
  11170. */
  11171. this.isFogExp2 = true;
  11172. /**
  11173. * The name of the fog.
  11174. *
  11175. * @type {string}
  11176. */
  11177. this.name = '';
  11178. /**
  11179. * The fog's color.
  11180. *
  11181. * @type {Color}
  11182. */
  11183. this.color = new Color( color );
  11184. /**
  11185. * Defines how fast the fog will grow dense.
  11186. *
  11187. * @type {number}
  11188. * @default 0.00025
  11189. */
  11190. this.density = density;
  11191. }
  11192. /**
  11193. * Returns a new fog with copied values from this instance.
  11194. *
  11195. * @return {FogExp2} A clone of this instance.
  11196. */
  11197. clone() {
  11198. return new FogExp2( this.color, this.density );
  11199. }
  11200. /**
  11201. * Serializes the fog into JSON.
  11202. *
  11203. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11204. * @return {Object} A JSON object representing the serialized fog
  11205. */
  11206. toJSON( /* meta */ ) {
  11207. return {
  11208. type: 'FogExp2',
  11209. name: this.name,
  11210. color: this.color.getHex(),
  11211. density: this.density
  11212. };
  11213. }
  11214. }
  11215. /**
  11216. * This class can be used to define a linear fog that grows linearly denser
  11217. * with the distance.
  11218. *
  11219. * ```js
  11220. * const scene = new THREE.Scene();
  11221. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  11222. * ```
  11223. */
  11224. class Fog {
  11225. /**
  11226. * Constructs a new fog.
  11227. *
  11228. * @param {number|Color} color - The fog's color.
  11229. * @param {number} [near=1] - The minimum distance to start applying fog.
  11230. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  11231. */
  11232. constructor( color, near = 1, far = 1000 ) {
  11233. /**
  11234. * This flag can be used for type testing.
  11235. *
  11236. * @type {boolean}
  11237. * @readonly
  11238. * @default true
  11239. */
  11240. this.isFog = true;
  11241. /**
  11242. * The name of the fog.
  11243. *
  11244. * @type {string}
  11245. */
  11246. this.name = '';
  11247. /**
  11248. * The fog's color.
  11249. *
  11250. * @type {Color}
  11251. */
  11252. this.color = new Color( color );
  11253. /**
  11254. * The minimum distance to start applying fog. Objects that are less than
  11255. * `near` units from the active camera won't be affected by fog.
  11256. *
  11257. * @type {number}
  11258. * @default 1
  11259. */
  11260. this.near = near;
  11261. /**
  11262. * The maximum distance at which fog stops being calculated and applied.
  11263. * Objects that are more than `far` units away from the active camera won't
  11264. * be affected by fog.
  11265. *
  11266. * @type {number}
  11267. * @default 1000
  11268. */
  11269. this.far = far;
  11270. }
  11271. /**
  11272. * Returns a new fog with copied values from this instance.
  11273. *
  11274. * @return {Fog} A clone of this instance.
  11275. */
  11276. clone() {
  11277. return new Fog( this.color, this.near, this.far );
  11278. }
  11279. /**
  11280. * Serializes the fog into JSON.
  11281. *
  11282. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11283. * @return {Object} A JSON object representing the serialized fog
  11284. */
  11285. toJSON( /* meta */ ) {
  11286. return {
  11287. type: 'Fog',
  11288. name: this.name,
  11289. color: this.color.getHex(),
  11290. near: this.near,
  11291. far: this.far
  11292. };
  11293. }
  11294. }
  11295. /**
  11296. * Scenes allow you to set up what is to be rendered and where by three.js.
  11297. * This is where you place 3D objects like meshes, lines or lights.
  11298. *
  11299. * @augments Object3D
  11300. */
  11301. class Scene extends Object3D {
  11302. /**
  11303. * Constructs a new scene.
  11304. */
  11305. constructor() {
  11306. super();
  11307. /**
  11308. * This flag can be used for type testing.
  11309. *
  11310. * @type {boolean}
  11311. * @readonly
  11312. * @default true
  11313. */
  11314. this.isScene = true;
  11315. this.type = 'Scene';
  11316. /**
  11317. * Defines the background of the scene. Valid inputs are:
  11318. *
  11319. * - A color for defining a uniform colored background.
  11320. * - A texture for defining a (flat) textured background.
  11321. * - Cube textures or equirectangular textures for defining a skybox.
  11322. *
  11323. * @type {?(Color|Texture)}
  11324. * @default null
  11325. */
  11326. this.background = null;
  11327. /**
  11328. * Sets the environment map for all physical materials in the scene. However,
  11329. * it's not possible to overwrite an existing texture assigned to the `envMap`
  11330. * material property.
  11331. *
  11332. * @type {?Texture}
  11333. * @default null
  11334. */
  11335. this.environment = null;
  11336. /**
  11337. * A fog instance defining the type of fog that affects everything
  11338. * rendered in the scene.
  11339. *
  11340. * @type {?(Fog|FogExp2)}
  11341. * @default null
  11342. */
  11343. this.fog = null;
  11344. /**
  11345. * Sets the blurriness of the background. Only influences environment maps
  11346. * assigned to {@link Scene#background}. Valid input is a float between `0`
  11347. * and `1`.
  11348. *
  11349. * @type {number}
  11350. * @default 0
  11351. */
  11352. this.backgroundBlurriness = 0;
  11353. /**
  11354. * Attenuates the color of the background. Only applies to background textures.
  11355. *
  11356. * @type {number}
  11357. * @default 1
  11358. */
  11359. this.backgroundIntensity = 1;
  11360. /**
  11361. * The rotation of the background in radians. Only influences environment maps
  11362. * assigned to {@link Scene#background}.
  11363. *
  11364. * @type {Euler}
  11365. * @default (0,0,0)
  11366. */
  11367. this.backgroundRotation = new Euler();
  11368. /**
  11369. * Attenuates the color of the environment. Only influences environment maps
  11370. * assigned to {@link Scene#environment}.
  11371. *
  11372. * @type {number}
  11373. * @default 1
  11374. */
  11375. this.environmentIntensity = 1;
  11376. /**
  11377. * The rotation of the environment map in radians. Only influences physical materials
  11378. * in the scene when {@link Scene#environment} is used.
  11379. *
  11380. * @type {Euler}
  11381. * @default (0,0,0)
  11382. */
  11383. this.environmentRotation = new Euler();
  11384. /**
  11385. * Forces everything in the scene to be rendered with the defined material. It is possible
  11386. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  11387. *
  11388. * @type {?Material}
  11389. * @default null
  11390. */
  11391. this.overrideMaterial = null;
  11392. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  11393. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  11394. }
  11395. }
  11396. copy( source, recursive ) {
  11397. super.copy( source, recursive );
  11398. if ( source.background !== null ) this.background = source.background.clone();
  11399. if ( source.environment !== null ) this.environment = source.environment.clone();
  11400. if ( source.fog !== null ) this.fog = source.fog.clone();
  11401. this.backgroundBlurriness = source.backgroundBlurriness;
  11402. this.backgroundIntensity = source.backgroundIntensity;
  11403. this.backgroundRotation.copy( source.backgroundRotation );
  11404. this.environmentIntensity = source.environmentIntensity;
  11405. this.environmentRotation.copy( source.environmentRotation );
  11406. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  11407. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11408. return this;
  11409. }
  11410. toJSON( meta ) {
  11411. const data = super.toJSON( meta );
  11412. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  11413. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  11414. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  11415. data.object.backgroundRotation = this.backgroundRotation.toArray();
  11416. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  11417. data.object.environmentRotation = this.environmentRotation.toArray();
  11418. return data;
  11419. }
  11420. }
  11421. const _v0$2 = /*@__PURE__*/ new Vector3();
  11422. const _v1$5 = /*@__PURE__*/ new Vector3();
  11423. const _v2$4 = /*@__PURE__*/ new Vector3();
  11424. const _v3$2 = /*@__PURE__*/ new Vector3();
  11425. const _vab = /*@__PURE__*/ new Vector3();
  11426. const _vac = /*@__PURE__*/ new Vector3();
  11427. const _vbc = /*@__PURE__*/ new Vector3();
  11428. const _vap = /*@__PURE__*/ new Vector3();
  11429. const _vbp = /*@__PURE__*/ new Vector3();
  11430. const _vcp = /*@__PURE__*/ new Vector3();
  11431. const _v40 = /*@__PURE__*/ new Vector4();
  11432. const _v41 = /*@__PURE__*/ new Vector4();
  11433. const _v42 = /*@__PURE__*/ new Vector4();
  11434. /**
  11435. * A geometric triangle as defined by three vectors representing its three corners.
  11436. */
  11437. class Triangle {
  11438. /**
  11439. * Constructs a new triangle.
  11440. *
  11441. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11442. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11443. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11444. */
  11445. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11446. /**
  11447. * The first corner of the triangle.
  11448. *
  11449. * @type {Vector3}
  11450. */
  11451. this.a = a;
  11452. /**
  11453. * The second corner of the triangle.
  11454. *
  11455. * @type {Vector3}
  11456. */
  11457. this.b = b;
  11458. /**
  11459. * The third corner of the triangle.
  11460. *
  11461. * @type {Vector3}
  11462. */
  11463. this.c = c;
  11464. }
  11465. /**
  11466. * Computes the normal vector of a triangle.
  11467. *
  11468. * @param {Vector3} a - The first corner of the triangle.
  11469. * @param {Vector3} b - The second corner of the triangle.
  11470. * @param {Vector3} c - The third corner of the triangle.
  11471. * @param {Vector3} target - The target vector that is used to store the method's result.
  11472. * @return {Vector3} The triangle's normal.
  11473. */
  11474. static getNormal( a, b, c, target ) {
  11475. target.subVectors( c, b );
  11476. _v0$2.subVectors( a, b );
  11477. target.cross( _v0$2 );
  11478. const targetLengthSq = target.lengthSq();
  11479. if ( targetLengthSq > 0 ) {
  11480. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11481. }
  11482. return target.set( 0, 0, 0 );
  11483. }
  11484. /**
  11485. * Computes a barycentric coordinates from the given vector.
  11486. * Returns `null` if the triangle is degenerate.
  11487. *
  11488. * @param {Vector3} point - A point in 3D space.
  11489. * @param {Vector3} a - The first corner of the triangle.
  11490. * @param {Vector3} b - The second corner of the triangle.
  11491. * @param {Vector3} c - The third corner of the triangle.
  11492. * @param {Vector3} target - The target vector that is used to store the method's result.
  11493. * @return {?Vector3} The barycentric coordinates for the given point
  11494. */
  11495. static getBarycoord( point, a, b, c, target ) {
  11496. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11497. _v0$2.subVectors( c, a );
  11498. _v1$5.subVectors( b, a );
  11499. _v2$4.subVectors( point, a );
  11500. const dot00 = _v0$2.dot( _v0$2 );
  11501. const dot01 = _v0$2.dot( _v1$5 );
  11502. const dot02 = _v0$2.dot( _v2$4 );
  11503. const dot11 = _v1$5.dot( _v1$5 );
  11504. const dot12 = _v1$5.dot( _v2$4 );
  11505. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11506. // collinear or singular triangle
  11507. if ( denom === 0 ) {
  11508. target.set( 0, 0, 0 );
  11509. return null;
  11510. }
  11511. const invDenom = 1 / denom;
  11512. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11513. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11514. // barycentric coordinates must always sum to 1
  11515. return target.set( 1 - u - v, v, u );
  11516. }
  11517. /**
  11518. * Returns `true` if the given point, when projected onto the plane of the
  11519. * triangle, lies within the triangle.
  11520. *
  11521. * @param {Vector3} point - The point in 3D space to test.
  11522. * @param {Vector3} a - The first corner of the triangle.
  11523. * @param {Vector3} b - The second corner of the triangle.
  11524. * @param {Vector3} c - The third corner of the triangle.
  11525. * @return {boolean} Whether the given point, when projected onto the plane of the
  11526. * triangle, lies within the triangle or not.
  11527. */
  11528. static containsPoint( point, a, b, c ) {
  11529. // if the triangle is degenerate then we can't contain a point
  11530. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11531. return false;
  11532. }
  11533. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11534. }
  11535. /**
  11536. * Computes the value barycentrically interpolated for the given point on the
  11537. * triangle. Returns `null` if the triangle is degenerate.
  11538. *
  11539. * @param {Vector3} point - Position of interpolated point.
  11540. * @param {Vector3} p1 - The first corner of the triangle.
  11541. * @param {Vector3} p2 - The second corner of the triangle.
  11542. * @param {Vector3} p3 - The third corner of the triangle.
  11543. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11544. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11545. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11546. * @param {Vector3} target - The target vector that is used to store the method's result.
  11547. * @return {?Vector3} The interpolated value.
  11548. */
  11549. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11550. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11551. target.x = 0;
  11552. target.y = 0;
  11553. if ( 'z' in target ) target.z = 0;
  11554. if ( 'w' in target ) target.w = 0;
  11555. return null;
  11556. }
  11557. target.setScalar( 0 );
  11558. target.addScaledVector( v1, _v3$2.x );
  11559. target.addScaledVector( v2, _v3$2.y );
  11560. target.addScaledVector( v3, _v3$2.z );
  11561. return target;
  11562. }
  11563. /**
  11564. * Computes the value barycentrically interpolated for the given attribute and indices.
  11565. *
  11566. * @param {BufferAttribute} attr - The attribute to interpolate.
  11567. * @param {number} i1 - Index of first vertex.
  11568. * @param {number} i2 - Index of second vertex.
  11569. * @param {number} i3 - Index of third vertex.
  11570. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11571. * @param {Vector3} target - The target vector that is used to store the method's result.
  11572. * @return {Vector3} The interpolated attribute value.
  11573. */
  11574. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11575. _v40.setScalar( 0 );
  11576. _v41.setScalar( 0 );
  11577. _v42.setScalar( 0 );
  11578. _v40.fromBufferAttribute( attr, i1 );
  11579. _v41.fromBufferAttribute( attr, i2 );
  11580. _v42.fromBufferAttribute( attr, i3 );
  11581. target.setScalar( 0 );
  11582. target.addScaledVector( _v40, barycoord.x );
  11583. target.addScaledVector( _v41, barycoord.y );
  11584. target.addScaledVector( _v42, barycoord.z );
  11585. return target;
  11586. }
  11587. /**
  11588. * Returns `true` if the triangle is oriented towards the given direction.
  11589. *
  11590. * @param {Vector3} a - The first corner of the triangle.
  11591. * @param {Vector3} b - The second corner of the triangle.
  11592. * @param {Vector3} c - The third corner of the triangle.
  11593. * @param {Vector3} direction - The (normalized) direction vector.
  11594. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11595. */
  11596. static isFrontFacing( a, b, c, direction ) {
  11597. _v0$2.subVectors( c, b );
  11598. _v1$5.subVectors( a, b );
  11599. // strictly front facing
  11600. return ( _v0$2.cross( _v1$5 ).dot( direction ) < 0 ) ? true : false;
  11601. }
  11602. /**
  11603. * Sets the triangle's vertices by copying the given values.
  11604. *
  11605. * @param {Vector3} a - The first corner of the triangle.
  11606. * @param {Vector3} b - The second corner of the triangle.
  11607. * @param {Vector3} c - The third corner of the triangle.
  11608. * @return {Triangle} A reference to this triangle.
  11609. */
  11610. set( a, b, c ) {
  11611. this.a.copy( a );
  11612. this.b.copy( b );
  11613. this.c.copy( c );
  11614. return this;
  11615. }
  11616. /**
  11617. * Sets the triangle's vertices by copying the given array values.
  11618. *
  11619. * @param {Array<Vector3>} points - An array with 3D points.
  11620. * @param {number} i0 - The array index representing the first corner of the triangle.
  11621. * @param {number} i1 - The array index representing the second corner of the triangle.
  11622. * @param {number} i2 - The array index representing the third corner of the triangle.
  11623. * @return {Triangle} A reference to this triangle.
  11624. */
  11625. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11626. this.a.copy( points[ i0 ] );
  11627. this.b.copy( points[ i1 ] );
  11628. this.c.copy( points[ i2 ] );
  11629. return this;
  11630. }
  11631. /**
  11632. * Sets the triangle's vertices by copying the given attribute values.
  11633. *
  11634. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11635. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11636. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11637. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11638. * @return {Triangle} A reference to this triangle.
  11639. */
  11640. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11641. this.a.fromBufferAttribute( attribute, i0 );
  11642. this.b.fromBufferAttribute( attribute, i1 );
  11643. this.c.fromBufferAttribute( attribute, i2 );
  11644. return this;
  11645. }
  11646. /**
  11647. * Returns a new triangle with copied values from this instance.
  11648. *
  11649. * @return {Triangle} A clone of this instance.
  11650. */
  11651. clone() {
  11652. return new this.constructor().copy( this );
  11653. }
  11654. /**
  11655. * Copies the values of the given triangle to this instance.
  11656. *
  11657. * @param {Triangle} triangle - The triangle to copy.
  11658. * @return {Triangle} A reference to this triangle.
  11659. */
  11660. copy( triangle ) {
  11661. this.a.copy( triangle.a );
  11662. this.b.copy( triangle.b );
  11663. this.c.copy( triangle.c );
  11664. return this;
  11665. }
  11666. /**
  11667. * Computes the area of the triangle.
  11668. *
  11669. * @return {number} The triangle's area.
  11670. */
  11671. getArea() {
  11672. _v0$2.subVectors( this.c, this.b );
  11673. _v1$5.subVectors( this.a, this.b );
  11674. return _v0$2.cross( _v1$5 ).length() * 0.5;
  11675. }
  11676. /**
  11677. * Computes the midpoint of the triangle.
  11678. *
  11679. * @param {Vector3} target - The target vector that is used to store the method's result.
  11680. * @return {Vector3} The triangle's midpoint.
  11681. */
  11682. getMidpoint( target ) {
  11683. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11684. }
  11685. /**
  11686. * Computes the normal of the triangle.
  11687. *
  11688. * @param {Vector3} target - The target vector that is used to store the method's result.
  11689. * @return {Vector3} The triangle's normal.
  11690. */
  11691. getNormal( target ) {
  11692. return Triangle.getNormal( this.a, this.b, this.c, target );
  11693. }
  11694. /**
  11695. * Computes a plane the triangle lies within.
  11696. *
  11697. * @param {Plane} target - The target vector that is used to store the method's result.
  11698. * @return {Plane} The plane the triangle lies within.
  11699. */
  11700. getPlane( target ) {
  11701. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11702. }
  11703. /**
  11704. * Computes a barycentric coordinates from the given vector.
  11705. * Returns `null` if the triangle is degenerate.
  11706. *
  11707. * @param {Vector3} point - A point in 3D space.
  11708. * @param {Vector3} target - The target vector that is used to store the method's result.
  11709. * @return {?Vector3} The barycentric coordinates for the given point
  11710. */
  11711. getBarycoord( point, target ) {
  11712. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11713. }
  11714. /**
  11715. * Computes the value barycentrically interpolated for the given point on the
  11716. * triangle. Returns `null` if the triangle is degenerate.
  11717. *
  11718. * @param {Vector3} point - Position of interpolated point.
  11719. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11720. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11721. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11722. * @param {Vector3} target - The target vector that is used to store the method's result.
  11723. * @return {?Vector3} The interpolated value.
  11724. */
  11725. getInterpolation( point, v1, v2, v3, target ) {
  11726. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11727. }
  11728. /**
  11729. * Returns `true` if the given point, when projected onto the plane of the
  11730. * triangle, lies within the triangle.
  11731. *
  11732. * @param {Vector3} point - The point in 3D space to test.
  11733. * @return {boolean} Whether the given point, when projected onto the plane of the
  11734. * triangle, lies within the triangle or not.
  11735. */
  11736. containsPoint( point ) {
  11737. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11738. }
  11739. /**
  11740. * Returns `true` if the triangle is oriented towards the given direction.
  11741. *
  11742. * @param {Vector3} direction - The (normalized) direction vector.
  11743. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11744. */
  11745. isFrontFacing( direction ) {
  11746. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11747. }
  11748. /**
  11749. * Returns `true` if this triangle intersects with the given box.
  11750. *
  11751. * @param {Box3} box - The box to intersect.
  11752. * @return {boolean} Whether this triangle intersects with the given box or not.
  11753. */
  11754. intersectsBox( box ) {
  11755. return box.intersectsTriangle( this );
  11756. }
  11757. /**
  11758. * Returns the closest point on the triangle to the given point.
  11759. *
  11760. * @param {Vector3} p - The point to compute the closest point for.
  11761. * @param {Vector3} target - The target vector that is used to store the method's result.
  11762. * @return {Vector3} The closest point on the triangle.
  11763. */
  11764. closestPointToPoint( p, target ) {
  11765. const a = this.a, b = this.b, c = this.c;
  11766. let v, w;
  11767. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11768. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11769. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11770. // basically, we're distinguishing which of the voronoi regions of the triangle
  11771. // the point lies in with the minimum amount of redundant computation.
  11772. _vab.subVectors( b, a );
  11773. _vac.subVectors( c, a );
  11774. _vap.subVectors( p, a );
  11775. const d1 = _vab.dot( _vap );
  11776. const d2 = _vac.dot( _vap );
  11777. if ( d1 <= 0 && d2 <= 0 ) {
  11778. // vertex region of A; barycentric coords (1, 0, 0)
  11779. return target.copy( a );
  11780. }
  11781. _vbp.subVectors( p, b );
  11782. const d3 = _vab.dot( _vbp );
  11783. const d4 = _vac.dot( _vbp );
  11784. if ( d3 >= 0 && d4 <= d3 ) {
  11785. // vertex region of B; barycentric coords (0, 1, 0)
  11786. return target.copy( b );
  11787. }
  11788. const vc = d1 * d4 - d3 * d2;
  11789. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11790. v = d1 / ( d1 - d3 );
  11791. // edge region of AB; barycentric coords (1-v, v, 0)
  11792. return target.copy( a ).addScaledVector( _vab, v );
  11793. }
  11794. _vcp.subVectors( p, c );
  11795. const d5 = _vab.dot( _vcp );
  11796. const d6 = _vac.dot( _vcp );
  11797. if ( d6 >= 0 && d5 <= d6 ) {
  11798. // vertex region of C; barycentric coords (0, 0, 1)
  11799. return target.copy( c );
  11800. }
  11801. const vb = d5 * d2 - d1 * d6;
  11802. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11803. w = d2 / ( d2 - d6 );
  11804. // edge region of AC; barycentric coords (1-w, 0, w)
  11805. return target.copy( a ).addScaledVector( _vac, w );
  11806. }
  11807. const va = d3 * d6 - d5 * d4;
  11808. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11809. _vbc.subVectors( c, b );
  11810. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11811. // edge region of BC; barycentric coords (0, 1-w, w)
  11812. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11813. }
  11814. // face region
  11815. const denom = 1 / ( va + vb + vc );
  11816. // u = va * denom
  11817. v = vb * denom;
  11818. w = vc * denom;
  11819. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11820. }
  11821. /**
  11822. * Returns `true` if this triangle is equal with the given one.
  11823. *
  11824. * @param {Triangle} triangle - The triangle to test for equality.
  11825. * @return {boolean} Whether this triangle is equal with the given one.
  11826. */
  11827. equals( triangle ) {
  11828. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11829. }
  11830. }
  11831. /**
  11832. * Represents an axis-aligned bounding box (AABB) in 3D space.
  11833. */
  11834. class Box3 {
  11835. /**
  11836. * Constructs a new bounding box.
  11837. *
  11838. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  11839. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  11840. */
  11841. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  11842. /**
  11843. * This flag can be used for type testing.
  11844. *
  11845. * @type {boolean}
  11846. * @readonly
  11847. * @default true
  11848. */
  11849. this.isBox3 = true;
  11850. /**
  11851. * The lower boundary of the box.
  11852. *
  11853. * @type {Vector3}
  11854. */
  11855. this.min = min;
  11856. /**
  11857. * The upper boundary of the box.
  11858. *
  11859. * @type {Vector3}
  11860. */
  11861. this.max = max;
  11862. }
  11863. /**
  11864. * Sets the lower and upper boundaries of this box.
  11865. * Please note that this method only copies the values from the given objects.
  11866. *
  11867. * @param {Vector3} min - The lower boundary of the box.
  11868. * @param {Vector3} max - The upper boundary of the box.
  11869. * @return {Box3} A reference to this bounding box.
  11870. */
  11871. set( min, max ) {
  11872. this.min.copy( min );
  11873. this.max.copy( max );
  11874. return this;
  11875. }
  11876. /**
  11877. * Sets the upper and lower bounds of this box so it encloses the position data
  11878. * in the given array.
  11879. *
  11880. * @param {Array<number>} array - An array holding 3D position data.
  11881. * @return {Box3} A reference to this bounding box.
  11882. */
  11883. setFromArray( array ) {
  11884. this.makeEmpty();
  11885. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  11886. this.expandByPoint( _vector$b.fromArray( array, i ) );
  11887. }
  11888. return this;
  11889. }
  11890. /**
  11891. * Sets the upper and lower bounds of this box so it encloses the position data
  11892. * in the given buffer attribute.
  11893. *
  11894. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  11895. * @return {Box3} A reference to this bounding box.
  11896. */
  11897. setFromBufferAttribute( attribute ) {
  11898. this.makeEmpty();
  11899. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  11900. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  11901. }
  11902. return this;
  11903. }
  11904. /**
  11905. * Sets the upper and lower bounds of this box so it encloses the position data
  11906. * in the given array.
  11907. *
  11908. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  11909. * @return {Box3} A reference to this bounding box.
  11910. */
  11911. setFromPoints( points ) {
  11912. this.makeEmpty();
  11913. for ( let i = 0, il = points.length; i < il; i ++ ) {
  11914. this.expandByPoint( points[ i ] );
  11915. }
  11916. return this;
  11917. }
  11918. /**
  11919. * Centers this box on the given center vector and sets this box's width, height and
  11920. * depth to the given size values.
  11921. *
  11922. * @param {Vector3} center - The center of the box.
  11923. * @param {Vector3} size - The x, y and z dimensions of the box.
  11924. * @return {Box3} A reference to this bounding box.
  11925. */
  11926. setFromCenterAndSize( center, size ) {
  11927. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  11928. this.min.copy( center ).sub( halfSize );
  11929. this.max.copy( center ).add( halfSize );
  11930. return this;
  11931. }
  11932. /**
  11933. * Computes the world-axis-aligned bounding box for the given 3D object
  11934. * (including its children), accounting for the object's, and children's,
  11935. * world transforms. The function may result in a larger box than strictly necessary.
  11936. *
  11937. * @param {Object3D} object - The 3D object to compute the bounding box for.
  11938. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  11939. * world-axis-aligned bounding box at the expense of more computation.
  11940. * @return {Box3} A reference to this bounding box.
  11941. */
  11942. setFromObject( object, precise = false ) {
  11943. this.makeEmpty();
  11944. return this.expandByObject( object, precise );
  11945. }
  11946. /**
  11947. * Returns a new box with copied values from this instance.
  11948. *
  11949. * @return {Box3} A clone of this instance.
  11950. */
  11951. clone() {
  11952. return new this.constructor().copy( this );
  11953. }
  11954. /**
  11955. * Copies the values of the given box to this instance.
  11956. *
  11957. * @param {Box3} box - The box to copy.
  11958. * @return {Box3} A reference to this bounding box.
  11959. */
  11960. copy( box ) {
  11961. this.min.copy( box.min );
  11962. this.max.copy( box.max );
  11963. return this;
  11964. }
  11965. /**
  11966. * Makes this box empty which means in encloses a zero space in 3D.
  11967. *
  11968. * @return {Box3} A reference to this bounding box.
  11969. */
  11970. makeEmpty() {
  11971. this.min.x = this.min.y = this.min.z = + Infinity;
  11972. this.max.x = this.max.y = this.max.z = - Infinity;
  11973. return this;
  11974. }
  11975. /**
  11976. * Returns true if this box includes zero points within its bounds.
  11977. * Note that a box with equal lower and upper bounds still includes one
  11978. * point, the one both bounds share.
  11979. *
  11980. * @return {boolean} Whether this box is empty or not.
  11981. */
  11982. isEmpty() {
  11983. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  11984. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  11985. }
  11986. /**
  11987. * Returns the center point of this box.
  11988. *
  11989. * @param {Vector3} target - The target vector that is used to store the method's result.
  11990. * @return {Vector3} The center point.
  11991. */
  11992. getCenter( target ) {
  11993. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  11994. }
  11995. /**
  11996. * Returns the dimensions of this box.
  11997. *
  11998. * @param {Vector3} target - The target vector that is used to store the method's result.
  11999. * @return {Vector3} The size.
  12000. */
  12001. getSize( target ) {
  12002. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  12003. }
  12004. /**
  12005. * Expands the boundaries of this box to include the given point.
  12006. *
  12007. * @param {Vector3} point - The point that should be included by the bounding box.
  12008. * @return {Box3} A reference to this bounding box.
  12009. */
  12010. expandByPoint( point ) {
  12011. this.min.min( point );
  12012. this.max.max( point );
  12013. return this;
  12014. }
  12015. /**
  12016. * Expands this box equilaterally by the given vector. The width of this
  12017. * box will be expanded by the x component of the vector in both
  12018. * directions. The height of this box will be expanded by the y component of
  12019. * the vector in both directions. The depth of this box will be
  12020. * expanded by the z component of the vector in both directions.
  12021. *
  12022. * @param {Vector3} vector - The vector that should expand the bounding box.
  12023. * @return {Box3} A reference to this bounding box.
  12024. */
  12025. expandByVector( vector ) {
  12026. this.min.sub( vector );
  12027. this.max.add( vector );
  12028. return this;
  12029. }
  12030. /**
  12031. * Expands each dimension of the box by the given scalar. If negative, the
  12032. * dimensions of the box will be contracted.
  12033. *
  12034. * @param {number} scalar - The scalar value that should expand the bounding box.
  12035. * @return {Box3} A reference to this bounding box.
  12036. */
  12037. expandByScalar( scalar ) {
  12038. this.min.addScalar( - scalar );
  12039. this.max.addScalar( scalar );
  12040. return this;
  12041. }
  12042. /**
  12043. * Expands the boundaries of this box to include the given 3D object and
  12044. * its children, accounting for the object's, and children's, world
  12045. * transforms. The function may result in a larger box than strictly
  12046. * necessary (unless the precise parameter is set to true).
  12047. *
  12048. * @param {Object3D} object - The 3D object that should expand the bounding box.
  12049. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  12050. * as little as necessary at the expense of more computation.
  12051. * @return {Box3} A reference to this bounding box.
  12052. */
  12053. expandByObject( object, precise = false ) {
  12054. // Computes the world-axis-aligned bounding box of an object (including its children),
  12055. // accounting for both the object's, and children's, world transforms
  12056. object.updateWorldMatrix( false, false );
  12057. const geometry = object.geometry;
  12058. if ( geometry !== undefined ) {
  12059. const positionAttribute = geometry.getAttribute( 'position' );
  12060. // precise AABB computation based on vertex data requires at least a position attribute.
  12061. // instancing isn't supported so far and uses the normal (conservative) code path.
  12062. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  12063. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  12064. if ( object.isMesh === true ) {
  12065. object.getVertexPosition( i, _vector$b );
  12066. } else {
  12067. _vector$b.fromBufferAttribute( positionAttribute, i );
  12068. }
  12069. _vector$b.applyMatrix4( object.matrixWorld );
  12070. this.expandByPoint( _vector$b );
  12071. }
  12072. } else {
  12073. if ( object.boundingBox !== undefined ) {
  12074. // object-level bounding box
  12075. if ( object.boundingBox === null ) {
  12076. object.computeBoundingBox();
  12077. }
  12078. _box$4.copy( object.boundingBox );
  12079. } else {
  12080. // geometry-level bounding box
  12081. if ( geometry.boundingBox === null ) {
  12082. geometry.computeBoundingBox();
  12083. }
  12084. _box$4.copy( geometry.boundingBox );
  12085. }
  12086. _box$4.applyMatrix4( object.matrixWorld );
  12087. this.union( _box$4 );
  12088. }
  12089. }
  12090. const children = object.children;
  12091. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12092. this.expandByObject( children[ i ], precise );
  12093. }
  12094. return this;
  12095. }
  12096. /**
  12097. * Returns `true` if the given point lies within or on the boundaries of this box.
  12098. *
  12099. * @param {Vector3} point - The point to test.
  12100. * @return {boolean} Whether the bounding box contains the given point or not.
  12101. */
  12102. containsPoint( point ) {
  12103. return point.x >= this.min.x && point.x <= this.max.x &&
  12104. point.y >= this.min.y && point.y <= this.max.y &&
  12105. point.z >= this.min.z && point.z <= this.max.z;
  12106. }
  12107. /**
  12108. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  12109. * If this box and the given one are identical, this function also returns `true`.
  12110. *
  12111. * @param {Box3} box - The bounding box to test.
  12112. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  12113. */
  12114. containsBox( box ) {
  12115. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  12116. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  12117. this.min.z <= box.min.z && box.max.z <= this.max.z;
  12118. }
  12119. /**
  12120. * Returns a point as a proportion of this box's width, height and depth.
  12121. *
  12122. * @param {Vector3} point - A point in 3D space.
  12123. * @param {Vector3} target - The target vector that is used to store the method's result.
  12124. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  12125. */
  12126. getParameter( point, target ) {
  12127. // This can potentially have a divide by zero if the box
  12128. // has a size dimension of 0.
  12129. return target.set(
  12130. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  12131. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  12132. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  12133. );
  12134. }
  12135. /**
  12136. * Returns `true` if the given bounding box intersects with this bounding box.
  12137. *
  12138. * @param {Box3} box - The bounding box to test.
  12139. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  12140. */
  12141. intersectsBox( box ) {
  12142. // using 6 splitting planes to rule out intersections.
  12143. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  12144. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  12145. box.max.z >= this.min.z && box.min.z <= this.max.z;
  12146. }
  12147. /**
  12148. * Returns `true` if the given bounding sphere intersects with this bounding box.
  12149. *
  12150. * @param {Sphere} sphere - The bounding sphere to test.
  12151. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  12152. */
  12153. intersectsSphere( sphere ) {
  12154. // Find the point on the AABB closest to the sphere center.
  12155. this.clampPoint( sphere.center, _vector$b );
  12156. // If that point is inside the sphere, the AABB and sphere intersect.
  12157. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  12158. }
  12159. /**
  12160. * Returns `true` if the given plane intersects with this bounding box.
  12161. *
  12162. * @param {Plane} plane - The plane to test.
  12163. * @return {boolean} Whether the given plane intersects with this bounding box.
  12164. */
  12165. intersectsPlane( plane ) {
  12166. // We compute the minimum and maximum dot product values. If those values
  12167. // are on the same side (back or front) of the plane, then there is no intersection.
  12168. let min, max;
  12169. if ( plane.normal.x > 0 ) {
  12170. min = plane.normal.x * this.min.x;
  12171. max = plane.normal.x * this.max.x;
  12172. } else {
  12173. min = plane.normal.x * this.max.x;
  12174. max = plane.normal.x * this.min.x;
  12175. }
  12176. if ( plane.normal.y > 0 ) {
  12177. min += plane.normal.y * this.min.y;
  12178. max += plane.normal.y * this.max.y;
  12179. } else {
  12180. min += plane.normal.y * this.max.y;
  12181. max += plane.normal.y * this.min.y;
  12182. }
  12183. if ( plane.normal.z > 0 ) {
  12184. min += plane.normal.z * this.min.z;
  12185. max += plane.normal.z * this.max.z;
  12186. } else {
  12187. min += plane.normal.z * this.max.z;
  12188. max += plane.normal.z * this.min.z;
  12189. }
  12190. return ( min <= - plane.constant && max >= - plane.constant );
  12191. }
  12192. /**
  12193. * Returns `true` if the given triangle intersects with this bounding box.
  12194. *
  12195. * @param {Triangle} triangle - The triangle to test.
  12196. * @return {boolean} Whether the given triangle intersects with this bounding box.
  12197. */
  12198. intersectsTriangle( triangle ) {
  12199. if ( this.isEmpty() ) {
  12200. return false;
  12201. }
  12202. // compute box center and extents
  12203. this.getCenter( _center );
  12204. _extents.subVectors( this.max, _center );
  12205. // translate triangle to aabb origin
  12206. _v0$1.subVectors( triangle.a, _center );
  12207. _v1$4.subVectors( triangle.b, _center );
  12208. _v2$3.subVectors( triangle.c, _center );
  12209. // compute edge vectors for triangle
  12210. _f0.subVectors( _v1$4, _v0$1 );
  12211. _f1.subVectors( _v2$3, _v1$4 );
  12212. _f2.subVectors( _v0$1, _v2$3 );
  12213. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  12214. // 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
  12215. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  12216. let axes = [
  12217. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  12218. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  12219. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  12220. ];
  12221. if ( ! satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ) ) {
  12222. return false;
  12223. }
  12224. // test 3 face normals from the aabb
  12225. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  12226. if ( ! satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ) ) {
  12227. return false;
  12228. }
  12229. // finally testing the face normal of the triangle
  12230. // use already existing triangle edge vectors here
  12231. _triangleNormal.crossVectors( _f0, _f1 );
  12232. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  12233. return satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents );
  12234. }
  12235. /**
  12236. * Clamps the given point within the bounds of this box.
  12237. *
  12238. * @param {Vector3} point - The point to clamp.
  12239. * @param {Vector3} target - The target vector that is used to store the method's result.
  12240. * @return {Vector3} The clamped point.
  12241. */
  12242. clampPoint( point, target ) {
  12243. return target.copy( point ).clamp( this.min, this.max );
  12244. }
  12245. /**
  12246. * Returns the euclidean distance from any edge of this box to the specified point. If
  12247. * the given point lies inside of this box, the distance will be `0`.
  12248. *
  12249. * @param {Vector3} point - The point to compute the distance to.
  12250. * @return {number} The euclidean distance.
  12251. */
  12252. distanceToPoint( point ) {
  12253. return this.clampPoint( point, _vector$b ).distanceTo( point );
  12254. }
  12255. /**
  12256. * Returns a bounding sphere that encloses this bounding box.
  12257. *
  12258. * @param {Sphere} target - The target sphere that is used to store the method's result.
  12259. * @return {Sphere} The bounding sphere that encloses this bounding box.
  12260. */
  12261. getBoundingSphere( target ) {
  12262. if ( this.isEmpty() ) {
  12263. target.makeEmpty();
  12264. } else {
  12265. this.getCenter( target.center );
  12266. target.radius = this.getSize( _vector$b ).length() * 0.5;
  12267. }
  12268. return target;
  12269. }
  12270. /**
  12271. * Computes the intersection of this bounding box and the given one, setting the upper
  12272. * bound of this box to the lesser of the two boxes' upper bounds and the
  12273. * lower bound of this box to the greater of the two boxes' lower bounds. If
  12274. * there's no overlap, makes this box empty.
  12275. *
  12276. * @param {Box3} box - The bounding box to intersect with.
  12277. * @return {Box3} A reference to this bounding box.
  12278. */
  12279. intersect( box ) {
  12280. this.min.max( box.min );
  12281. this.max.min( box.max );
  12282. // 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.
  12283. if ( this.isEmpty() ) this.makeEmpty();
  12284. return this;
  12285. }
  12286. /**
  12287. * Computes the union of this box and another and the given one, setting the upper
  12288. * bound of this box to the greater of the two boxes' upper bounds and the
  12289. * lower bound of this box to the lesser of the two boxes' lower bounds.
  12290. *
  12291. * @param {Box3} box - The bounding box that will be unioned with this instance.
  12292. * @return {Box3} A reference to this bounding box.
  12293. */
  12294. union( box ) {
  12295. this.min.min( box.min );
  12296. this.max.max( box.max );
  12297. return this;
  12298. }
  12299. /**
  12300. * Transforms this bounding box by the given 4x4 transformation matrix.
  12301. *
  12302. * @param {Matrix4} matrix - The transformation matrix.
  12303. * @return {Box3} A reference to this bounding box.
  12304. */
  12305. applyMatrix4( matrix ) {
  12306. // transform of empty box is an empty box.
  12307. if ( this.isEmpty() ) return this;
  12308. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  12309. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  12310. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  12311. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  12312. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  12313. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  12314. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  12315. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  12316. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  12317. this.setFromPoints( _points );
  12318. return this;
  12319. }
  12320. /**
  12321. * Adds the given offset to both the upper and lower bounds of this bounding box,
  12322. * effectively moving it in 3D space.
  12323. *
  12324. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  12325. * @return {Box3} A reference to this bounding box.
  12326. */
  12327. translate( offset ) {
  12328. this.min.add( offset );
  12329. this.max.add( offset );
  12330. return this;
  12331. }
  12332. /**
  12333. * Returns `true` if this bounding box is equal with the given one.
  12334. *
  12335. * @param {Box3} box - The box to test for equality.
  12336. * @return {boolean} Whether this bounding box is equal with the given one.
  12337. */
  12338. equals( box ) {
  12339. return box.min.equals( this.min ) && box.max.equals( this.max );
  12340. }
  12341. /**
  12342. * Returns a serialized structure of the bounding box.
  12343. *
  12344. * @return {Object} Serialized structure with fields representing the object state.
  12345. */
  12346. toJSON() {
  12347. return {
  12348. min: this.min.toArray(),
  12349. max: this.max.toArray()
  12350. };
  12351. }
  12352. /**
  12353. * Returns a serialized structure of the bounding box.
  12354. *
  12355. * @param {Object} json - The serialized json to set the box from.
  12356. * @return {Box3} A reference to this bounding box.
  12357. */
  12358. fromJSON( json ) {
  12359. this.min.fromArray( json.min );
  12360. this.max.fromArray( json.max );
  12361. return this;
  12362. }
  12363. }
  12364. const _points = [
  12365. /*@__PURE__*/ new Vector3(),
  12366. /*@__PURE__*/ new Vector3(),
  12367. /*@__PURE__*/ new Vector3(),
  12368. /*@__PURE__*/ new Vector3(),
  12369. /*@__PURE__*/ new Vector3(),
  12370. /*@__PURE__*/ new Vector3(),
  12371. /*@__PURE__*/ new Vector3(),
  12372. /*@__PURE__*/ new Vector3()
  12373. ];
  12374. const _vector$b = /*@__PURE__*/ new Vector3();
  12375. const _box$4 = /*@__PURE__*/ new Box3();
  12376. // triangle centered vertices
  12377. const _v0$1 = /*@__PURE__*/ new Vector3();
  12378. const _v1$4 = /*@__PURE__*/ new Vector3();
  12379. const _v2$3 = /*@__PURE__*/ new Vector3();
  12380. // triangle edge vectors
  12381. const _f0 = /*@__PURE__*/ new Vector3();
  12382. const _f1 = /*@__PURE__*/ new Vector3();
  12383. const _f2 = /*@__PURE__*/ new Vector3();
  12384. const _center = /*@__PURE__*/ new Vector3();
  12385. const _extents = /*@__PURE__*/ new Vector3();
  12386. const _triangleNormal = /*@__PURE__*/ new Vector3();
  12387. const _testAxis = /*@__PURE__*/ new Vector3();
  12388. function satForAxes( axes, v0, v1, v2, extents ) {
  12389. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  12390. _testAxis.fromArray( axes, i );
  12391. // project the aabb onto the separating axis
  12392. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  12393. // project all 3 vertices of the triangle onto the separating axis
  12394. const p0 = v0.dot( _testAxis );
  12395. const p1 = v1.dot( _testAxis );
  12396. const p2 = v2.dot( _testAxis );
  12397. // actual test, basically see if either of the most extreme of the triangle points intersects r
  12398. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  12399. // points of the projected triangle are outside the projected half-length of the aabb
  12400. // the axis is separating and we can exit
  12401. return false;
  12402. }
  12403. }
  12404. return true;
  12405. }
  12406. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  12407. const _tables = /*@__PURE__*/ _generateTables();
  12408. function _generateTables() {
  12409. // float32 to float16 helpers
  12410. const buffer = new ArrayBuffer( 4 );
  12411. const floatView = new Float32Array( buffer );
  12412. const uint32View = new Uint32Array( buffer );
  12413. const baseTable = new Uint32Array( 512 );
  12414. const shiftTable = new Uint32Array( 512 );
  12415. for ( let i = 0; i < 256; ++ i ) {
  12416. const e = i - 127;
  12417. // very small number (0, -0)
  12418. if ( e < -27 ) {
  12419. baseTable[ i ] = 0x0000;
  12420. baseTable[ i | 0x100 ] = 0x8000;
  12421. shiftTable[ i ] = 24;
  12422. shiftTable[ i | 0x100 ] = 24;
  12423. // small number (denorm)
  12424. } else if ( e < -14 ) {
  12425. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  12426. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  12427. shiftTable[ i ] = - e - 1;
  12428. shiftTable[ i | 0x100 ] = - e - 1;
  12429. // normal number
  12430. } else if ( e <= 15 ) {
  12431. baseTable[ i ] = ( e + 15 ) << 10;
  12432. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  12433. shiftTable[ i ] = 13;
  12434. shiftTable[ i | 0x100 ] = 13;
  12435. // large number (Infinity, -Infinity)
  12436. } else if ( e < 128 ) {
  12437. baseTable[ i ] = 0x7c00;
  12438. baseTable[ i | 0x100 ] = 0xfc00;
  12439. shiftTable[ i ] = 24;
  12440. shiftTable[ i | 0x100 ] = 24;
  12441. // stay (NaN, Infinity, -Infinity)
  12442. } else {
  12443. baseTable[ i ] = 0x7c00;
  12444. baseTable[ i | 0x100 ] = 0xfc00;
  12445. shiftTable[ i ] = 13;
  12446. shiftTable[ i | 0x100 ] = 13;
  12447. }
  12448. }
  12449. // float16 to float32 helpers
  12450. const mantissaTable = new Uint32Array( 2048 );
  12451. const exponentTable = new Uint32Array( 64 );
  12452. const offsetTable = new Uint32Array( 64 );
  12453. for ( let i = 1; i < 1024; ++ i ) {
  12454. let m = i << 13; // zero pad mantissa bits
  12455. let e = 0; // zero exponent
  12456. // normalized
  12457. while ( ( m & 0x00800000 ) === 0 ) {
  12458. m <<= 1;
  12459. e -= 0x00800000; // decrement exponent
  12460. }
  12461. m &= -8388609; // clear leading 1 bit
  12462. e += 0x38800000; // adjust bias
  12463. mantissaTable[ i ] = m | e;
  12464. }
  12465. for ( let i = 1024; i < 2048; ++ i ) {
  12466. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  12467. }
  12468. for ( let i = 1; i < 31; ++ i ) {
  12469. exponentTable[ i ] = i << 23;
  12470. }
  12471. exponentTable[ 31 ] = 0x47800000;
  12472. exponentTable[ 32 ] = 0x80000000;
  12473. for ( let i = 33; i < 63; ++ i ) {
  12474. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  12475. }
  12476. exponentTable[ 63 ] = 0xc7800000;
  12477. for ( let i = 1; i < 64; ++ i ) {
  12478. if ( i !== 32 ) {
  12479. offsetTable[ i ] = 1024;
  12480. }
  12481. }
  12482. return {
  12483. floatView: floatView,
  12484. uint32View: uint32View,
  12485. baseTable: baseTable,
  12486. shiftTable: shiftTable,
  12487. mantissaTable: mantissaTable,
  12488. exponentTable: exponentTable,
  12489. offsetTable: offsetTable
  12490. };
  12491. }
  12492. /**
  12493. * Returns a half precision floating point value (FP16) from the given single
  12494. * precision floating point value (FP32).
  12495. *
  12496. * @param {number} val - A single precision floating point value.
  12497. * @return {number} The FP16 value.
  12498. */
  12499. function toHalfFloat( val ) {
  12500. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  12501. val = clamp( val, -65504, 65504 );
  12502. _tables.floatView[ 0 ] = val;
  12503. const f = _tables.uint32View[ 0 ];
  12504. const e = ( f >> 23 ) & 0x1ff;
  12505. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  12506. }
  12507. /**
  12508. * Returns a single precision floating point value (FP32) from the given half
  12509. * precision floating point value (FP16).
  12510. *
  12511. * @param {number} val - A half precision floating point value.
  12512. * @return {number} The FP32 value.
  12513. */
  12514. function fromHalfFloat( val ) {
  12515. const m = val >> 10;
  12516. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  12517. return _tables.floatView[ 0 ];
  12518. }
  12519. /**
  12520. * A class containing utility functions for data.
  12521. *
  12522. * @hideconstructor
  12523. */
  12524. class DataUtils {
  12525. /**
  12526. * Returns a half precision floating point value (FP16) from the given single
  12527. * precision floating point value (FP32).
  12528. *
  12529. * @param {number} val - A single precision floating point value.
  12530. * @return {number} The FP16 value.
  12531. */
  12532. static toHalfFloat( val ) {
  12533. return toHalfFloat( val );
  12534. }
  12535. /**
  12536. * Returns a single precision floating point value (FP32) from the given half
  12537. * precision floating point value (FP16).
  12538. *
  12539. * @param {number} val - A half precision floating point value.
  12540. * @return {number} The FP32 value.
  12541. */
  12542. static fromHalfFloat( val ) {
  12543. return fromHalfFloat( val );
  12544. }
  12545. }
  12546. const _vector$a = /*@__PURE__*/ new Vector3();
  12547. const _vector2$1 = /*@__PURE__*/ new Vector2();
  12548. let _id$2 = 0;
  12549. /**
  12550. * This class stores data for an attribute (such as vertex positions, face
  12551. * indices, normals, colors, UVs, and any custom attributes ) associated with
  12552. * a geometry, which allows for more efficient passing of data to the GPU.
  12553. *
  12554. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  12555. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  12556. */
  12557. class BufferAttribute {
  12558. /**
  12559. * Constructs a new buffer attribute.
  12560. *
  12561. * @param {TypedArray} array - The array holding the attribute data.
  12562. * @param {number} itemSize - The item size.
  12563. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  12564. */
  12565. constructor( array, itemSize, normalized = false ) {
  12566. if ( Array.isArray( array ) ) {
  12567. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  12568. }
  12569. /**
  12570. * This flag can be used for type testing.
  12571. *
  12572. * @type {boolean}
  12573. * @readonly
  12574. * @default true
  12575. */
  12576. this.isBufferAttribute = true;
  12577. /**
  12578. * The ID of the buffer attribute.
  12579. *
  12580. * @name BufferAttribute#id
  12581. * @type {number}
  12582. * @readonly
  12583. */
  12584. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  12585. /**
  12586. * The name of the buffer attribute.
  12587. *
  12588. * @type {string}
  12589. */
  12590. this.name = '';
  12591. /**
  12592. * The array holding the attribute data. It should have `itemSize * numVertices`
  12593. * elements, where `numVertices` is the number of vertices in the associated geometry.
  12594. *
  12595. * @type {TypedArray}
  12596. */
  12597. this.array = array;
  12598. /**
  12599. * The number of values of the array that should be associated with a particular vertex.
  12600. * For instance, if this attribute is storing a 3-component vector (such as a position,
  12601. * normal, or color), then the value should be `3`.
  12602. *
  12603. * @type {number}
  12604. */
  12605. this.itemSize = itemSize;
  12606. /**
  12607. * Represents the number of items this buffer attribute stores. It is internally computed
  12608. * by dividing the `array` length by the `itemSize`.
  12609. *
  12610. * @type {number}
  12611. * @readonly
  12612. */
  12613. this.count = array !== undefined ? array.length / itemSize : 0;
  12614. /**
  12615. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  12616. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  12617. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  12618. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  12619. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  12620. *
  12621. * @type {boolean}
  12622. */
  12623. this.normalized = normalized;
  12624. /**
  12625. * Defines the intended usage pattern of the data store for optimization purposes.
  12626. *
  12627. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  12628. * instantiate a new one and set the desired usage before the next render.
  12629. *
  12630. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  12631. * @default StaticDrawUsage
  12632. */
  12633. this.usage = StaticDrawUsage;
  12634. /**
  12635. * This can be used to only update some components of stored vectors (for example, just the
  12636. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  12637. *
  12638. * @type {Array<Object>}
  12639. */
  12640. this.updateRanges = [];
  12641. /**
  12642. * Configures the bound GPU type for use in shaders.
  12643. *
  12644. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  12645. * For lower precision float types, use `Float16BufferAttribute`.
  12646. *
  12647. * @type {(FloatType|IntType)}
  12648. * @default FloatType
  12649. */
  12650. this.gpuType = FloatType;
  12651. /**
  12652. * A version number, incremented every time the `needsUpdate` is set to `true`.
  12653. *
  12654. * @type {number}
  12655. */
  12656. this.version = 0;
  12657. }
  12658. /**
  12659. * A callback function that is executed after the renderer has transferred the attribute
  12660. * array data to the GPU.
  12661. */
  12662. onUploadCallback() {}
  12663. /**
  12664. * Flag to indicate that this attribute has changed and should be re-sent to
  12665. * the GPU. Set this to `true` when you modify the value of the array.
  12666. *
  12667. * @type {number}
  12668. * @default false
  12669. * @param {boolean} value
  12670. */
  12671. set needsUpdate( value ) {
  12672. if ( value === true ) this.version ++;
  12673. }
  12674. /**
  12675. * Sets the usage of this buffer attribute.
  12676. *
  12677. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  12678. * @return {BufferAttribute} A reference to this buffer attribute.
  12679. */
  12680. setUsage( value ) {
  12681. this.usage = value;
  12682. return this;
  12683. }
  12684. /**
  12685. * Adds a range of data in the data array to be updated on the GPU.
  12686. *
  12687. * @param {number} start - Position at which to start update.
  12688. * @param {number} count - The number of components to update.
  12689. */
  12690. addUpdateRange( start, count ) {
  12691. this.updateRanges.push( { start, count } );
  12692. }
  12693. /**
  12694. * Clears the update ranges.
  12695. */
  12696. clearUpdateRanges() {
  12697. this.updateRanges.length = 0;
  12698. }
  12699. /**
  12700. * Copies the values of the given buffer attribute to this instance.
  12701. *
  12702. * @param {BufferAttribute} source - The buffer attribute to copy.
  12703. * @return {BufferAttribute} A reference to this instance.
  12704. */
  12705. copy( source ) {
  12706. this.name = source.name;
  12707. this.array = new source.array.constructor( source.array );
  12708. this.itemSize = source.itemSize;
  12709. this.count = source.count;
  12710. this.normalized = source.normalized;
  12711. this.usage = source.usage;
  12712. this.gpuType = source.gpuType;
  12713. return this;
  12714. }
  12715. /**
  12716. * Copies a vector from the given buffer attribute to this one. The start
  12717. * and destination position in the attribute buffers are represented by the
  12718. * given indices.
  12719. *
  12720. * @param {number} index1 - The destination index into this buffer attribute.
  12721. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  12722. * @param {number} index2 - The source index into the given buffer attribute.
  12723. * @return {BufferAttribute} A reference to this instance.
  12724. */
  12725. copyAt( index1, attribute, index2 ) {
  12726. index1 *= this.itemSize;
  12727. index2 *= attribute.itemSize;
  12728. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  12729. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  12730. }
  12731. return this;
  12732. }
  12733. /**
  12734. * Copies the given array data into this buffer attribute.
  12735. *
  12736. * @param {(TypedArray|Array)} array - The array to copy.
  12737. * @return {BufferAttribute} A reference to this instance.
  12738. */
  12739. copyArray( array ) {
  12740. this.array.set( array );
  12741. return this;
  12742. }
  12743. /**
  12744. * Applies the given 3x3 matrix to the given attribute. Works with
  12745. * item size `2` and `3`.
  12746. *
  12747. * @param {Matrix3} m - The matrix to apply.
  12748. * @return {BufferAttribute} A reference to this instance.
  12749. */
  12750. applyMatrix3( m ) {
  12751. if ( this.itemSize === 2 ) {
  12752. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12753. _vector2$1.fromBufferAttribute( this, i );
  12754. _vector2$1.applyMatrix3( m );
  12755. this.setXY( i, _vector2$1.x, _vector2$1.y );
  12756. }
  12757. } else if ( this.itemSize === 3 ) {
  12758. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12759. _vector$a.fromBufferAttribute( this, i );
  12760. _vector$a.applyMatrix3( m );
  12761. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12762. }
  12763. }
  12764. return this;
  12765. }
  12766. /**
  12767. * Applies the given 4x4 matrix to the given attribute. Only works with
  12768. * item size `3`.
  12769. *
  12770. * @param {Matrix4} m - The matrix to apply.
  12771. * @return {BufferAttribute} A reference to this instance.
  12772. */
  12773. applyMatrix4( m ) {
  12774. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12775. _vector$a.fromBufferAttribute( this, i );
  12776. _vector$a.applyMatrix4( m );
  12777. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12778. }
  12779. return this;
  12780. }
  12781. /**
  12782. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  12783. * item size `3`.
  12784. *
  12785. * @param {Matrix3} m - The normal matrix to apply.
  12786. * @return {BufferAttribute} A reference to this instance.
  12787. */
  12788. applyNormalMatrix( m ) {
  12789. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12790. _vector$a.fromBufferAttribute( this, i );
  12791. _vector$a.applyNormalMatrix( m );
  12792. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12793. }
  12794. return this;
  12795. }
  12796. /**
  12797. * Applies the given 4x4 matrix to the given attribute. Only works with
  12798. * item size `3` and with direction vectors.
  12799. *
  12800. * @param {Matrix4} m - The matrix to apply.
  12801. * @return {BufferAttribute} A reference to this instance.
  12802. */
  12803. transformDirection( m ) {
  12804. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12805. _vector$a.fromBufferAttribute( this, i );
  12806. _vector$a.transformDirection( m );
  12807. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12808. }
  12809. return this;
  12810. }
  12811. /**
  12812. * Sets the given array data in the buffer attribute.
  12813. *
  12814. * @param {(TypedArray|Array)} value - The array data to set.
  12815. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  12816. * @return {BufferAttribute} A reference to this instance.
  12817. */
  12818. set( value, offset = 0 ) {
  12819. // Matching BufferAttribute constructor, do not normalize the array.
  12820. this.array.set( value, offset );
  12821. return this;
  12822. }
  12823. /**
  12824. * Returns the given component of the vector at the given index.
  12825. *
  12826. * @param {number} index - The index into the buffer attribute.
  12827. * @param {number} component - The component index.
  12828. * @return {number} The returned value.
  12829. */
  12830. getComponent( index, component ) {
  12831. let value = this.array[ index * this.itemSize + component ];
  12832. if ( this.normalized ) value = denormalize( value, this.array );
  12833. return value;
  12834. }
  12835. /**
  12836. * Sets the given value to the given component of the vector at the given index.
  12837. *
  12838. * @param {number} index - The index into the buffer attribute.
  12839. * @param {number} component - The component index.
  12840. * @param {number} value - The value to set.
  12841. * @return {BufferAttribute} A reference to this instance.
  12842. */
  12843. setComponent( index, component, value ) {
  12844. if ( this.normalized ) value = normalize( value, this.array );
  12845. this.array[ index * this.itemSize + component ] = value;
  12846. return this;
  12847. }
  12848. /**
  12849. * Returns the x component of the vector at the given index.
  12850. *
  12851. * @param {number} index - The index into the buffer attribute.
  12852. * @return {number} The x component.
  12853. */
  12854. getX( index ) {
  12855. let x = this.array[ index * this.itemSize ];
  12856. if ( this.normalized ) x = denormalize( x, this.array );
  12857. return x;
  12858. }
  12859. /**
  12860. * Sets the x component of the vector at the given index.
  12861. *
  12862. * @param {number} index - The index into the buffer attribute.
  12863. * @param {number} x - The value to set.
  12864. * @return {BufferAttribute} A reference to this instance.
  12865. */
  12866. setX( index, x ) {
  12867. if ( this.normalized ) x = normalize( x, this.array );
  12868. this.array[ index * this.itemSize ] = x;
  12869. return this;
  12870. }
  12871. /**
  12872. * Returns the y component of the vector at the given index.
  12873. *
  12874. * @param {number} index - The index into the buffer attribute.
  12875. * @return {number} The y component.
  12876. */
  12877. getY( index ) {
  12878. let y = this.array[ index * this.itemSize + 1 ];
  12879. if ( this.normalized ) y = denormalize( y, this.array );
  12880. return y;
  12881. }
  12882. /**
  12883. * Sets the y component of the vector at the given index.
  12884. *
  12885. * @param {number} index - The index into the buffer attribute.
  12886. * @param {number} y - The value to set.
  12887. * @return {BufferAttribute} A reference to this instance.
  12888. */
  12889. setY( index, y ) {
  12890. if ( this.normalized ) y = normalize( y, this.array );
  12891. this.array[ index * this.itemSize + 1 ] = y;
  12892. return this;
  12893. }
  12894. /**
  12895. * Returns the z component of the vector at the given index.
  12896. *
  12897. * @param {number} index - The index into the buffer attribute.
  12898. * @return {number} The z component.
  12899. */
  12900. getZ( index ) {
  12901. let z = this.array[ index * this.itemSize + 2 ];
  12902. if ( this.normalized ) z = denormalize( z, this.array );
  12903. return z;
  12904. }
  12905. /**
  12906. * Sets the z component of the vector at the given index.
  12907. *
  12908. * @param {number} index - The index into the buffer attribute.
  12909. * @param {number} z - The value to set.
  12910. * @return {BufferAttribute} A reference to this instance.
  12911. */
  12912. setZ( index, z ) {
  12913. if ( this.normalized ) z = normalize( z, this.array );
  12914. this.array[ index * this.itemSize + 2 ] = z;
  12915. return this;
  12916. }
  12917. /**
  12918. * Returns the w component of the vector at the given index.
  12919. *
  12920. * @param {number} index - The index into the buffer attribute.
  12921. * @return {number} The w component.
  12922. */
  12923. getW( index ) {
  12924. let w = this.array[ index * this.itemSize + 3 ];
  12925. if ( this.normalized ) w = denormalize( w, this.array );
  12926. return w;
  12927. }
  12928. /**
  12929. * Sets the w component of the vector at the given index.
  12930. *
  12931. * @param {number} index - The index into the buffer attribute.
  12932. * @param {number} w - The value to set.
  12933. * @return {BufferAttribute} A reference to this instance.
  12934. */
  12935. setW( index, w ) {
  12936. if ( this.normalized ) w = normalize( w, this.array );
  12937. this.array[ index * this.itemSize + 3 ] = w;
  12938. return this;
  12939. }
  12940. /**
  12941. * Sets the x and y component of the vector at the given index.
  12942. *
  12943. * @param {number} index - The index into the buffer attribute.
  12944. * @param {number} x - The value for the x component to set.
  12945. * @param {number} y - The value for the y component to set.
  12946. * @return {BufferAttribute} A reference to this instance.
  12947. */
  12948. setXY( index, x, y ) {
  12949. index *= this.itemSize;
  12950. if ( this.normalized ) {
  12951. x = normalize( x, this.array );
  12952. y = normalize( y, this.array );
  12953. }
  12954. this.array[ index + 0 ] = x;
  12955. this.array[ index + 1 ] = y;
  12956. return this;
  12957. }
  12958. /**
  12959. * Sets the x, y and z component of the vector at the given index.
  12960. *
  12961. * @param {number} index - The index into the buffer attribute.
  12962. * @param {number} x - The value for the x component to set.
  12963. * @param {number} y - The value for the y component to set.
  12964. * @param {number} z - The value for the z component to set.
  12965. * @return {BufferAttribute} A reference to this instance.
  12966. */
  12967. setXYZ( index, x, y, z ) {
  12968. index *= this.itemSize;
  12969. if ( this.normalized ) {
  12970. x = normalize( x, this.array );
  12971. y = normalize( y, this.array );
  12972. z = normalize( z, this.array );
  12973. }
  12974. this.array[ index + 0 ] = x;
  12975. this.array[ index + 1 ] = y;
  12976. this.array[ index + 2 ] = z;
  12977. return this;
  12978. }
  12979. /**
  12980. * Sets the x, y, z and w component of the vector at the given index.
  12981. *
  12982. * @param {number} index - The index into the buffer attribute.
  12983. * @param {number} x - The value for the x component to set.
  12984. * @param {number} y - The value for the y component to set.
  12985. * @param {number} z - The value for the z component to set.
  12986. * @param {number} w - The value for the w component to set.
  12987. * @return {BufferAttribute} A reference to this instance.
  12988. */
  12989. setXYZW( index, x, y, z, w ) {
  12990. index *= this.itemSize;
  12991. if ( this.normalized ) {
  12992. x = normalize( x, this.array );
  12993. y = normalize( y, this.array );
  12994. z = normalize( z, this.array );
  12995. w = normalize( w, this.array );
  12996. }
  12997. this.array[ index + 0 ] = x;
  12998. this.array[ index + 1 ] = y;
  12999. this.array[ index + 2 ] = z;
  13000. this.array[ index + 3 ] = w;
  13001. return this;
  13002. }
  13003. /**
  13004. * Sets the given callback function that is executed after the Renderer has transferred
  13005. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13006. * the upload when attribute data are not needed anymore on the CPU side.
  13007. *
  13008. * @param {Function} callback - The `onUpload()` callback.
  13009. * @return {BufferAttribute} A reference to this instance.
  13010. */
  13011. onUpload( callback ) {
  13012. this.onUploadCallback = callback;
  13013. return this;
  13014. }
  13015. /**
  13016. * Returns a new buffer attribute with copied values from this instance.
  13017. *
  13018. * @return {BufferAttribute} A clone of this instance.
  13019. */
  13020. clone() {
  13021. return new this.constructor( this.array, this.itemSize ).copy( this );
  13022. }
  13023. /**
  13024. * Serializes the buffer attribute into JSON.
  13025. *
  13026. * @return {Object} A JSON object representing the serialized buffer attribute.
  13027. */
  13028. toJSON() {
  13029. const data = {
  13030. itemSize: this.itemSize,
  13031. type: this.array.constructor.name,
  13032. array: Array.from( this.array ),
  13033. normalized: this.normalized
  13034. };
  13035. if ( this.name !== '' ) data.name = this.name;
  13036. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13037. return data;
  13038. }
  13039. }
  13040. /**
  13041. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13042. * a plain `Array` instance.
  13043. *
  13044. * @augments BufferAttribute
  13045. */
  13046. class Int8BufferAttribute extends BufferAttribute {
  13047. /**
  13048. * Constructs a new buffer attribute.
  13049. *
  13050. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13051. * @param {number} itemSize - The item size.
  13052. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13053. */
  13054. constructor( array, itemSize, normalized ) {
  13055. super( new Int8Array( array ), itemSize, normalized );
  13056. }
  13057. }
  13058. /**
  13059. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13060. * a plain `Array` instance.
  13061. *
  13062. * @augments BufferAttribute
  13063. */
  13064. class Uint8BufferAttribute extends BufferAttribute {
  13065. /**
  13066. * Constructs a new buffer attribute.
  13067. *
  13068. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13069. * @param {number} itemSize - The item size.
  13070. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13071. */
  13072. constructor( array, itemSize, normalized ) {
  13073. super( new Uint8Array( array ), itemSize, normalized );
  13074. }
  13075. }
  13076. /**
  13077. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13078. * a plain `Array` instance.
  13079. *
  13080. * @augments BufferAttribute
  13081. */
  13082. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13083. /**
  13084. * Constructs a new buffer attribute.
  13085. *
  13086. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13087. * @param {number} itemSize - The item size.
  13088. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13089. */
  13090. constructor( array, itemSize, normalized ) {
  13091. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13092. }
  13093. }
  13094. /**
  13095. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13096. * a plain `Array` instance.
  13097. *
  13098. * @augments BufferAttribute
  13099. */
  13100. class Int16BufferAttribute extends BufferAttribute {
  13101. /**
  13102. * Constructs a new buffer attribute.
  13103. *
  13104. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13105. * @param {number} itemSize - The item size.
  13106. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13107. */
  13108. constructor( array, itemSize, normalized ) {
  13109. super( new Int16Array( array ), itemSize, normalized );
  13110. }
  13111. }
  13112. /**
  13113. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13114. * a plain `Array` instance.
  13115. *
  13116. * @augments BufferAttribute
  13117. */
  13118. class Uint16BufferAttribute extends BufferAttribute {
  13119. /**
  13120. * Constructs a new buffer attribute.
  13121. *
  13122. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13123. * @param {number} itemSize - The item size.
  13124. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13125. */
  13126. constructor( array, itemSize, normalized ) {
  13127. super( new Uint16Array( array ), itemSize, normalized );
  13128. }
  13129. }
  13130. /**
  13131. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13132. * a plain `Array` instance.
  13133. *
  13134. * @augments BufferAttribute
  13135. */
  13136. class Int32BufferAttribute extends BufferAttribute {
  13137. /**
  13138. * Constructs a new buffer attribute.
  13139. *
  13140. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13141. * @param {number} itemSize - The item size.
  13142. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13143. */
  13144. constructor( array, itemSize, normalized ) {
  13145. super( new Int32Array( array ), itemSize, normalized );
  13146. }
  13147. }
  13148. /**
  13149. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13150. * a plain `Array` instance.
  13151. *
  13152. * @augments BufferAttribute
  13153. */
  13154. class Uint32BufferAttribute extends BufferAttribute {
  13155. /**
  13156. * Constructs a new buffer attribute.
  13157. *
  13158. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13159. * @param {number} itemSize - The item size.
  13160. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13161. */
  13162. constructor( array, itemSize, normalized ) {
  13163. super( new Uint32Array( array ), itemSize, normalized );
  13164. }
  13165. }
  13166. /**
  13167. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13168. * a plain `Array` instance.
  13169. *
  13170. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  13171. * browser support is still problematic.
  13172. *
  13173. * @augments BufferAttribute
  13174. */
  13175. class Float16BufferAttribute extends BufferAttribute {
  13176. /**
  13177. * Constructs a new buffer attribute.
  13178. *
  13179. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13180. * @param {number} itemSize - The item size.
  13181. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13182. */
  13183. constructor( array, itemSize, normalized ) {
  13184. super( new Uint16Array( array ), itemSize, normalized );
  13185. this.isFloat16BufferAttribute = true;
  13186. }
  13187. getX( index ) {
  13188. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  13189. if ( this.normalized ) x = denormalize( x, this.array );
  13190. return x;
  13191. }
  13192. setX( index, x ) {
  13193. if ( this.normalized ) x = normalize( x, this.array );
  13194. this.array[ index * this.itemSize ] = toHalfFloat( x );
  13195. return this;
  13196. }
  13197. getY( index ) {
  13198. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  13199. if ( this.normalized ) y = denormalize( y, this.array );
  13200. return y;
  13201. }
  13202. setY( index, y ) {
  13203. if ( this.normalized ) y = normalize( y, this.array );
  13204. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  13205. return this;
  13206. }
  13207. getZ( index ) {
  13208. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  13209. if ( this.normalized ) z = denormalize( z, this.array );
  13210. return z;
  13211. }
  13212. setZ( index, z ) {
  13213. if ( this.normalized ) z = normalize( z, this.array );
  13214. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  13215. return this;
  13216. }
  13217. getW( index ) {
  13218. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  13219. if ( this.normalized ) w = denormalize( w, this.array );
  13220. return w;
  13221. }
  13222. setW( index, w ) {
  13223. if ( this.normalized ) w = normalize( w, this.array );
  13224. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  13225. return this;
  13226. }
  13227. setXY( index, x, y ) {
  13228. index *= this.itemSize;
  13229. if ( this.normalized ) {
  13230. x = normalize( x, this.array );
  13231. y = normalize( y, this.array );
  13232. }
  13233. this.array[ index + 0 ] = toHalfFloat( x );
  13234. this.array[ index + 1 ] = toHalfFloat( y );
  13235. return this;
  13236. }
  13237. setXYZ( index, x, y, z ) {
  13238. index *= this.itemSize;
  13239. if ( this.normalized ) {
  13240. x = normalize( x, this.array );
  13241. y = normalize( y, this.array );
  13242. z = normalize( z, this.array );
  13243. }
  13244. this.array[ index + 0 ] = toHalfFloat( x );
  13245. this.array[ index + 1 ] = toHalfFloat( y );
  13246. this.array[ index + 2 ] = toHalfFloat( z );
  13247. return this;
  13248. }
  13249. setXYZW( index, x, y, z, w ) {
  13250. index *= this.itemSize;
  13251. if ( this.normalized ) {
  13252. x = normalize( x, this.array );
  13253. y = normalize( y, this.array );
  13254. z = normalize( z, this.array );
  13255. w = normalize( w, this.array );
  13256. }
  13257. this.array[ index + 0 ] = toHalfFloat( x );
  13258. this.array[ index + 1 ] = toHalfFloat( y );
  13259. this.array[ index + 2 ] = toHalfFloat( z );
  13260. this.array[ index + 3 ] = toHalfFloat( w );
  13261. return this;
  13262. }
  13263. }
  13264. /**
  13265. * Convenient class that can be used when creating a `Float32` buffer attribute with
  13266. * a plain `Array` instance.
  13267. *
  13268. * @augments BufferAttribute
  13269. */
  13270. class Float32BufferAttribute extends BufferAttribute {
  13271. /**
  13272. * Constructs a new buffer attribute.
  13273. *
  13274. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  13275. * @param {number} itemSize - The item size.
  13276. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13277. */
  13278. constructor( array, itemSize, normalized ) {
  13279. super( new Float32Array( array ), itemSize, normalized );
  13280. }
  13281. }
  13282. const _box$3 = /*@__PURE__*/ new Box3();
  13283. const _v1$3 = /*@__PURE__*/ new Vector3();
  13284. const _v2$2 = /*@__PURE__*/ new Vector3();
  13285. /**
  13286. * An analytical 3D sphere defined by a center and radius. This class is mainly
  13287. * used as a Bounding Sphere for 3D objects.
  13288. */
  13289. class Sphere {
  13290. /**
  13291. * Constructs a new sphere.
  13292. *
  13293. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  13294. * @param {number} [radius=-1] - The radius of the sphere.
  13295. */
  13296. constructor( center = new Vector3(), radius = -1 ) {
  13297. /**
  13298. * This flag can be used for type testing.
  13299. *
  13300. * @type {boolean}
  13301. * @readonly
  13302. * @default true
  13303. */
  13304. this.isSphere = true;
  13305. /**
  13306. * The center of the sphere
  13307. *
  13308. * @type {Vector3}
  13309. */
  13310. this.center = center;
  13311. /**
  13312. * The radius of the sphere.
  13313. *
  13314. * @type {number}
  13315. */
  13316. this.radius = radius;
  13317. }
  13318. /**
  13319. * Sets the sphere's components by copying the given values.
  13320. *
  13321. * @param {Vector3} center - The center.
  13322. * @param {number} radius - The radius.
  13323. * @return {Sphere} A reference to this sphere.
  13324. */
  13325. set( center, radius ) {
  13326. this.center.copy( center );
  13327. this.radius = radius;
  13328. return this;
  13329. }
  13330. /**
  13331. * Computes the minimum bounding sphere for list of points.
  13332. * If the optional center point is given, it is used as the sphere's
  13333. * center. Otherwise, the center of the axis-aligned bounding box
  13334. * encompassing the points is calculated.
  13335. *
  13336. * @param {Array<Vector3>} points - A list of points in 3D space.
  13337. * @param {Vector3} [optionalCenter] - The center of the sphere.
  13338. * @return {Sphere} A reference to this sphere.
  13339. */
  13340. setFromPoints( points, optionalCenter ) {
  13341. const center = this.center;
  13342. if ( optionalCenter !== undefined ) {
  13343. center.copy( optionalCenter );
  13344. } else {
  13345. _box$3.setFromPoints( points ).getCenter( center );
  13346. }
  13347. let maxRadiusSq = 0;
  13348. for ( let i = 0, il = points.length; i < il; i ++ ) {
  13349. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  13350. }
  13351. this.radius = Math.sqrt( maxRadiusSq );
  13352. return this;
  13353. }
  13354. /**
  13355. * Copies the values of the given sphere to this instance.
  13356. *
  13357. * @param {Sphere} sphere - The sphere to copy.
  13358. * @return {Sphere} A reference to this sphere.
  13359. */
  13360. copy( sphere ) {
  13361. this.center.copy( sphere.center );
  13362. this.radius = sphere.radius;
  13363. return this;
  13364. }
  13365. /**
  13366. * Returns `true` if the sphere is empty (the radius set to a negative number).
  13367. *
  13368. * Spheres with a radius of `0` contain only their center point and are not
  13369. * considered to be empty.
  13370. *
  13371. * @return {boolean} Whether this sphere is empty or not.
  13372. */
  13373. isEmpty() {
  13374. return ( this.radius < 0 );
  13375. }
  13376. /**
  13377. * Makes this sphere empty which means in encloses a zero space in 3D.
  13378. *
  13379. * @return {Sphere} A reference to this sphere.
  13380. */
  13381. makeEmpty() {
  13382. this.center.set( 0, 0, 0 );
  13383. this.radius = -1;
  13384. return this;
  13385. }
  13386. /**
  13387. * Returns `true` if this sphere contains the given point inclusive of
  13388. * the surface of the sphere.
  13389. *
  13390. * @param {Vector3} point - The point to check.
  13391. * @return {boolean} Whether this sphere contains the given point or not.
  13392. */
  13393. containsPoint( point ) {
  13394. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  13395. }
  13396. /**
  13397. * Returns the closest distance from the boundary of the sphere to the
  13398. * given point. If the sphere contains the point, the distance will
  13399. * be negative.
  13400. *
  13401. * @param {Vector3} point - The point to compute the distance to.
  13402. * @return {number} The distance to the point.
  13403. */
  13404. distanceToPoint( point ) {
  13405. return ( point.distanceTo( this.center ) - this.radius );
  13406. }
  13407. /**
  13408. * Returns `true` if this sphere intersects with the given one.
  13409. *
  13410. * @param {Sphere} sphere - The sphere to test.
  13411. * @return {boolean} Whether this sphere intersects with the given one or not.
  13412. */
  13413. intersectsSphere( sphere ) {
  13414. const radiusSum = this.radius + sphere.radius;
  13415. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  13416. }
  13417. /**
  13418. * Returns `true` if this sphere intersects with the given box.
  13419. *
  13420. * @param {Box3} box - The box to test.
  13421. * @return {boolean} Whether this sphere intersects with the given box or not.
  13422. */
  13423. intersectsBox( box ) {
  13424. return box.intersectsSphere( this );
  13425. }
  13426. /**
  13427. * Returns `true` if this sphere intersects with the given plane.
  13428. *
  13429. * @param {Plane} plane - The plane to test.
  13430. * @return {boolean} Whether this sphere intersects with the given plane or not.
  13431. */
  13432. intersectsPlane( plane ) {
  13433. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  13434. }
  13435. /**
  13436. * Clamps a point within the sphere. If the point is outside the sphere, it
  13437. * will clamp it to the closest point on the edge of the sphere. Points
  13438. * already inside the sphere will not be affected.
  13439. *
  13440. * @param {Vector3} point - The plane to clamp.
  13441. * @param {Vector3} target - The target vector that is used to store the method's result.
  13442. * @return {Vector3} The clamped point.
  13443. */
  13444. clampPoint( point, target ) {
  13445. const deltaLengthSq = this.center.distanceToSquared( point );
  13446. target.copy( point );
  13447. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  13448. target.sub( this.center ).normalize();
  13449. target.multiplyScalar( this.radius ).add( this.center );
  13450. }
  13451. return target;
  13452. }
  13453. /**
  13454. * Returns a bounding box that encloses this sphere.
  13455. *
  13456. * @param {Box3} target - The target box that is used to store the method's result.
  13457. * @return {Box3} The bounding box that encloses this sphere.
  13458. */
  13459. getBoundingBox( target ) {
  13460. if ( this.isEmpty() ) {
  13461. // Empty sphere produces empty bounding box
  13462. target.makeEmpty();
  13463. return target;
  13464. }
  13465. target.set( this.center, this.center );
  13466. target.expandByScalar( this.radius );
  13467. return target;
  13468. }
  13469. /**
  13470. * Transforms this sphere with the given 4x4 transformation matrix.
  13471. *
  13472. * @param {Matrix4} matrix - The transformation matrix.
  13473. * @return {Sphere} A reference to this sphere.
  13474. */
  13475. applyMatrix4( matrix ) {
  13476. this.center.applyMatrix4( matrix );
  13477. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  13478. return this;
  13479. }
  13480. /**
  13481. * Translates the sphere's center by the given offset.
  13482. *
  13483. * @param {Vector3} offset - The offset.
  13484. * @return {Sphere} A reference to this sphere.
  13485. */
  13486. translate( offset ) {
  13487. this.center.add( offset );
  13488. return this;
  13489. }
  13490. /**
  13491. * Expands the boundaries of this sphere to include the given point.
  13492. *
  13493. * @param {Vector3} point - The point to include.
  13494. * @return {Sphere} A reference to this sphere.
  13495. */
  13496. expandByPoint( point ) {
  13497. if ( this.isEmpty() ) {
  13498. this.center.copy( point );
  13499. this.radius = 0;
  13500. return this;
  13501. }
  13502. _v1$3.subVectors( point, this.center );
  13503. const lengthSq = _v1$3.lengthSq();
  13504. if ( lengthSq > ( this.radius * this.radius ) ) {
  13505. // calculate the minimal sphere
  13506. const length = Math.sqrt( lengthSq );
  13507. const delta = ( length - this.radius ) * 0.5;
  13508. this.center.addScaledVector( _v1$3, delta / length );
  13509. this.radius += delta;
  13510. }
  13511. return this;
  13512. }
  13513. /**
  13514. * Expands this sphere to enclose both the original sphere and the given sphere.
  13515. *
  13516. * @param {Sphere} sphere - The sphere to include.
  13517. * @return {Sphere} A reference to this sphere.
  13518. */
  13519. union( sphere ) {
  13520. if ( sphere.isEmpty() ) {
  13521. return this;
  13522. }
  13523. if ( this.isEmpty() ) {
  13524. this.copy( sphere );
  13525. return this;
  13526. }
  13527. if ( this.center.equals( sphere.center ) === true ) {
  13528. this.radius = Math.max( this.radius, sphere.radius );
  13529. } else {
  13530. _v2$2.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  13531. this.expandByPoint( _v1$3.copy( sphere.center ).add( _v2$2 ) );
  13532. this.expandByPoint( _v1$3.copy( sphere.center ).sub( _v2$2 ) );
  13533. }
  13534. return this;
  13535. }
  13536. /**
  13537. * Returns `true` if this sphere is equal with the given one.
  13538. *
  13539. * @param {Sphere} sphere - The sphere to test for equality.
  13540. * @return {boolean} Whether this bounding sphere is equal with the given one.
  13541. */
  13542. equals( sphere ) {
  13543. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  13544. }
  13545. /**
  13546. * Returns a new sphere with copied values from this instance.
  13547. *
  13548. * @return {Sphere} A clone of this instance.
  13549. */
  13550. clone() {
  13551. return new this.constructor().copy( this );
  13552. }
  13553. /**
  13554. * Returns a serialized structure of the bounding sphere.
  13555. *
  13556. * @return {Object} Serialized structure with fields representing the object state.
  13557. */
  13558. toJSON() {
  13559. return {
  13560. radius: this.radius,
  13561. center: this.center.toArray()
  13562. };
  13563. }
  13564. /**
  13565. * Returns a serialized structure of the bounding sphere.
  13566. *
  13567. * @param {Object} json - The serialized json to set the sphere from.
  13568. * @return {Sphere} A reference to this bounding sphere.
  13569. */
  13570. fromJSON( json ) {
  13571. this.radius = json.radius;
  13572. this.center.fromArray( json.center );
  13573. return this;
  13574. }
  13575. }
  13576. let _id$1 = 0;
  13577. const _m1 = /*@__PURE__*/ new Matrix4();
  13578. const _obj = /*@__PURE__*/ new Object3D();
  13579. const _offset = /*@__PURE__*/ new Vector3();
  13580. const _box$2 = /*@__PURE__*/ new Box3();
  13581. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  13582. const _vector$9 = /*@__PURE__*/ new Vector3();
  13583. /**
  13584. * A representation of mesh, line, or point geometry. Includes vertex
  13585. * positions, face indices, normals, colors, UVs, and custom attributes
  13586. * within buffers, reducing the cost of passing all this data to the GPU.
  13587. *
  13588. * ```js
  13589. * const geometry = new THREE.BufferGeometry();
  13590. * // create a simple square shape. We duplicate the top left and bottom right
  13591. * // vertices because each vertex needs to appear once per triangle.
  13592. * const vertices = new Float32Array( [
  13593. * -1.0, -1.0, 1.0, // v0
  13594. * 1.0, -1.0, 1.0, // v1
  13595. * 1.0, 1.0, 1.0, // v2
  13596. *
  13597. * 1.0, 1.0, 1.0, // v3
  13598. * -1.0, 1.0, 1.0, // v4
  13599. * -1.0, -1.0, 1.0 // v5
  13600. * ] );
  13601. * // itemSize = 3 because there are 3 values (components) per vertex
  13602. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13603. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  13604. * const mesh = new THREE.Mesh( geometry, material );
  13605. * ```
  13606. *
  13607. * @augments EventDispatcher
  13608. */
  13609. class BufferGeometry extends EventDispatcher {
  13610. /**
  13611. * Constructs a new geometry.
  13612. */
  13613. constructor() {
  13614. super();
  13615. /**
  13616. * This flag can be used for type testing.
  13617. *
  13618. * @type {boolean}
  13619. * @readonly
  13620. * @default true
  13621. */
  13622. this.isBufferGeometry = true;
  13623. /**
  13624. * The ID of the geometry.
  13625. *
  13626. * @name BufferGeometry#id
  13627. * @type {number}
  13628. * @readonly
  13629. */
  13630. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  13631. /**
  13632. * The UUID of the geometry.
  13633. *
  13634. * @type {string}
  13635. * @readonly
  13636. */
  13637. this.uuid = generateUUID();
  13638. /**
  13639. * The name of the geometry.
  13640. *
  13641. * @type {string}
  13642. */
  13643. this.name = '';
  13644. this.type = 'BufferGeometry';
  13645. /**
  13646. * Allows for vertices to be re-used across multiple triangles; this is
  13647. * called using "indexed triangles". Each triangle is associated with the
  13648. * indices of three vertices. This attribute therefore stores the index of
  13649. * each vertex for each triangular face. If this attribute is not set, the
  13650. * renderer assumes that each three contiguous positions represent a single triangle.
  13651. *
  13652. * @type {?BufferAttribute}
  13653. * @default null
  13654. */
  13655. this.index = null;
  13656. /**
  13657. * A (storage) buffer attribute which was generated with a compute shader and
  13658. * now defines indirect draw calls.
  13659. *
  13660. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13661. *
  13662. * @type {?BufferAttribute}
  13663. * @default null
  13664. */
  13665. this.indirect = null;
  13666. /**
  13667. * The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  13668. *
  13669. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13670. *
  13671. * @type {number|Array<number>}
  13672. * @default 0
  13673. */
  13674. this.indirectOffset = 0;
  13675. /**
  13676. * This dictionary has as id the name of the attribute to be set and as value
  13677. * the buffer attribute to set it to. Rather than accessing this property directly,
  13678. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  13679. *
  13680. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  13681. */
  13682. this.attributes = {};
  13683. /**
  13684. * This dictionary holds the morph targets of the geometry.
  13685. *
  13686. * Note: Once the geometry has been rendered, the morph attribute data cannot
  13687. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  13688. *
  13689. * @type {Object}
  13690. */
  13691. this.morphAttributes = {};
  13692. /**
  13693. * Used to control the morph target behavior; when set to `true`, the morph
  13694. * target data is treated as relative offsets, rather than as absolute
  13695. * positions/normals.
  13696. *
  13697. * @type {boolean}
  13698. * @default false
  13699. */
  13700. this.morphTargetsRelative = false;
  13701. /**
  13702. * Split the geometry into groups, each of which will be rendered in a
  13703. * separate draw call. This allows an array of materials to be used with the geometry.
  13704. *
  13705. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  13706. *
  13707. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  13708. * indices, and must not leave vertices or indices unused.
  13709. *
  13710. * @type {Array<Object>}
  13711. */
  13712. this.groups = [];
  13713. /**
  13714. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  13715. *
  13716. * @type {?Box3}
  13717. * @default null
  13718. */
  13719. this.boundingBox = null;
  13720. /**
  13721. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  13722. *
  13723. * @type {?Sphere}
  13724. * @default null
  13725. */
  13726. this.boundingSphere = null;
  13727. /**
  13728. * Determines the part of the geometry to render. This should not be set directly,
  13729. * instead use `setDrawRange()`.
  13730. *
  13731. * @type {{start:number,count:number}}
  13732. */
  13733. this.drawRange = { start: 0, count: Infinity };
  13734. /**
  13735. * An object that can be used to store custom data about the geometry.
  13736. * It should not hold references to functions as these will not be cloned.
  13737. *
  13738. * @type {Object}
  13739. */
  13740. this.userData = {};
  13741. }
  13742. /**
  13743. * Returns the index of this geometry.
  13744. *
  13745. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  13746. */
  13747. getIndex() {
  13748. return this.index;
  13749. }
  13750. /**
  13751. * Sets the given index to this geometry.
  13752. *
  13753. * @param {Array<number>|BufferAttribute} index - The index to set.
  13754. * @return {BufferGeometry} A reference to this instance.
  13755. */
  13756. setIndex( index ) {
  13757. if ( Array.isArray( index ) ) {
  13758. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  13759. } else {
  13760. this.index = index;
  13761. }
  13762. return this;
  13763. }
  13764. /**
  13765. * Sets the given indirect attribute to this geometry.
  13766. *
  13767. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  13768. * @param {number|Array<number>} [indirectOffset=0] - The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  13769. * @return {BufferGeometry} A reference to this instance.
  13770. */
  13771. setIndirect( indirect, indirectOffset = 0 ) {
  13772. this.indirect = indirect;
  13773. this.indirectOffset = indirectOffset;
  13774. return this;
  13775. }
  13776. /**
  13777. * Returns the indirect attribute of this geometry.
  13778. *
  13779. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  13780. */
  13781. getIndirect() {
  13782. return this.indirect;
  13783. }
  13784. /**
  13785. * Returns the buffer attribute for the given name.
  13786. *
  13787. * @param {string} name - The attribute name.
  13788. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  13789. * Returns `undefined` if not attribute has been found.
  13790. */
  13791. getAttribute( name ) {
  13792. return this.attributes[ name ];
  13793. }
  13794. /**
  13795. * Sets the given attribute for the given name.
  13796. *
  13797. * @param {string} name - The attribute name.
  13798. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  13799. * @return {BufferGeometry} A reference to this instance.
  13800. */
  13801. setAttribute( name, attribute ) {
  13802. this.attributes[ name ] = attribute;
  13803. return this;
  13804. }
  13805. /**
  13806. * Deletes the attribute for the given name.
  13807. *
  13808. * @param {string} name - The attribute name to delete.
  13809. * @return {BufferGeometry} A reference to this instance.
  13810. */
  13811. deleteAttribute( name ) {
  13812. delete this.attributes[ name ];
  13813. return this;
  13814. }
  13815. /**
  13816. * Returns `true` if this geometry has an attribute for the given name.
  13817. *
  13818. * @param {string} name - The attribute name.
  13819. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  13820. */
  13821. hasAttribute( name ) {
  13822. return this.attributes[ name ] !== undefined;
  13823. }
  13824. /**
  13825. * Adds a group to this geometry.
  13826. *
  13827. * @param {number} start - The first element in this draw call. That is the first
  13828. * vertex for non-indexed geometry, otherwise the first triangle index.
  13829. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  13830. * @param {number} [materialIndex=0] - The material array index to use.
  13831. */
  13832. addGroup( start, count, materialIndex = 0 ) {
  13833. this.groups.push( {
  13834. start: start,
  13835. count: count,
  13836. materialIndex: materialIndex
  13837. } );
  13838. }
  13839. /**
  13840. * Clears all groups.
  13841. */
  13842. clearGroups() {
  13843. this.groups = [];
  13844. }
  13845. /**
  13846. * Sets the draw range for this geometry.
  13847. *
  13848. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  13849. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  13850. * For indexed BufferGeometry, `count` is the number of indices to render.
  13851. */
  13852. setDrawRange( start, count ) {
  13853. this.drawRange.start = start;
  13854. this.drawRange.count = count;
  13855. }
  13856. /**
  13857. * Applies the given 4x4 transformation matrix to the geometry.
  13858. *
  13859. * @param {Matrix4} matrix - The matrix to apply.
  13860. * @return {BufferGeometry} A reference to this instance.
  13861. */
  13862. applyMatrix4( matrix ) {
  13863. const position = this.attributes.position;
  13864. if ( position !== undefined ) {
  13865. position.applyMatrix4( matrix );
  13866. position.needsUpdate = true;
  13867. }
  13868. const normal = this.attributes.normal;
  13869. if ( normal !== undefined ) {
  13870. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  13871. normal.applyNormalMatrix( normalMatrix );
  13872. normal.needsUpdate = true;
  13873. }
  13874. const tangent = this.attributes.tangent;
  13875. if ( tangent !== undefined ) {
  13876. tangent.transformDirection( matrix );
  13877. tangent.needsUpdate = true;
  13878. }
  13879. if ( this.boundingBox !== null ) {
  13880. this.computeBoundingBox();
  13881. }
  13882. if ( this.boundingSphere !== null ) {
  13883. this.computeBoundingSphere();
  13884. }
  13885. return this;
  13886. }
  13887. /**
  13888. * Applies the rotation represented by the Quaternion to the geometry.
  13889. *
  13890. * @param {Quaternion} q - The Quaternion to apply.
  13891. * @return {BufferGeometry} A reference to this instance.
  13892. */
  13893. applyQuaternion( q ) {
  13894. _m1.makeRotationFromQuaternion( q );
  13895. this.applyMatrix4( _m1 );
  13896. return this;
  13897. }
  13898. /**
  13899. * Rotates the geometry about the X axis. This is typically done as a one time
  13900. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13901. * real-time mesh rotation.
  13902. *
  13903. * @param {number} angle - The angle in radians.
  13904. * @return {BufferGeometry} A reference to this instance.
  13905. */
  13906. rotateX( angle ) {
  13907. // rotate geometry around world x-axis
  13908. _m1.makeRotationX( angle );
  13909. this.applyMatrix4( _m1 );
  13910. return this;
  13911. }
  13912. /**
  13913. * Rotates the geometry about the Y axis. This is typically done as a one time
  13914. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13915. * real-time mesh rotation.
  13916. *
  13917. * @param {number} angle - The angle in radians.
  13918. * @return {BufferGeometry} A reference to this instance.
  13919. */
  13920. rotateY( angle ) {
  13921. // rotate geometry around world y-axis
  13922. _m1.makeRotationY( angle );
  13923. this.applyMatrix4( _m1 );
  13924. return this;
  13925. }
  13926. /**
  13927. * Rotates the geometry about the Z axis. This is typically done as a one time
  13928. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13929. * real-time mesh rotation.
  13930. *
  13931. * @param {number} angle - The angle in radians.
  13932. * @return {BufferGeometry} A reference to this instance.
  13933. */
  13934. rotateZ( angle ) {
  13935. // rotate geometry around world z-axis
  13936. _m1.makeRotationZ( angle );
  13937. this.applyMatrix4( _m1 );
  13938. return this;
  13939. }
  13940. /**
  13941. * Translates the geometry. This is typically done as a one time
  13942. * operation, and not during a loop. Use {@link Object3D#position} for typical
  13943. * real-time mesh rotation.
  13944. *
  13945. * @param {number} x - The x offset.
  13946. * @param {number} y - The y offset.
  13947. * @param {number} z - The z offset.
  13948. * @return {BufferGeometry} A reference to this instance.
  13949. */
  13950. translate( x, y, z ) {
  13951. // translate geometry
  13952. _m1.makeTranslation( x, y, z );
  13953. this.applyMatrix4( _m1 );
  13954. return this;
  13955. }
  13956. /**
  13957. * Scales the geometry. This is typically done as a one time
  13958. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  13959. * real-time mesh rotation.
  13960. *
  13961. * @param {number} x - The x scale.
  13962. * @param {number} y - The y scale.
  13963. * @param {number} z - The z scale.
  13964. * @return {BufferGeometry} A reference to this instance.
  13965. */
  13966. scale( x, y, z ) {
  13967. // scale geometry
  13968. _m1.makeScale( x, y, z );
  13969. this.applyMatrix4( _m1 );
  13970. return this;
  13971. }
  13972. /**
  13973. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  13974. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  13975. * real-time mesh rotation.
  13976. *
  13977. * @param {Vector3} vector - The target point.
  13978. * @return {BufferGeometry} A reference to this instance.
  13979. */
  13980. lookAt( vector ) {
  13981. _obj.lookAt( vector );
  13982. _obj.updateMatrix();
  13983. this.applyMatrix4( _obj.matrix );
  13984. return this;
  13985. }
  13986. /**
  13987. * Center the geometry based on its bounding box.
  13988. *
  13989. * @return {BufferGeometry} A reference to this instance.
  13990. */
  13991. center() {
  13992. this.computeBoundingBox();
  13993. this.boundingBox.getCenter( _offset ).negate();
  13994. this.translate( _offset.x, _offset.y, _offset.z );
  13995. return this;
  13996. }
  13997. /**
  13998. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  13999. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14000. * set to `0`.
  14001. *
  14002. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14003. * data from the array. The length of the array must match the vertex count.
  14004. *
  14005. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14006. * @return {BufferGeometry} A reference to this instance.
  14007. */
  14008. setFromPoints( points ) {
  14009. const positionAttribute = this.getAttribute( 'position' );
  14010. if ( positionAttribute === undefined ) {
  14011. const position = [];
  14012. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14013. const point = points[ i ];
  14014. position.push( point.x, point.y, point.z || 0 );
  14015. }
  14016. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14017. } else {
  14018. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14019. for ( let i = 0; i < l; i ++ ) {
  14020. const point = points[ i ];
  14021. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14022. }
  14023. if ( points.length > positionAttribute.count ) {
  14024. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14025. }
  14026. positionAttribute.needsUpdate = true;
  14027. }
  14028. return this;
  14029. }
  14030. /**
  14031. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14032. * The bounding box is not computed by the engine; it must be computed by your app.
  14033. * You may need to recompute the bounding box if the geometry vertices are modified.
  14034. */
  14035. computeBoundingBox() {
  14036. if ( this.boundingBox === null ) {
  14037. this.boundingBox = new Box3();
  14038. }
  14039. const position = this.attributes.position;
  14040. const morphAttributesPosition = this.morphAttributes.position;
  14041. if ( position && position.isGLBufferAttribute ) {
  14042. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14043. this.boundingBox.set(
  14044. new Vector3( - Infinity, - Infinity, - Infinity ),
  14045. new Vector3( + Infinity, + Infinity, + Infinity )
  14046. );
  14047. return;
  14048. }
  14049. if ( position !== undefined ) {
  14050. this.boundingBox.setFromBufferAttribute( position );
  14051. // process morph attributes if present
  14052. if ( morphAttributesPosition ) {
  14053. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14054. const morphAttribute = morphAttributesPosition[ i ];
  14055. _box$2.setFromBufferAttribute( morphAttribute );
  14056. if ( this.morphTargetsRelative ) {
  14057. _vector$9.addVectors( this.boundingBox.min, _box$2.min );
  14058. this.boundingBox.expandByPoint( _vector$9 );
  14059. _vector$9.addVectors( this.boundingBox.max, _box$2.max );
  14060. this.boundingBox.expandByPoint( _vector$9 );
  14061. } else {
  14062. this.boundingBox.expandByPoint( _box$2.min );
  14063. this.boundingBox.expandByPoint( _box$2.max );
  14064. }
  14065. }
  14066. }
  14067. } else {
  14068. this.boundingBox.makeEmpty();
  14069. }
  14070. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14071. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14072. }
  14073. }
  14074. /**
  14075. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14076. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14077. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14078. */
  14079. computeBoundingSphere() {
  14080. if ( this.boundingSphere === null ) {
  14081. this.boundingSphere = new Sphere();
  14082. }
  14083. const position = this.attributes.position;
  14084. const morphAttributesPosition = this.morphAttributes.position;
  14085. if ( position && position.isGLBufferAttribute ) {
  14086. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14087. this.boundingSphere.set( new Vector3(), Infinity );
  14088. return;
  14089. }
  14090. if ( position ) {
  14091. // first, find the center of the bounding sphere
  14092. const center = this.boundingSphere.center;
  14093. _box$2.setFromBufferAttribute( position );
  14094. // process morph attributes if present
  14095. if ( morphAttributesPosition ) {
  14096. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14097. const morphAttribute = morphAttributesPosition[ i ];
  14098. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14099. if ( this.morphTargetsRelative ) {
  14100. _vector$9.addVectors( _box$2.min, _boxMorphTargets.min );
  14101. _box$2.expandByPoint( _vector$9 );
  14102. _vector$9.addVectors( _box$2.max, _boxMorphTargets.max );
  14103. _box$2.expandByPoint( _vector$9 );
  14104. } else {
  14105. _box$2.expandByPoint( _boxMorphTargets.min );
  14106. _box$2.expandByPoint( _boxMorphTargets.max );
  14107. }
  14108. }
  14109. }
  14110. _box$2.getCenter( center );
  14111. // second, try to find a boundingSphere with a radius smaller than the
  14112. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14113. let maxRadiusSq = 0;
  14114. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14115. _vector$9.fromBufferAttribute( position, i );
  14116. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) );
  14117. }
  14118. // process morph attributes if present
  14119. if ( morphAttributesPosition ) {
  14120. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14121. const morphAttribute = morphAttributesPosition[ i ];
  14122. const morphTargetsRelative = this.morphTargetsRelative;
  14123. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14124. _vector$9.fromBufferAttribute( morphAttribute, j );
  14125. if ( morphTargetsRelative ) {
  14126. _offset.fromBufferAttribute( position, j );
  14127. _vector$9.add( _offset );
  14128. }
  14129. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) );
  14130. }
  14131. }
  14132. }
  14133. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14134. if ( isNaN( this.boundingSphere.radius ) ) {
  14135. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14136. }
  14137. }
  14138. }
  14139. /**
  14140. * Calculates and adds a tangent attribute to this geometry.
  14141. *
  14142. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14143. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14144. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14145. */
  14146. computeTangents() {
  14147. const index = this.index;
  14148. const attributes = this.attributes;
  14149. // based on http://www.terathon.com/code/tangent.html
  14150. // (per vertex tangents)
  14151. if ( index === null ||
  14152. attributes.position === undefined ||
  14153. attributes.normal === undefined ||
  14154. attributes.uv === undefined ) {
  14155. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14156. return;
  14157. }
  14158. const positionAttribute = attributes.position;
  14159. const normalAttribute = attributes.normal;
  14160. const uvAttribute = attributes.uv;
  14161. if ( this.hasAttribute( 'tangent' ) === false ) {
  14162. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14163. }
  14164. const tangentAttribute = this.getAttribute( 'tangent' );
  14165. const tan1 = [], tan2 = [];
  14166. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14167. tan1[ i ] = new Vector3();
  14168. tan2[ i ] = new Vector3();
  14169. }
  14170. const vA = new Vector3(),
  14171. vB = new Vector3(),
  14172. vC = new Vector3(),
  14173. uvA = new Vector2(),
  14174. uvB = new Vector2(),
  14175. uvC = new Vector2(),
  14176. sdir = new Vector3(),
  14177. tdir = new Vector3();
  14178. function handleTriangle( a, b, c ) {
  14179. vA.fromBufferAttribute( positionAttribute, a );
  14180. vB.fromBufferAttribute( positionAttribute, b );
  14181. vC.fromBufferAttribute( positionAttribute, c );
  14182. uvA.fromBufferAttribute( uvAttribute, a );
  14183. uvB.fromBufferAttribute( uvAttribute, b );
  14184. uvC.fromBufferAttribute( uvAttribute, c );
  14185. vB.sub( vA );
  14186. vC.sub( vA );
  14187. uvB.sub( uvA );
  14188. uvC.sub( uvA );
  14189. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14190. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14191. if ( ! isFinite( r ) ) return;
  14192. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14193. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14194. tan1[ a ].add( sdir );
  14195. tan1[ b ].add( sdir );
  14196. tan1[ c ].add( sdir );
  14197. tan2[ a ].add( tdir );
  14198. tan2[ b ].add( tdir );
  14199. tan2[ c ].add( tdir );
  14200. }
  14201. let groups = this.groups;
  14202. if ( groups.length === 0 ) {
  14203. groups = [ {
  14204. start: 0,
  14205. count: index.count
  14206. } ];
  14207. }
  14208. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14209. const group = groups[ i ];
  14210. const start = group.start;
  14211. const count = group.count;
  14212. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14213. handleTriangle(
  14214. index.getX( j + 0 ),
  14215. index.getX( j + 1 ),
  14216. index.getX( j + 2 )
  14217. );
  14218. }
  14219. }
  14220. const tmp = new Vector3(), tmp2 = new Vector3();
  14221. const n = new Vector3(), n2 = new Vector3();
  14222. function handleVertex( v ) {
  14223. n.fromBufferAttribute( normalAttribute, v );
  14224. n2.copy( n );
  14225. const t = tan1[ v ];
  14226. // Gram-Schmidt orthogonalize
  14227. tmp.copy( t );
  14228. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14229. // Calculate handedness
  14230. tmp2.crossVectors( n2, t );
  14231. const test = tmp2.dot( tan2[ v ] );
  14232. const w = ( test < 0.0 ) ? -1 : 1.0;
  14233. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14234. }
  14235. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14236. const group = groups[ i ];
  14237. const start = group.start;
  14238. const count = group.count;
  14239. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14240. handleVertex( index.getX( j + 0 ) );
  14241. handleVertex( index.getX( j + 1 ) );
  14242. handleVertex( index.getX( j + 2 ) );
  14243. }
  14244. }
  14245. }
  14246. /**
  14247. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14248. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14249. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14250. * to be the same as the face normal.
  14251. */
  14252. computeVertexNormals() {
  14253. const index = this.index;
  14254. const positionAttribute = this.getAttribute( 'position' );
  14255. if ( positionAttribute !== undefined ) {
  14256. let normalAttribute = this.getAttribute( 'normal' );
  14257. if ( normalAttribute === undefined ) {
  14258. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14259. this.setAttribute( 'normal', normalAttribute );
  14260. } else {
  14261. // reset existing normals to zero
  14262. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14263. normalAttribute.setXYZ( i, 0, 0, 0 );
  14264. }
  14265. }
  14266. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14267. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14268. const cb = new Vector3(), ab = new Vector3();
  14269. // indexed elements
  14270. if ( index ) {
  14271. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14272. const vA = index.getX( i + 0 );
  14273. const vB = index.getX( i + 1 );
  14274. const vC = index.getX( i + 2 );
  14275. pA.fromBufferAttribute( positionAttribute, vA );
  14276. pB.fromBufferAttribute( positionAttribute, vB );
  14277. pC.fromBufferAttribute( positionAttribute, vC );
  14278. cb.subVectors( pC, pB );
  14279. ab.subVectors( pA, pB );
  14280. cb.cross( ab );
  14281. nA.fromBufferAttribute( normalAttribute, vA );
  14282. nB.fromBufferAttribute( normalAttribute, vB );
  14283. nC.fromBufferAttribute( normalAttribute, vC );
  14284. nA.add( cb );
  14285. nB.add( cb );
  14286. nC.add( cb );
  14287. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14288. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14289. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14290. }
  14291. } else {
  14292. // non-indexed elements (unconnected triangle soup)
  14293. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14294. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14295. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14296. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14297. cb.subVectors( pC, pB );
  14298. ab.subVectors( pA, pB );
  14299. cb.cross( ab );
  14300. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14301. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14302. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14303. }
  14304. }
  14305. this.normalizeNormals();
  14306. normalAttribute.needsUpdate = true;
  14307. }
  14308. }
  14309. /**
  14310. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14311. * correct lighting on the geometry surfaces.
  14312. */
  14313. normalizeNormals() {
  14314. const normals = this.attributes.normal;
  14315. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14316. _vector$9.fromBufferAttribute( normals, i );
  14317. _vector$9.normalize();
  14318. normals.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  14319. }
  14320. }
  14321. /**
  14322. * Return a new non-index version of this indexed geometry. If the geometry
  14323. * is already non-indexed, the method is a NOOP.
  14324. *
  14325. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14326. */
  14327. toNonIndexed() {
  14328. function convertBufferAttribute( attribute, indices ) {
  14329. const array = attribute.array;
  14330. const itemSize = attribute.itemSize;
  14331. const normalized = attribute.normalized;
  14332. const array2 = new array.constructor( indices.length * itemSize );
  14333. let index = 0, index2 = 0;
  14334. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14335. if ( attribute.isInterleavedBufferAttribute ) {
  14336. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14337. } else {
  14338. index = indices[ i ] * itemSize;
  14339. }
  14340. for ( let j = 0; j < itemSize; j ++ ) {
  14341. array2[ index2 ++ ] = array[ index ++ ];
  14342. }
  14343. }
  14344. return new BufferAttribute( array2, itemSize, normalized );
  14345. }
  14346. //
  14347. if ( this.index === null ) {
  14348. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14349. return this;
  14350. }
  14351. const geometry2 = new BufferGeometry();
  14352. const indices = this.index.array;
  14353. const attributes = this.attributes;
  14354. // attributes
  14355. for ( const name in attributes ) {
  14356. const attribute = attributes[ name ];
  14357. const newAttribute = convertBufferAttribute( attribute, indices );
  14358. geometry2.setAttribute( name, newAttribute );
  14359. }
  14360. // morph attributes
  14361. const morphAttributes = this.morphAttributes;
  14362. for ( const name in morphAttributes ) {
  14363. const morphArray = [];
  14364. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14365. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14366. const attribute = morphAttribute[ i ];
  14367. const newAttribute = convertBufferAttribute( attribute, indices );
  14368. morphArray.push( newAttribute );
  14369. }
  14370. geometry2.morphAttributes[ name ] = morphArray;
  14371. }
  14372. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14373. // groups
  14374. const groups = this.groups;
  14375. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14376. const group = groups[ i ];
  14377. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14378. }
  14379. return geometry2;
  14380. }
  14381. /**
  14382. * Serializes the geometry into JSON.
  14383. *
  14384. * @return {Object} A JSON object representing the serialized geometry.
  14385. */
  14386. toJSON() {
  14387. const data = {
  14388. metadata: {
  14389. version: 4.7,
  14390. type: 'BufferGeometry',
  14391. generator: 'BufferGeometry.toJSON'
  14392. }
  14393. };
  14394. // standard BufferGeometry serialization
  14395. data.uuid = this.uuid;
  14396. data.type = this.type;
  14397. if ( this.name !== '' ) data.name = this.name;
  14398. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14399. if ( this.parameters !== undefined ) {
  14400. const parameters = this.parameters;
  14401. for ( const key in parameters ) {
  14402. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14403. }
  14404. return data;
  14405. }
  14406. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14407. data.data = { attributes: {} };
  14408. const index = this.index;
  14409. if ( index !== null ) {
  14410. data.data.index = {
  14411. type: index.array.constructor.name,
  14412. array: Array.prototype.slice.call( index.array )
  14413. };
  14414. }
  14415. const attributes = this.attributes;
  14416. for ( const key in attributes ) {
  14417. const attribute = attributes[ key ];
  14418. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14419. }
  14420. const morphAttributes = {};
  14421. let hasMorphAttributes = false;
  14422. for ( const key in this.morphAttributes ) {
  14423. const attributeArray = this.morphAttributes[ key ];
  14424. const array = [];
  14425. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14426. const attribute = attributeArray[ i ];
  14427. array.push( attribute.toJSON( data.data ) );
  14428. }
  14429. if ( array.length > 0 ) {
  14430. morphAttributes[ key ] = array;
  14431. hasMorphAttributes = true;
  14432. }
  14433. }
  14434. if ( hasMorphAttributes ) {
  14435. data.data.morphAttributes = morphAttributes;
  14436. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14437. }
  14438. const groups = this.groups;
  14439. if ( groups.length > 0 ) {
  14440. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14441. }
  14442. const boundingSphere = this.boundingSphere;
  14443. if ( boundingSphere !== null ) {
  14444. data.data.boundingSphere = boundingSphere.toJSON();
  14445. }
  14446. return data;
  14447. }
  14448. /**
  14449. * Returns a new geometry with copied values from this instance.
  14450. *
  14451. * @return {BufferGeometry} A clone of this instance.
  14452. */
  14453. clone() {
  14454. return new this.constructor().copy( this );
  14455. }
  14456. /**
  14457. * Copies the values of the given geometry to this instance.
  14458. *
  14459. * @param {BufferGeometry} source - The geometry to copy.
  14460. * @return {BufferGeometry} A reference to this instance.
  14461. */
  14462. copy( source ) {
  14463. // reset
  14464. this.index = null;
  14465. this.attributes = {};
  14466. this.morphAttributes = {};
  14467. this.groups = [];
  14468. this.boundingBox = null;
  14469. this.boundingSphere = null;
  14470. // used for storing cloned, shared data
  14471. const data = {};
  14472. // name
  14473. this.name = source.name;
  14474. // index
  14475. const index = source.index;
  14476. if ( index !== null ) {
  14477. this.setIndex( index.clone() );
  14478. }
  14479. // attributes
  14480. const attributes = source.attributes;
  14481. for ( const name in attributes ) {
  14482. const attribute = attributes[ name ];
  14483. this.setAttribute( name, attribute.clone( data ) );
  14484. }
  14485. // morph attributes
  14486. const morphAttributes = source.morphAttributes;
  14487. for ( const name in morphAttributes ) {
  14488. const array = [];
  14489. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14490. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  14491. array.push( morphAttribute[ i ].clone( data ) );
  14492. }
  14493. this.morphAttributes[ name ] = array;
  14494. }
  14495. this.morphTargetsRelative = source.morphTargetsRelative;
  14496. // groups
  14497. const groups = source.groups;
  14498. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14499. const group = groups[ i ];
  14500. this.addGroup( group.start, group.count, group.materialIndex );
  14501. }
  14502. // bounding box
  14503. const boundingBox = source.boundingBox;
  14504. if ( boundingBox !== null ) {
  14505. this.boundingBox = boundingBox.clone();
  14506. }
  14507. // bounding sphere
  14508. const boundingSphere = source.boundingSphere;
  14509. if ( boundingSphere !== null ) {
  14510. this.boundingSphere = boundingSphere.clone();
  14511. }
  14512. // draw range
  14513. this.drawRange.start = source.drawRange.start;
  14514. this.drawRange.count = source.drawRange.count;
  14515. // user data
  14516. this.userData = source.userData;
  14517. return this;
  14518. }
  14519. /**
  14520. * Frees the GPU-related resources allocated by this instance. Call this
  14521. * method whenever this instance is no longer used in your app.
  14522. *
  14523. * @fires BufferGeometry#dispose
  14524. */
  14525. dispose() {
  14526. this.dispatchEvent( { type: 'dispose' } );
  14527. }
  14528. }
  14529. /**
  14530. * "Interleaved" means that multiple attributes, possibly of different types,
  14531. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  14532. *
  14533. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  14534. */
  14535. class InterleavedBuffer {
  14536. /**
  14537. * Constructs a new interleaved buffer.
  14538. *
  14539. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  14540. * @param {number} stride - The number of typed-array elements per vertex.
  14541. */
  14542. constructor( array, stride ) {
  14543. /**
  14544. * This flag can be used for type testing.
  14545. *
  14546. * @type {boolean}
  14547. * @readonly
  14548. * @default true
  14549. */
  14550. this.isInterleavedBuffer = true;
  14551. /**
  14552. * A typed array with a shared buffer storing attribute data.
  14553. *
  14554. * @type {TypedArray}
  14555. */
  14556. this.array = array;
  14557. /**
  14558. * The number of typed-array elements per vertex.
  14559. *
  14560. * @type {number}
  14561. */
  14562. this.stride = stride;
  14563. /**
  14564. * The total number of elements in the array
  14565. *
  14566. * @type {number}
  14567. * @readonly
  14568. */
  14569. this.count = array !== undefined ? array.length / stride : 0;
  14570. /**
  14571. * Defines the intended usage pattern of the data store for optimization purposes.
  14572. *
  14573. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  14574. * instantiate a new one and set the desired usage before the next render.
  14575. *
  14576. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  14577. * @default StaticDrawUsage
  14578. */
  14579. this.usage = StaticDrawUsage;
  14580. /**
  14581. * This can be used to only update some components of stored vectors (for example, just the
  14582. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  14583. *
  14584. * @type {Array<Object>}
  14585. */
  14586. this.updateRanges = [];
  14587. /**
  14588. * A version number, incremented every time the `needsUpdate` is set to `true`.
  14589. *
  14590. * @type {number}
  14591. */
  14592. this.version = 0;
  14593. /**
  14594. * The UUID of the interleaved buffer.
  14595. *
  14596. * @type {string}
  14597. * @readonly
  14598. */
  14599. this.uuid = generateUUID();
  14600. }
  14601. /**
  14602. * A callback function that is executed after the renderer has transferred the attribute array
  14603. * data to the GPU.
  14604. */
  14605. onUploadCallback() {}
  14606. /**
  14607. * Flag to indicate that this attribute has changed and should be re-sent to
  14608. * the GPU. Set this to `true` when you modify the value of the array.
  14609. *
  14610. * @type {number}
  14611. * @default false
  14612. * @param {boolean} value
  14613. */
  14614. set needsUpdate( value ) {
  14615. if ( value === true ) this.version ++;
  14616. }
  14617. /**
  14618. * Sets the usage of this interleaved buffer.
  14619. *
  14620. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  14621. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  14622. */
  14623. setUsage( value ) {
  14624. this.usage = value;
  14625. return this;
  14626. }
  14627. /**
  14628. * Adds a range of data in the data array to be updated on the GPU.
  14629. *
  14630. * @param {number} start - Position at which to start update.
  14631. * @param {number} count - The number of components to update.
  14632. */
  14633. addUpdateRange( start, count ) {
  14634. this.updateRanges.push( { start, count } );
  14635. }
  14636. /**
  14637. * Clears the update ranges.
  14638. */
  14639. clearUpdateRanges() {
  14640. this.updateRanges.length = 0;
  14641. }
  14642. /**
  14643. * Copies the values of the given interleaved buffer to this instance.
  14644. *
  14645. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  14646. * @return {InterleavedBuffer} A reference to this instance.
  14647. */
  14648. copy( source ) {
  14649. this.array = new source.array.constructor( source.array );
  14650. this.count = source.count;
  14651. this.stride = source.stride;
  14652. this.usage = source.usage;
  14653. return this;
  14654. }
  14655. /**
  14656. * Copies a vector from the given interleaved buffer to this one. The start
  14657. * and destination position in the attribute buffers are represented by the
  14658. * given indices.
  14659. *
  14660. * @param {number} index1 - The destination index into this interleaved buffer.
  14661. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  14662. * @param {number} index2 - The source index into the given interleaved buffer.
  14663. * @return {InterleavedBuffer} A reference to this instance.
  14664. */
  14665. copyAt( index1, interleavedBuffer, index2 ) {
  14666. index1 *= this.stride;
  14667. index2 *= interleavedBuffer.stride;
  14668. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  14669. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  14670. }
  14671. return this;
  14672. }
  14673. /**
  14674. * Sets the given array data in the interleaved buffer.
  14675. *
  14676. * @param {(TypedArray|Array)} value - The array data to set.
  14677. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  14678. * @return {InterleavedBuffer} A reference to this instance.
  14679. */
  14680. set( value, offset = 0 ) {
  14681. this.array.set( value, offset );
  14682. return this;
  14683. }
  14684. /**
  14685. * Returns a new interleaved buffer with copied values from this instance.
  14686. *
  14687. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  14688. * @return {InterleavedBuffer} A clone of this instance.
  14689. */
  14690. clone( data ) {
  14691. if ( data.arrayBuffers === undefined ) {
  14692. data.arrayBuffers = {};
  14693. }
  14694. if ( this.array.buffer._uuid === undefined ) {
  14695. this.array.buffer._uuid = generateUUID();
  14696. }
  14697. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  14698. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  14699. }
  14700. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  14701. const ib = new this.constructor( array, this.stride );
  14702. ib.setUsage( this.usage );
  14703. return ib;
  14704. }
  14705. /**
  14706. * Sets the given callback function that is executed after the Renderer has transferred
  14707. * the array data to the GPU. Can be used to perform clean-up operations after
  14708. * the upload when data are not needed anymore on the CPU side.
  14709. *
  14710. * @param {Function} callback - The `onUpload()` callback.
  14711. * @return {InterleavedBuffer} A reference to this instance.
  14712. */
  14713. onUpload( callback ) {
  14714. this.onUploadCallback = callback;
  14715. return this;
  14716. }
  14717. /**
  14718. * Serializes the interleaved buffer into JSON.
  14719. *
  14720. * @param {Object} [data] - An optional value holding meta information about the serialization.
  14721. * @return {Object} A JSON object representing the serialized interleaved buffer.
  14722. */
  14723. toJSON( data ) {
  14724. if ( data.arrayBuffers === undefined ) {
  14725. data.arrayBuffers = {};
  14726. }
  14727. // generate UUID for array buffer if necessary
  14728. if ( this.array.buffer._uuid === undefined ) {
  14729. this.array.buffer._uuid = generateUUID();
  14730. }
  14731. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  14732. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  14733. }
  14734. //
  14735. return {
  14736. uuid: this.uuid,
  14737. buffer: this.array.buffer._uuid,
  14738. type: this.array.constructor.name,
  14739. stride: this.stride
  14740. };
  14741. }
  14742. }
  14743. const _vector$8 = /*@__PURE__*/ new Vector3();
  14744. /**
  14745. * An alternative version of a buffer attribute with interleaved data. Interleaved
  14746. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  14747. * different offsets into the buffer.
  14748. */
  14749. class InterleavedBufferAttribute {
  14750. /**
  14751. * Constructs a new interleaved buffer attribute.
  14752. *
  14753. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  14754. * @param {number} itemSize - The item size.
  14755. * @param {number} offset - The attribute offset into the buffer.
  14756. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14757. */
  14758. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  14759. /**
  14760. * This flag can be used for type testing.
  14761. *
  14762. * @type {boolean}
  14763. * @readonly
  14764. * @default true
  14765. */
  14766. this.isInterleavedBufferAttribute = true;
  14767. /**
  14768. * The name of the buffer attribute.
  14769. *
  14770. * @type {string}
  14771. */
  14772. this.name = '';
  14773. /**
  14774. * The buffer holding the interleaved data.
  14775. *
  14776. * @type {InterleavedBuffer}
  14777. */
  14778. this.data = interleavedBuffer;
  14779. /**
  14780. * The item size, see {@link BufferAttribute#itemSize}.
  14781. *
  14782. * @type {number}
  14783. */
  14784. this.itemSize = itemSize;
  14785. /**
  14786. * The attribute offset into the buffer.
  14787. *
  14788. * @type {number}
  14789. */
  14790. this.offset = offset;
  14791. /**
  14792. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  14793. *
  14794. * @type {InterleavedBuffer}
  14795. */
  14796. this.normalized = normalized;
  14797. }
  14798. /**
  14799. * The item count of this buffer attribute.
  14800. *
  14801. * @type {number}
  14802. * @readonly
  14803. */
  14804. get count() {
  14805. return this.data.count;
  14806. }
  14807. /**
  14808. * The array holding the interleaved buffer attribute data.
  14809. *
  14810. * @type {TypedArray}
  14811. */
  14812. get array() {
  14813. return this.data.array;
  14814. }
  14815. /**
  14816. * Flag to indicate that this attribute has changed and should be re-sent to
  14817. * the GPU. Set this to `true` when you modify the value of the array.
  14818. *
  14819. * @type {number}
  14820. * @default false
  14821. * @param {boolean} value
  14822. */
  14823. set needsUpdate( value ) {
  14824. this.data.needsUpdate = value;
  14825. }
  14826. /**
  14827. * Applies the given 4x4 matrix to the given attribute. Only works with
  14828. * item size `3`.
  14829. *
  14830. * @param {Matrix4} m - The matrix to apply.
  14831. * @return {InterleavedBufferAttribute} A reference to this instance.
  14832. */
  14833. applyMatrix4( m ) {
  14834. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  14835. _vector$8.fromBufferAttribute( this, i );
  14836. _vector$8.applyMatrix4( m );
  14837. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14838. }
  14839. return this;
  14840. }
  14841. /**
  14842. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  14843. * item size `3`.
  14844. *
  14845. * @param {Matrix3} m - The normal matrix to apply.
  14846. * @return {InterleavedBufferAttribute} A reference to this instance.
  14847. */
  14848. applyNormalMatrix( m ) {
  14849. for ( let i = 0, l = this.count; i < l; i ++ ) {
  14850. _vector$8.fromBufferAttribute( this, i );
  14851. _vector$8.applyNormalMatrix( m );
  14852. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14853. }
  14854. return this;
  14855. }
  14856. /**
  14857. * Applies the given 4x4 matrix to the given attribute. Only works with
  14858. * item size `3` and with direction vectors.
  14859. *
  14860. * @param {Matrix4} m - The matrix to apply.
  14861. * @return {InterleavedBufferAttribute} A reference to this instance.
  14862. */
  14863. transformDirection( m ) {
  14864. for ( let i = 0, l = this.count; i < l; i ++ ) {
  14865. _vector$8.fromBufferAttribute( this, i );
  14866. _vector$8.transformDirection( m );
  14867. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14868. }
  14869. return this;
  14870. }
  14871. /**
  14872. * Returns the given component of the vector at the given index.
  14873. *
  14874. * @param {number} index - The index into the buffer attribute.
  14875. * @param {number} component - The component index.
  14876. * @return {number} The returned value.
  14877. */
  14878. getComponent( index, component ) {
  14879. let value = this.array[ index * this.data.stride + this.offset + component ];
  14880. if ( this.normalized ) value = denormalize( value, this.array );
  14881. return value;
  14882. }
  14883. /**
  14884. * Sets the given value to the given component of the vector at the given index.
  14885. *
  14886. * @param {number} index - The index into the buffer attribute.
  14887. * @param {number} component - The component index.
  14888. * @param {number} value - The value to set.
  14889. * @return {InterleavedBufferAttribute} A reference to this instance.
  14890. */
  14891. setComponent( index, component, value ) {
  14892. if ( this.normalized ) value = normalize( value, this.array );
  14893. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  14894. return this;
  14895. }
  14896. /**
  14897. * Sets the x component of the vector at the given index.
  14898. *
  14899. * @param {number} index - The index into the buffer attribute.
  14900. * @param {number} x - The value to set.
  14901. * @return {InterleavedBufferAttribute} A reference to this instance.
  14902. */
  14903. setX( index, x ) {
  14904. if ( this.normalized ) x = normalize( x, this.array );
  14905. this.data.array[ index * this.data.stride + this.offset ] = x;
  14906. return this;
  14907. }
  14908. /**
  14909. * Sets the y component of the vector at the given index.
  14910. *
  14911. * @param {number} index - The index into the buffer attribute.
  14912. * @param {number} y - The value to set.
  14913. * @return {InterleavedBufferAttribute} A reference to this instance.
  14914. */
  14915. setY( index, y ) {
  14916. if ( this.normalized ) y = normalize( y, this.array );
  14917. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  14918. return this;
  14919. }
  14920. /**
  14921. * Sets the z component of the vector at the given index.
  14922. *
  14923. * @param {number} index - The index into the buffer attribute.
  14924. * @param {number} z - The value to set.
  14925. * @return {InterleavedBufferAttribute} A reference to this instance.
  14926. */
  14927. setZ( index, z ) {
  14928. if ( this.normalized ) z = normalize( z, this.array );
  14929. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  14930. return this;
  14931. }
  14932. /**
  14933. * Sets the w component of the vector at the given index.
  14934. *
  14935. * @param {number} index - The index into the buffer attribute.
  14936. * @param {number} w - The value to set.
  14937. * @return {InterleavedBufferAttribute} A reference to this instance.
  14938. */
  14939. setW( index, w ) {
  14940. if ( this.normalized ) w = normalize( w, this.array );
  14941. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  14942. return this;
  14943. }
  14944. /**
  14945. * Returns the x component of the vector at the given index.
  14946. *
  14947. * @param {number} index - The index into the buffer attribute.
  14948. * @return {number} The x component.
  14949. */
  14950. getX( index ) {
  14951. let x = this.data.array[ index * this.data.stride + this.offset ];
  14952. if ( this.normalized ) x = denormalize( x, this.array );
  14953. return x;
  14954. }
  14955. /**
  14956. * Returns the y component of the vector at the given index.
  14957. *
  14958. * @param {number} index - The index into the buffer attribute.
  14959. * @return {number} The y component.
  14960. */
  14961. getY( index ) {
  14962. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  14963. if ( this.normalized ) y = denormalize( y, this.array );
  14964. return y;
  14965. }
  14966. /**
  14967. * Returns the z component of the vector at the given index.
  14968. *
  14969. * @param {number} index - The index into the buffer attribute.
  14970. * @return {number} The z component.
  14971. */
  14972. getZ( index ) {
  14973. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  14974. if ( this.normalized ) z = denormalize( z, this.array );
  14975. return z;
  14976. }
  14977. /**
  14978. * Returns the w component of the vector at the given index.
  14979. *
  14980. * @param {number} index - The index into the buffer attribute.
  14981. * @return {number} The w component.
  14982. */
  14983. getW( index ) {
  14984. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  14985. if ( this.normalized ) w = denormalize( w, this.array );
  14986. return w;
  14987. }
  14988. /**
  14989. * Sets the x and y component of the vector at the given index.
  14990. *
  14991. * @param {number} index - The index into the buffer attribute.
  14992. * @param {number} x - The value for the x component to set.
  14993. * @param {number} y - The value for the y component to set.
  14994. * @return {InterleavedBufferAttribute} A reference to this instance.
  14995. */
  14996. setXY( index, x, y ) {
  14997. index = index * this.data.stride + this.offset;
  14998. if ( this.normalized ) {
  14999. x = normalize( x, this.array );
  15000. y = normalize( y, this.array );
  15001. }
  15002. this.data.array[ index + 0 ] = x;
  15003. this.data.array[ index + 1 ] = y;
  15004. return this;
  15005. }
  15006. /**
  15007. * Sets the x, y and z component of the vector at the given index.
  15008. *
  15009. * @param {number} index - The index into the buffer attribute.
  15010. * @param {number} x - The value for the x component to set.
  15011. * @param {number} y - The value for the y component to set.
  15012. * @param {number} z - The value for the z component to set.
  15013. * @return {InterleavedBufferAttribute} A reference to this instance.
  15014. */
  15015. setXYZ( index, x, y, z ) {
  15016. index = index * this.data.stride + this.offset;
  15017. if ( this.normalized ) {
  15018. x = normalize( x, this.array );
  15019. y = normalize( y, this.array );
  15020. z = normalize( z, this.array );
  15021. }
  15022. this.data.array[ index + 0 ] = x;
  15023. this.data.array[ index + 1 ] = y;
  15024. this.data.array[ index + 2 ] = z;
  15025. return this;
  15026. }
  15027. /**
  15028. * Sets the x, y, z and w component of the vector at the given index.
  15029. *
  15030. * @param {number} index - The index into the buffer attribute.
  15031. * @param {number} x - The value for the x component to set.
  15032. * @param {number} y - The value for the y component to set.
  15033. * @param {number} z - The value for the z component to set.
  15034. * @param {number} w - The value for the w component to set.
  15035. * @return {InterleavedBufferAttribute} A reference to this instance.
  15036. */
  15037. setXYZW( index, x, y, z, w ) {
  15038. index = index * this.data.stride + this.offset;
  15039. if ( this.normalized ) {
  15040. x = normalize( x, this.array );
  15041. y = normalize( y, this.array );
  15042. z = normalize( z, this.array );
  15043. w = normalize( w, this.array );
  15044. }
  15045. this.data.array[ index + 0 ] = x;
  15046. this.data.array[ index + 1 ] = y;
  15047. this.data.array[ index + 2 ] = z;
  15048. this.data.array[ index + 3 ] = w;
  15049. return this;
  15050. }
  15051. /**
  15052. * Returns a new buffer attribute with copied values from this instance.
  15053. *
  15054. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  15055. *
  15056. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  15057. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  15058. */
  15059. clone( data ) {
  15060. if ( data === undefined ) {
  15061. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  15062. const array = [];
  15063. for ( let i = 0; i < this.count; i ++ ) {
  15064. const index = i * this.data.stride + this.offset;
  15065. for ( let j = 0; j < this.itemSize; j ++ ) {
  15066. array.push( this.data.array[ index + j ] );
  15067. }
  15068. }
  15069. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  15070. } else {
  15071. if ( data.interleavedBuffers === undefined ) {
  15072. data.interleavedBuffers = {};
  15073. }
  15074. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15075. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  15076. }
  15077. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  15078. }
  15079. }
  15080. /**
  15081. * Serializes the buffer attribute into JSON.
  15082. *
  15083. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  15084. *
  15085. * @param {Object} [data] - An optional value holding meta information about the serialization.
  15086. * @return {Object} A JSON object representing the serialized buffer attribute.
  15087. */
  15088. toJSON( data ) {
  15089. if ( data === undefined ) {
  15090. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  15091. const array = [];
  15092. for ( let i = 0; i < this.count; i ++ ) {
  15093. const index = i * this.data.stride + this.offset;
  15094. for ( let j = 0; j < this.itemSize; j ++ ) {
  15095. array.push( this.data.array[ index + j ] );
  15096. }
  15097. }
  15098. // de-interleave data and save it as an ordinary buffer attribute for now
  15099. return {
  15100. itemSize: this.itemSize,
  15101. type: this.array.constructor.name,
  15102. array: array,
  15103. normalized: this.normalized
  15104. };
  15105. } else {
  15106. // save as true interleaved attribute
  15107. if ( data.interleavedBuffers === undefined ) {
  15108. data.interleavedBuffers = {};
  15109. }
  15110. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15111. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  15112. }
  15113. return {
  15114. isInterleavedBufferAttribute: true,
  15115. itemSize: this.itemSize,
  15116. data: this.data.uuid,
  15117. offset: this.offset,
  15118. normalized: this.normalized
  15119. };
  15120. }
  15121. }
  15122. }
  15123. let _materialId = 0;
  15124. /**
  15125. * Abstract base class for materials.
  15126. *
  15127. * Materials define the appearance of renderable 3D objects.
  15128. *
  15129. * @abstract
  15130. * @augments EventDispatcher
  15131. */
  15132. class Material extends EventDispatcher {
  15133. /**
  15134. * Constructs a new material.
  15135. */
  15136. constructor() {
  15137. super();
  15138. /**
  15139. * This flag can be used for type testing.
  15140. *
  15141. * @type {boolean}
  15142. * @readonly
  15143. * @default true
  15144. */
  15145. this.isMaterial = true;
  15146. /**
  15147. * The ID of the material.
  15148. *
  15149. * @name Material#id
  15150. * @type {number}
  15151. * @readonly
  15152. */
  15153. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  15154. /**
  15155. * The UUID of the material.
  15156. *
  15157. * @type {string}
  15158. * @readonly
  15159. */
  15160. this.uuid = generateUUID();
  15161. /**
  15162. * The name of the material.
  15163. *
  15164. * @type {string}
  15165. */
  15166. this.name = '';
  15167. /**
  15168. * The type property is used for detecting the object type
  15169. * in context of serialization/deserialization.
  15170. *
  15171. * @type {string}
  15172. * @readonly
  15173. */
  15174. this.type = 'Material';
  15175. /**
  15176. * Defines the blending type of the material.
  15177. *
  15178. * It must be set to `CustomBlending` if custom blending properties like
  15179. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  15180. * should have any effect.
  15181. *
  15182. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  15183. * @default NormalBlending
  15184. */
  15185. this.blending = NormalBlending;
  15186. /**
  15187. * Defines which side of faces will be rendered - front, back or both.
  15188. *
  15189. * @type {(FrontSide|BackSide|DoubleSide)}
  15190. * @default FrontSide
  15191. */
  15192. this.side = FrontSide;
  15193. /**
  15194. * If set to `true`, vertex colors should be used.
  15195. *
  15196. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  15197. * four (RGBA) component color buffer attribute is used.
  15198. *
  15199. * @type {boolean}
  15200. * @default false
  15201. */
  15202. this.vertexColors = false;
  15203. /**
  15204. * Defines how transparent the material is.
  15205. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  15206. *
  15207. * If the {@link Material#transparent} is not set to `true`,
  15208. * the material will remain fully opaque and this value will only affect its color.
  15209. *
  15210. * @type {number}
  15211. * @default 1
  15212. */
  15213. this.opacity = 1;
  15214. /**
  15215. * Defines whether this material is transparent. This has an effect on
  15216. * rendering as transparent objects need special treatment and are rendered
  15217. * after non-transparent objects.
  15218. *
  15219. * When set to true, the extent to which the material is transparent is
  15220. * controlled by {@link Material#opacity}.
  15221. *
  15222. * @type {boolean}
  15223. * @default false
  15224. */
  15225. this.transparent = false;
  15226. /**
  15227. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  15228. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  15229. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  15230. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  15231. *
  15232. * @type {boolean}
  15233. * @default false
  15234. */
  15235. this.alphaHash = false;
  15236. /**
  15237. * Defines the blending source factor.
  15238. *
  15239. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15240. * @default SrcAlphaFactor
  15241. */
  15242. this.blendSrc = SrcAlphaFactor;
  15243. /**
  15244. * Defines the blending destination factor.
  15245. *
  15246. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15247. * @default OneMinusSrcAlphaFactor
  15248. */
  15249. this.blendDst = OneMinusSrcAlphaFactor;
  15250. /**
  15251. * Defines the blending equation.
  15252. *
  15253. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  15254. * @default AddEquation
  15255. */
  15256. this.blendEquation = AddEquation;
  15257. /**
  15258. * Defines the blending source alpha factor.
  15259. *
  15260. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15261. * @default null
  15262. */
  15263. this.blendSrcAlpha = null;
  15264. /**
  15265. * Defines the blending destination alpha factor.
  15266. *
  15267. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15268. * @default null
  15269. */
  15270. this.blendDstAlpha = null;
  15271. /**
  15272. * Defines the blending equation of the alpha channel.
  15273. *
  15274. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  15275. * @default null
  15276. */
  15277. this.blendEquationAlpha = null;
  15278. /**
  15279. * Represents the RGB values of the constant blend color.
  15280. *
  15281. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  15282. *
  15283. * @type {Color}
  15284. * @default (0,0,0)
  15285. */
  15286. this.blendColor = new Color( 0, 0, 0 );
  15287. /**
  15288. * Represents the alpha value of the constant blend color.
  15289. *
  15290. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  15291. *
  15292. * @type {number}
  15293. * @default 0
  15294. */
  15295. this.blendAlpha = 0;
  15296. /**
  15297. * Defines the depth function.
  15298. *
  15299. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  15300. * @default LessEqualDepth
  15301. */
  15302. this.depthFunc = LessEqualDepth;
  15303. /**
  15304. * Whether to have depth test enabled when rendering this material.
  15305. * When the depth test is disabled, the depth write will also be implicitly disabled.
  15306. *
  15307. * @type {boolean}
  15308. * @default true
  15309. */
  15310. this.depthTest = true;
  15311. /**
  15312. * Whether rendering this material has any effect on the depth buffer.
  15313. *
  15314. * When drawing 2D overlays it can be useful to disable the depth writing in
  15315. * order to layer several things together without creating z-index artifacts.
  15316. *
  15317. * @type {boolean}
  15318. * @default true
  15319. */
  15320. this.depthWrite = true;
  15321. /**
  15322. * The bit mask to use when writing to the stencil buffer.
  15323. *
  15324. * @type {number}
  15325. * @default 0xff
  15326. */
  15327. this.stencilWriteMask = 0xff;
  15328. /**
  15329. * The stencil comparison function to use.
  15330. *
  15331. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  15332. * @default AlwaysStencilFunc
  15333. */
  15334. this.stencilFunc = AlwaysStencilFunc;
  15335. /**
  15336. * The value to use when performing stencil comparisons or stencil operations.
  15337. *
  15338. * @type {number}
  15339. * @default 0
  15340. */
  15341. this.stencilRef = 0;
  15342. /**
  15343. * The bit mask to use when comparing against the stencil buffer.
  15344. *
  15345. * @type {number}
  15346. * @default 0xff
  15347. */
  15348. this.stencilFuncMask = 0xff;
  15349. /**
  15350. * Which stencil operation to perform when the comparison function returns `false`.
  15351. *
  15352. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15353. * @default KeepStencilOp
  15354. */
  15355. this.stencilFail = KeepStencilOp;
  15356. /**
  15357. * Which stencil operation to perform when the comparison function returns
  15358. * `true` but the depth test fails.
  15359. *
  15360. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15361. * @default KeepStencilOp
  15362. */
  15363. this.stencilZFail = KeepStencilOp;
  15364. /**
  15365. * Which stencil operation to perform when the comparison function returns
  15366. * `true` and the depth test passes.
  15367. *
  15368. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15369. * @default KeepStencilOp
  15370. */
  15371. this.stencilZPass = KeepStencilOp;
  15372. /**
  15373. * Whether stencil operations are performed against the stencil buffer. In
  15374. * order to perform writes or comparisons against the stencil buffer this
  15375. * value must be `true`.
  15376. *
  15377. * @type {boolean}
  15378. * @default false
  15379. */
  15380. this.stencilWrite = false;
  15381. /**
  15382. * User-defined clipping planes specified as THREE.Plane objects in world
  15383. * space. These planes apply to the objects this material is attached to.
  15384. * Points in space whose signed distance to the plane is negative are clipped
  15385. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  15386. * be `true`.
  15387. *
  15388. * @type {?Array<Plane>}
  15389. * @default null
  15390. */
  15391. this.clippingPlanes = null;
  15392. /**
  15393. * Changes the behavior of clipping planes so that only their intersection is
  15394. * clipped, rather than their union.
  15395. *
  15396. * @type {boolean}
  15397. * @default false
  15398. */
  15399. this.clipIntersection = false;
  15400. /**
  15401. * Defines whether to clip shadows according to the clipping planes specified
  15402. * on this material.
  15403. *
  15404. * @type {boolean}
  15405. * @default false
  15406. */
  15407. this.clipShadows = false;
  15408. /**
  15409. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  15410. * is determined as follows:
  15411. *
  15412. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  15413. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  15414. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  15415. *
  15416. * @type {?(FrontSide|BackSide|DoubleSide)}
  15417. * @default null
  15418. */
  15419. this.shadowSide = null;
  15420. /**
  15421. * Whether to render the material's color.
  15422. *
  15423. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  15424. * objects that occlude other objects.
  15425. *
  15426. * @type {boolean}
  15427. * @default true
  15428. */
  15429. this.colorWrite = true;
  15430. /**
  15431. * Override the renderer's default precision for this material.
  15432. *
  15433. * @type {?('highp'|'mediump'|'lowp')}
  15434. * @default null
  15435. */
  15436. this.precision = null;
  15437. /**
  15438. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  15439. * be offset after it is interpolated from the depth values of the appropriate vertices.
  15440. * The offset is added before the depth test is performed and before the value is written
  15441. * into the depth buffer.
  15442. *
  15443. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  15444. * rendering solids with highlighted edges.
  15445. *
  15446. * @type {boolean}
  15447. * @default false
  15448. */
  15449. this.polygonOffset = false;
  15450. /**
  15451. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  15452. *
  15453. * @type {number}
  15454. * @default 0
  15455. */
  15456. this.polygonOffsetFactor = 0;
  15457. /**
  15458. * Is multiplied by an implementation-specific value to create a constant depth offset.
  15459. *
  15460. * @type {number}
  15461. * @default 0
  15462. */
  15463. this.polygonOffsetUnits = 0;
  15464. /**
  15465. * Whether to apply dithering to the color to remove the appearance of banding.
  15466. *
  15467. * @type {boolean}
  15468. * @default false
  15469. */
  15470. this.dithering = false;
  15471. /**
  15472. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  15473. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  15474. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  15475. *
  15476. * @type {boolean}
  15477. * @default false
  15478. */
  15479. this.alphaToCoverage = false;
  15480. /**
  15481. * Whether to premultiply the alpha (transparency) value.
  15482. *
  15483. * @type {boolean}
  15484. * @default false
  15485. */
  15486. this.premultipliedAlpha = false;
  15487. /**
  15488. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  15489. *
  15490. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  15491. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  15492. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  15493. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  15494. * disable the two pass rendering to avoid performance issues.
  15495. *
  15496. * @type {boolean}
  15497. * @default false
  15498. */
  15499. this.forceSinglePass = false;
  15500. /**
  15501. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  15502. *
  15503. * @type {boolean}
  15504. * @default true
  15505. */
  15506. this.allowOverride = true;
  15507. /**
  15508. * Defines whether 3D objects using this material are visible.
  15509. *
  15510. * @type {boolean}
  15511. * @default true
  15512. */
  15513. this.visible = true;
  15514. /**
  15515. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  15516. *
  15517. * It is ignored when rendering to a render target or using post processing or when using
  15518. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  15519. *
  15520. * @type {boolean}
  15521. * @default true
  15522. */
  15523. this.toneMapped = true;
  15524. /**
  15525. * An object that can be used to store custom data about the Material. It
  15526. * should not hold references to functions as these will not be cloned.
  15527. *
  15528. * @type {Object}
  15529. */
  15530. this.userData = {};
  15531. /**
  15532. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  15533. *
  15534. * @type {number}
  15535. * @readonly
  15536. * @default 0
  15537. */
  15538. this.version = 0;
  15539. this._alphaTest = 0;
  15540. }
  15541. /**
  15542. * Sets the alpha value to be used when running an alpha test. The material
  15543. * will not be rendered if the opacity is lower than this value.
  15544. *
  15545. * @type {number}
  15546. * @readonly
  15547. * @default 0
  15548. */
  15549. get alphaTest() {
  15550. return this._alphaTest;
  15551. }
  15552. set alphaTest( value ) {
  15553. if ( this._alphaTest > 0 !== value > 0 ) {
  15554. this.version ++;
  15555. }
  15556. this._alphaTest = value;
  15557. }
  15558. /**
  15559. * An optional callback that is executed immediately before the material is used to render a 3D object.
  15560. *
  15561. * This method can only be used when rendering with {@link WebGLRenderer}.
  15562. *
  15563. * @param {WebGLRenderer} renderer - The renderer.
  15564. * @param {Scene} scene - The scene.
  15565. * @param {Camera} camera - The camera that is used to render the scene.
  15566. * @param {BufferGeometry} geometry - The 3D object's geometry.
  15567. * @param {Object3D} object - The 3D object.
  15568. * @param {Object} group - The geometry group data.
  15569. */
  15570. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  15571. /**
  15572. * An optional callback that is executed immediately before the shader
  15573. * program is compiled. This function is called with the shader source code
  15574. * as a parameter. Useful for the modification of built-in materials.
  15575. *
  15576. * This method can only be used when rendering with {@link WebGLRenderer}. The
  15577. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  15578. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  15579. *
  15580. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  15581. * @param {WebGLRenderer} renderer - A reference to the renderer.
  15582. */
  15583. onBeforeCompile( /* shaderobject, renderer */ ) {}
  15584. /**
  15585. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  15586. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  15587. * shader or recompile the shader for this material as needed.
  15588. *
  15589. * This method can only be used when rendering with {@link WebGLRenderer}.
  15590. *
  15591. * @return {string} The custom program cache key.
  15592. */
  15593. customProgramCacheKey() {
  15594. return this.onBeforeCompile.toString();
  15595. }
  15596. /**
  15597. * This method can be used to set default values from parameter objects.
  15598. * It is a generic implementation so it can be used with different types
  15599. * of materials.
  15600. *
  15601. * @param {Object} [values] - The material values to set.
  15602. */
  15603. setValues( values ) {
  15604. if ( values === undefined ) return;
  15605. for ( const key in values ) {
  15606. const newValue = values[ key ];
  15607. if ( newValue === undefined ) {
  15608. warn( `Material: parameter '${ key }' has value of undefined.` );
  15609. continue;
  15610. }
  15611. const currentValue = this[ key ];
  15612. if ( currentValue === undefined ) {
  15613. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  15614. continue;
  15615. }
  15616. if ( currentValue && currentValue.isColor ) {
  15617. currentValue.set( newValue );
  15618. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  15619. currentValue.copy( newValue );
  15620. } else {
  15621. this[ key ] = newValue;
  15622. }
  15623. }
  15624. }
  15625. /**
  15626. * Serializes the material into JSON.
  15627. *
  15628. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  15629. * @return {Object} A JSON object representing the serialized material.
  15630. * @see {@link ObjectLoader#parse}
  15631. */
  15632. toJSON( meta ) {
  15633. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  15634. if ( isRootObject ) {
  15635. meta = {
  15636. textures: {},
  15637. images: {}
  15638. };
  15639. }
  15640. const data = {
  15641. metadata: {
  15642. version: 4.7,
  15643. type: 'Material',
  15644. generator: 'Material.toJSON'
  15645. }
  15646. };
  15647. // standard Material serialization
  15648. data.uuid = this.uuid;
  15649. data.type = this.type;
  15650. if ( this.name !== '' ) data.name = this.name;
  15651. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  15652. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  15653. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  15654. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  15655. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  15656. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  15657. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  15658. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  15659. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  15660. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  15661. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  15662. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  15663. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  15664. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  15665. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  15666. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  15667. }
  15668. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  15669. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  15670. }
  15671. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  15672. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  15673. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  15674. }
  15675. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  15676. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  15677. }
  15678. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  15679. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  15680. }
  15681. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  15682. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  15683. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  15684. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  15685. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  15686. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  15687. }
  15688. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  15689. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  15690. }
  15691. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  15692. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  15693. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  15694. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  15695. }
  15696. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  15697. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  15698. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  15699. if ( this.lightMap && this.lightMap.isTexture ) {
  15700. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  15701. data.lightMapIntensity = this.lightMapIntensity;
  15702. }
  15703. if ( this.aoMap && this.aoMap.isTexture ) {
  15704. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  15705. data.aoMapIntensity = this.aoMapIntensity;
  15706. }
  15707. if ( this.bumpMap && this.bumpMap.isTexture ) {
  15708. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  15709. data.bumpScale = this.bumpScale;
  15710. }
  15711. if ( this.normalMap && this.normalMap.isTexture ) {
  15712. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  15713. data.normalMapType = this.normalMapType;
  15714. data.normalScale = this.normalScale.toArray();
  15715. }
  15716. if ( this.displacementMap && this.displacementMap.isTexture ) {
  15717. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  15718. data.displacementScale = this.displacementScale;
  15719. data.displacementBias = this.displacementBias;
  15720. }
  15721. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  15722. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  15723. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  15724. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  15725. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  15726. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  15727. if ( this.envMap && this.envMap.isTexture ) {
  15728. data.envMap = this.envMap.toJSON( meta ).uuid;
  15729. if ( this.combine !== undefined ) data.combine = this.combine;
  15730. }
  15731. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  15732. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  15733. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  15734. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  15735. if ( this.gradientMap && this.gradientMap.isTexture ) {
  15736. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  15737. }
  15738. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  15739. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  15740. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  15741. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  15742. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  15743. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  15744. if ( this.size !== undefined ) data.size = this.size;
  15745. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  15746. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  15747. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  15748. if ( this.side !== FrontSide ) data.side = this.side;
  15749. if ( this.vertexColors === true ) data.vertexColors = true;
  15750. if ( this.opacity < 1 ) data.opacity = this.opacity;
  15751. if ( this.transparent === true ) data.transparent = true;
  15752. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  15753. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  15754. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  15755. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  15756. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  15757. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  15758. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  15759. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  15760. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  15761. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  15762. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  15763. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  15764. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  15765. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  15766. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  15767. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  15768. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  15769. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  15770. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  15771. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  15772. // rotation (SpriteMaterial)
  15773. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  15774. if ( this.polygonOffset === true ) data.polygonOffset = true;
  15775. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  15776. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  15777. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  15778. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  15779. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  15780. if ( this.scale !== undefined ) data.scale = this.scale;
  15781. if ( this.dithering === true ) data.dithering = true;
  15782. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  15783. if ( this.alphaHash === true ) data.alphaHash = true;
  15784. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  15785. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  15786. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  15787. if ( this.allowOverride === false ) data.allowOverride = false;
  15788. if ( this.wireframe === true ) data.wireframe = true;
  15789. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  15790. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  15791. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  15792. if ( this.flatShading === true ) data.flatShading = true;
  15793. if ( this.visible === false ) data.visible = false;
  15794. if ( this.toneMapped === false ) data.toneMapped = false;
  15795. if ( this.fog === false ) data.fog = false;
  15796. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15797. // TODO: Copied from Object3D.toJSON
  15798. function extractFromCache( cache ) {
  15799. const values = [];
  15800. for ( const key in cache ) {
  15801. const data = cache[ key ];
  15802. delete data.metadata;
  15803. values.push( data );
  15804. }
  15805. return values;
  15806. }
  15807. if ( isRootObject ) {
  15808. const textures = extractFromCache( meta.textures );
  15809. const images = extractFromCache( meta.images );
  15810. if ( textures.length > 0 ) data.textures = textures;
  15811. if ( images.length > 0 ) data.images = images;
  15812. }
  15813. return data;
  15814. }
  15815. /**
  15816. * Returns a new material with copied values from this instance.
  15817. *
  15818. * @return {Material} A clone of this instance.
  15819. */
  15820. clone() {
  15821. return new this.constructor().copy( this );
  15822. }
  15823. /**
  15824. * Copies the values of the given material to this instance.
  15825. *
  15826. * @param {Material} source - The material to copy.
  15827. * @return {Material} A reference to this instance.
  15828. */
  15829. copy( source ) {
  15830. this.name = source.name;
  15831. this.blending = source.blending;
  15832. this.side = source.side;
  15833. this.vertexColors = source.vertexColors;
  15834. this.opacity = source.opacity;
  15835. this.transparent = source.transparent;
  15836. this.blendSrc = source.blendSrc;
  15837. this.blendDst = source.blendDst;
  15838. this.blendEquation = source.blendEquation;
  15839. this.blendSrcAlpha = source.blendSrcAlpha;
  15840. this.blendDstAlpha = source.blendDstAlpha;
  15841. this.blendEquationAlpha = source.blendEquationAlpha;
  15842. this.blendColor.copy( source.blendColor );
  15843. this.blendAlpha = source.blendAlpha;
  15844. this.depthFunc = source.depthFunc;
  15845. this.depthTest = source.depthTest;
  15846. this.depthWrite = source.depthWrite;
  15847. this.stencilWriteMask = source.stencilWriteMask;
  15848. this.stencilFunc = source.stencilFunc;
  15849. this.stencilRef = source.stencilRef;
  15850. this.stencilFuncMask = source.stencilFuncMask;
  15851. this.stencilFail = source.stencilFail;
  15852. this.stencilZFail = source.stencilZFail;
  15853. this.stencilZPass = source.stencilZPass;
  15854. this.stencilWrite = source.stencilWrite;
  15855. const srcPlanes = source.clippingPlanes;
  15856. let dstPlanes = null;
  15857. if ( srcPlanes !== null ) {
  15858. const n = srcPlanes.length;
  15859. dstPlanes = new Array( n );
  15860. for ( let i = 0; i !== n; ++ i ) {
  15861. dstPlanes[ i ] = srcPlanes[ i ].clone();
  15862. }
  15863. }
  15864. this.clippingPlanes = dstPlanes;
  15865. this.clipIntersection = source.clipIntersection;
  15866. this.clipShadows = source.clipShadows;
  15867. this.shadowSide = source.shadowSide;
  15868. this.colorWrite = source.colorWrite;
  15869. this.precision = source.precision;
  15870. this.polygonOffset = source.polygonOffset;
  15871. this.polygonOffsetFactor = source.polygonOffsetFactor;
  15872. this.polygonOffsetUnits = source.polygonOffsetUnits;
  15873. this.dithering = source.dithering;
  15874. this.alphaTest = source.alphaTest;
  15875. this.alphaHash = source.alphaHash;
  15876. this.alphaToCoverage = source.alphaToCoverage;
  15877. this.premultipliedAlpha = source.premultipliedAlpha;
  15878. this.forceSinglePass = source.forceSinglePass;
  15879. this.allowOverride = source.allowOverride;
  15880. this.visible = source.visible;
  15881. this.toneMapped = source.toneMapped;
  15882. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  15883. return this;
  15884. }
  15885. /**
  15886. * Frees the GPU-related resources allocated by this instance. Call this
  15887. * method whenever this instance is no longer used in your app.
  15888. *
  15889. * @fires Material#dispose
  15890. */
  15891. dispose() {
  15892. /**
  15893. * Fires when the material has been disposed of.
  15894. *
  15895. * @event Material#dispose
  15896. * @type {Object}
  15897. */
  15898. this.dispatchEvent( { type: 'dispose' } );
  15899. }
  15900. /**
  15901. * Setting this property to `true` indicates the engine the material
  15902. * needs to be recompiled.
  15903. *
  15904. * @type {boolean}
  15905. * @default false
  15906. * @param {boolean} value
  15907. */
  15908. set needsUpdate( value ) {
  15909. if ( value === true ) this.version ++;
  15910. }
  15911. }
  15912. /**
  15913. * A material for rendering instances of {@link Sprite}.
  15914. *
  15915. * ```js
  15916. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  15917. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  15918. *
  15919. * const sprite = new THREE.Sprite( material );
  15920. * sprite.scale.set(200, 200, 1)
  15921. * scene.add( sprite );
  15922. * ```
  15923. *
  15924. * @augments Material
  15925. */
  15926. class SpriteMaterial extends Material {
  15927. /**
  15928. * Constructs a new sprite material.
  15929. *
  15930. * @param {Object} [parameters] - An object with one or more properties
  15931. * defining the material's appearance. Any property of the material
  15932. * (including any property from inherited materials) can be passed
  15933. * in here. Color values can be passed any type of value accepted
  15934. * by {@link Color#set}.
  15935. */
  15936. constructor( parameters ) {
  15937. super();
  15938. /**
  15939. * This flag can be used for type testing.
  15940. *
  15941. * @type {boolean}
  15942. * @readonly
  15943. * @default true
  15944. */
  15945. this.isSpriteMaterial = true;
  15946. this.type = 'SpriteMaterial';
  15947. /**
  15948. * Color of the material.
  15949. *
  15950. * @type {Color}
  15951. * @default (1,1,1)
  15952. */
  15953. this.color = new Color( 0xffffff );
  15954. /**
  15955. * The color map. May optionally include an alpha channel, typically combined
  15956. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  15957. * color is modulated by the diffuse `color`.
  15958. *
  15959. * @type {?Texture}
  15960. * @default null
  15961. */
  15962. this.map = null;
  15963. /**
  15964. * The alpha map is a grayscale texture that controls the opacity across the
  15965. * surface (black: fully transparent; white: fully opaque).
  15966. *
  15967. * Only the color of the texture is used, ignoring the alpha channel if one
  15968. * exists. For RGB and RGBA textures, the renderer will use the green channel
  15969. * when sampling this texture due to the extra bit of precision provided for
  15970. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  15971. * luminance/alpha textures will also still work as expected.
  15972. *
  15973. * @type {?Texture}
  15974. * @default null
  15975. */
  15976. this.alphaMap = null;
  15977. /**
  15978. * The rotation of the sprite in radians.
  15979. *
  15980. * @type {number}
  15981. * @default 0
  15982. */
  15983. this.rotation = 0;
  15984. /**
  15985. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  15986. *
  15987. * @type {boolean}
  15988. * @default true
  15989. */
  15990. this.sizeAttenuation = true;
  15991. /**
  15992. * Overwritten since sprite materials are transparent
  15993. * by default.
  15994. *
  15995. * @type {boolean}
  15996. * @default true
  15997. */
  15998. this.transparent = true;
  15999. /**
  16000. * Whether the material is affected by fog or not.
  16001. *
  16002. * @type {boolean}
  16003. * @default true
  16004. */
  16005. this.fog = true;
  16006. this.setValues( parameters );
  16007. }
  16008. copy( source ) {
  16009. super.copy( source );
  16010. this.color.copy( source.color );
  16011. this.map = source.map;
  16012. this.alphaMap = source.alphaMap;
  16013. this.rotation = source.rotation;
  16014. this.sizeAttenuation = source.sizeAttenuation;
  16015. this.fog = source.fog;
  16016. return this;
  16017. }
  16018. }
  16019. let _geometry;
  16020. const _intersectPoint = /*@__PURE__*/ new Vector3();
  16021. const _worldScale = /*@__PURE__*/ new Vector3();
  16022. const _mvPosition = /*@__PURE__*/ new Vector3();
  16023. const _alignedPosition = /*@__PURE__*/ new Vector2();
  16024. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  16025. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  16026. const _vA$1 = /*@__PURE__*/ new Vector3();
  16027. const _vB$1 = /*@__PURE__*/ new Vector3();
  16028. const _vC$1 = /*@__PURE__*/ new Vector3();
  16029. const _uvA = /*@__PURE__*/ new Vector2();
  16030. const _uvB = /*@__PURE__*/ new Vector2();
  16031. const _uvC = /*@__PURE__*/ new Vector2();
  16032. /**
  16033. * A sprite is a plane that always faces towards the camera, generally with a
  16034. * partially transparent texture applied.
  16035. *
  16036. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  16037. * have no effect.
  16038. *
  16039. * ```js
  16040. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  16041. * const material = new THREE.SpriteMaterial( { map: map } );
  16042. *
  16043. * const sprite = new THREE.Sprite( material );
  16044. * scene.add( sprite );
  16045. * ```
  16046. *
  16047. * @augments Object3D
  16048. */
  16049. class Sprite extends Object3D {
  16050. /**
  16051. * Constructs a new sprite.
  16052. *
  16053. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  16054. */
  16055. constructor( material = new SpriteMaterial() ) {
  16056. super();
  16057. /**
  16058. * This flag can be used for type testing.
  16059. *
  16060. * @type {boolean}
  16061. * @readonly
  16062. * @default true
  16063. */
  16064. this.isSprite = true;
  16065. this.type = 'Sprite';
  16066. if ( _geometry === undefined ) {
  16067. _geometry = new BufferGeometry();
  16068. const float32Array = new Float32Array( [
  16069. -0.5, -0.5, 0, 0, 0,
  16070. 0.5, -0.5, 0, 1, 0,
  16071. 0.5, 0.5, 0, 1, 1,
  16072. -0.5, 0.5, 0, 0, 1
  16073. ] );
  16074. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16075. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16076. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16077. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16078. }
  16079. /**
  16080. * The sprite geometry.
  16081. *
  16082. * @type {BufferGeometry}
  16083. */
  16084. this.geometry = _geometry;
  16085. /**
  16086. * The sprite material.
  16087. *
  16088. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  16089. */
  16090. this.material = material;
  16091. /**
  16092. * The sprite's anchor point, and the point around which the sprite rotates.
  16093. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  16094. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  16095. *
  16096. * @type {Vector2}
  16097. * @default (0.5,0.5)
  16098. */
  16099. this.center = new Vector2( 0.5, 0.5 );
  16100. /**
  16101. * The number of instances of this sprite.
  16102. * Can only be used with {@link WebGPURenderer}.
  16103. *
  16104. * @type {number}
  16105. * @default 1
  16106. */
  16107. this.count = 1;
  16108. }
  16109. /**
  16110. * Computes intersection points between a casted ray and this sprite.
  16111. *
  16112. * @param {Raycaster} raycaster - The raycaster.
  16113. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16114. */
  16115. raycast( raycaster, intersects ) {
  16116. if ( raycaster.camera === null ) {
  16117. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16118. }
  16119. _worldScale.setFromMatrixScale( this.matrixWorld );
  16120. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16121. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16122. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16123. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16124. _worldScale.multiplyScalar( - _mvPosition.z );
  16125. }
  16126. const rotation = this.material.rotation;
  16127. let sin, cos;
  16128. if ( rotation !== 0 ) {
  16129. cos = Math.cos( rotation );
  16130. sin = Math.sin( rotation );
  16131. }
  16132. const center = this.center;
  16133. transformVertex( _vA$1.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16134. transformVertex( _vB$1.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16135. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16136. _uvA.set( 0, 0 );
  16137. _uvB.set( 1, 0 );
  16138. _uvC.set( 1, 1 );
  16139. // check first triangle
  16140. let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  16141. if ( intersect === null ) {
  16142. // check second triangle
  16143. transformVertex( _vB$1.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16144. _uvB.set( 0, 1 );
  16145. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  16146. if ( intersect === null ) {
  16147. return;
  16148. }
  16149. }
  16150. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16151. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16152. intersects.push( {
  16153. distance: distance,
  16154. point: _intersectPoint.clone(),
  16155. uv: Triangle.getInterpolation( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA, _uvB, _uvC, new Vector2() ),
  16156. face: null,
  16157. object: this
  16158. } );
  16159. }
  16160. copy( source, recursive ) {
  16161. super.copy( source, recursive );
  16162. if ( source.center !== undefined ) this.center.copy( source.center );
  16163. this.material = source.material;
  16164. return this;
  16165. }
  16166. }
  16167. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16168. // compute position in camera space
  16169. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16170. // to check if rotation is not zero
  16171. if ( sin !== undefined ) {
  16172. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16173. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16174. } else {
  16175. _rotatedPosition.copy( _alignedPosition );
  16176. }
  16177. vertexPosition.copy( mvPosition );
  16178. vertexPosition.x += _rotatedPosition.x;
  16179. vertexPosition.y += _rotatedPosition.y;
  16180. // transform to world space
  16181. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16182. }
  16183. const _v1$2 = /*@__PURE__*/ new Vector3();
  16184. const _v2$1 = /*@__PURE__*/ new Vector3();
  16185. /**
  16186. * A component for providing a basic Level of Detail (LOD) mechanism.
  16187. *
  16188. * Every LOD level is associated with an object, and rendering can be switched
  16189. * between them at the distances specified. Typically you would create, say,
  16190. * three meshes, one for far away (low detail), one for mid range (medium
  16191. * detail) and one for close up (high detail).
  16192. *
  16193. * ```js
  16194. * const lod = new THREE.LOD();
  16195. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  16196. *
  16197. * //Create spheres with 3 levels of detail and create new LOD levels for them
  16198. * for( let i = 0; i < 3; i++ ) {
  16199. *
  16200. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  16201. * const mesh = new THREE.Mesh( geometry, material );
  16202. * lod.addLevel( mesh, i * 75 );
  16203. *
  16204. * }
  16205. *
  16206. * scene.add( lod );
  16207. * ```
  16208. *
  16209. * @augments Object3D
  16210. */
  16211. class LOD extends Object3D {
  16212. /**
  16213. * Constructs a new LOD.
  16214. */
  16215. constructor() {
  16216. super();
  16217. /**
  16218. * This flag can be used for type testing.
  16219. *
  16220. * @type {boolean}
  16221. * @readonly
  16222. * @default true
  16223. */
  16224. this.isLOD = true;
  16225. /**
  16226. * The current LOD index.
  16227. *
  16228. * @private
  16229. * @type {number}
  16230. * @default 0
  16231. */
  16232. this._currentLevel = 0;
  16233. this.type = 'LOD';
  16234. Object.defineProperties( this, {
  16235. /**
  16236. * This array holds the LOD levels.
  16237. *
  16238. * @name LOD#levels
  16239. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  16240. */
  16241. levels: {
  16242. enumerable: true,
  16243. value: []
  16244. }
  16245. } );
  16246. /**
  16247. * Whether the LOD object is updated automatically by the renderer per frame
  16248. * or not. If set to `false`, you have to call {@link LOD#update} in the
  16249. * render loop by yourself.
  16250. *
  16251. * @type {boolean}
  16252. * @default true
  16253. */
  16254. this.autoUpdate = true;
  16255. }
  16256. copy( source ) {
  16257. super.copy( source, false );
  16258. const levels = source.levels;
  16259. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16260. const level = levels[ i ];
  16261. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  16262. }
  16263. this.autoUpdate = source.autoUpdate;
  16264. return this;
  16265. }
  16266. /**
  16267. * Adds a mesh that will display at a certain distance and greater. Typically
  16268. * the further away the distance, the lower the detail on the mesh.
  16269. *
  16270. * @param {Object3D} object - The 3D object to display at this level.
  16271. * @param {number} [distance=0] - The distance at which to display this level of detail.
  16272. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  16273. * @return {LOD} A reference to this instance.
  16274. */
  16275. addLevel( object, distance = 0, hysteresis = 0 ) {
  16276. distance = Math.abs( distance );
  16277. const levels = this.levels;
  16278. let l;
  16279. for ( l = 0; l < levels.length; l ++ ) {
  16280. if ( distance < levels[ l ].distance ) {
  16281. break;
  16282. }
  16283. }
  16284. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  16285. this.add( object );
  16286. return this;
  16287. }
  16288. /**
  16289. * Removes an existing level, based on the distance from the camera.
  16290. * Returns `true` when the level has been removed. Otherwise `false`.
  16291. *
  16292. * @param {number} distance - Distance of the level to remove.
  16293. * @return {boolean} Whether the level has been removed or not.
  16294. */
  16295. removeLevel( distance ) {
  16296. const levels = this.levels;
  16297. for ( let i = 0; i < levels.length; i ++ ) {
  16298. if ( levels[ i ].distance === distance ) {
  16299. const removedElements = levels.splice( i, 1 );
  16300. this.remove( removedElements[ 0 ].object );
  16301. return true;
  16302. }
  16303. }
  16304. return false;
  16305. }
  16306. /**
  16307. * Returns the currently active LOD level index.
  16308. *
  16309. * @return {number} The current active LOD level index.
  16310. */
  16311. getCurrentLevel() {
  16312. return this._currentLevel;
  16313. }
  16314. /**
  16315. * Returns a reference to the first 3D object that is greater than
  16316. * the given distance.
  16317. *
  16318. * @param {number} distance - The LOD distance.
  16319. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  16320. */
  16321. getObjectForDistance( distance ) {
  16322. const levels = this.levels;
  16323. if ( levels.length > 0 ) {
  16324. let i, l;
  16325. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16326. let levelDistance = levels[ i ].distance;
  16327. if ( levels[ i ].object.visible ) {
  16328. levelDistance -= levelDistance * levels[ i ].hysteresis;
  16329. }
  16330. if ( distance < levelDistance ) {
  16331. break;
  16332. }
  16333. }
  16334. return levels[ i - 1 ].object;
  16335. }
  16336. return null;
  16337. }
  16338. /**
  16339. * Computes intersection points between a casted ray and this LOD.
  16340. *
  16341. * @param {Raycaster} raycaster - The raycaster.
  16342. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16343. */
  16344. raycast( raycaster, intersects ) {
  16345. const levels = this.levels;
  16346. if ( levels.length > 0 ) {
  16347. _v1$2.setFromMatrixPosition( this.matrixWorld );
  16348. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  16349. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16350. }
  16351. }
  16352. /**
  16353. * Updates the LOD by computing which LOD level should be visible according
  16354. * to the current distance of the given camera.
  16355. *
  16356. * @param {Camera} camera - The camera the scene is rendered with.
  16357. */
  16358. update( camera ) {
  16359. const levels = this.levels;
  16360. if ( levels.length > 1 ) {
  16361. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  16362. _v2$1.setFromMatrixPosition( this.matrixWorld );
  16363. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  16364. levels[ 0 ].object.visible = true;
  16365. let i, l;
  16366. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16367. let levelDistance = levels[ i ].distance;
  16368. if ( levels[ i ].object.visible ) {
  16369. levelDistance -= levelDistance * levels[ i ].hysteresis;
  16370. }
  16371. if ( distance >= levelDistance ) {
  16372. levels[ i - 1 ].object.visible = false;
  16373. levels[ i ].object.visible = true;
  16374. } else {
  16375. break;
  16376. }
  16377. }
  16378. this._currentLevel = i - 1;
  16379. for ( ; i < l; i ++ ) {
  16380. levels[ i ].object.visible = false;
  16381. }
  16382. }
  16383. }
  16384. toJSON( meta ) {
  16385. const data = super.toJSON( meta );
  16386. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  16387. data.object.levels = [];
  16388. const levels = this.levels;
  16389. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16390. const level = levels[ i ];
  16391. data.object.levels.push( {
  16392. object: level.object.uuid,
  16393. distance: level.distance,
  16394. hysteresis: level.hysteresis
  16395. } );
  16396. }
  16397. return data;
  16398. }
  16399. }
  16400. const _vector$7 = /*@__PURE__*/ new Vector3();
  16401. const _segCenter = /*@__PURE__*/ new Vector3();
  16402. const _segDir = /*@__PURE__*/ new Vector3();
  16403. const _diff = /*@__PURE__*/ new Vector3();
  16404. const _edge1 = /*@__PURE__*/ new Vector3();
  16405. const _edge2 = /*@__PURE__*/ new Vector3();
  16406. const _normal$1 = /*@__PURE__*/ new Vector3();
  16407. /**
  16408. * A ray that emits from an origin in a certain direction. The class is used by
  16409. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  16410. * mouse picking (working out what objects in the 3D space the mouse is over)
  16411. * amongst other things.
  16412. */
  16413. class Ray {
  16414. /**
  16415. * Constructs a new ray.
  16416. *
  16417. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  16418. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  16419. */
  16420. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  16421. /**
  16422. * The origin of the ray.
  16423. *
  16424. * @type {Vector3}
  16425. */
  16426. this.origin = origin;
  16427. /**
  16428. * The (normalized) direction of the ray.
  16429. *
  16430. * @type {Vector3}
  16431. */
  16432. this.direction = direction;
  16433. }
  16434. /**
  16435. * Sets the ray's components by copying the given values.
  16436. *
  16437. * @param {Vector3} origin - The origin.
  16438. * @param {Vector3} direction - The direction.
  16439. * @return {Ray} A reference to this ray.
  16440. */
  16441. set( origin, direction ) {
  16442. this.origin.copy( origin );
  16443. this.direction.copy( direction );
  16444. return this;
  16445. }
  16446. /**
  16447. * Copies the values of the given ray to this instance.
  16448. *
  16449. * @param {Ray} ray - The ray to copy.
  16450. * @return {Ray} A reference to this ray.
  16451. */
  16452. copy( ray ) {
  16453. this.origin.copy( ray.origin );
  16454. this.direction.copy( ray.direction );
  16455. return this;
  16456. }
  16457. /**
  16458. * Returns a vector that is located at a given distance along this ray.
  16459. *
  16460. * @param {number} t - The distance along the ray to retrieve a position for.
  16461. * @param {Vector3} target - The target vector that is used to store the method's result.
  16462. * @return {Vector3} A position on the ray.
  16463. */
  16464. at( t, target ) {
  16465. return target.copy( this.origin ).addScaledVector( this.direction, t );
  16466. }
  16467. /**
  16468. * Adjusts the direction of the ray to point at the given vector in world space.
  16469. *
  16470. * @param {Vector3} v - The target position.
  16471. * @return {Ray} A reference to this ray.
  16472. */
  16473. lookAt( v ) {
  16474. this.direction.copy( v ).sub( this.origin ).normalize();
  16475. return this;
  16476. }
  16477. /**
  16478. * Shift the origin of this ray along its direction by the given distance.
  16479. *
  16480. * @param {number} t - The distance along the ray to interpolate.
  16481. * @return {Ray} A reference to this ray.
  16482. */
  16483. recast( t ) {
  16484. this.origin.copy( this.at( t, _vector$7 ) );
  16485. return this;
  16486. }
  16487. /**
  16488. * Returns the point along this ray that is closest to the given point.
  16489. *
  16490. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  16491. * @param {Vector3} target - The target vector that is used to store the method's result.
  16492. * @return {Vector3} The closest point on this ray.
  16493. */
  16494. closestPointToPoint( point, target ) {
  16495. target.subVectors( point, this.origin );
  16496. const directionDistance = target.dot( this.direction );
  16497. if ( directionDistance < 0 ) {
  16498. return target.copy( this.origin );
  16499. }
  16500. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16501. }
  16502. /**
  16503. * Returns the distance of the closest approach between this ray and the given point.
  16504. *
  16505. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16506. * @return {number} The distance.
  16507. */
  16508. distanceToPoint( point ) {
  16509. return Math.sqrt( this.distanceSqToPoint( point ) );
  16510. }
  16511. /**
  16512. * Returns the squared distance of the closest approach between this ray and the given point.
  16513. *
  16514. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16515. * @return {number} The squared distance.
  16516. */
  16517. distanceSqToPoint( point ) {
  16518. const directionDistance = _vector$7.subVectors( point, this.origin ).dot( this.direction );
  16519. // point behind the ray
  16520. if ( directionDistance < 0 ) {
  16521. return this.origin.distanceToSquared( point );
  16522. }
  16523. _vector$7.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16524. return _vector$7.distanceToSquared( point );
  16525. }
  16526. /**
  16527. * Returns the squared distance between this ray and the given line segment.
  16528. *
  16529. * @param {Vector3} v0 - The start point of the line segment.
  16530. * @param {Vector3} v1 - The end point of the line segment.
  16531. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  16532. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  16533. * @return {number} The squared distance.
  16534. */
  16535. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  16536. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  16537. // It returns the min distance between the ray and the segment
  16538. // defined by v0 and v1
  16539. // It can also set two optional targets :
  16540. // - The closest point on the ray
  16541. // - The closest point on the segment
  16542. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  16543. _segDir.copy( v1 ).sub( v0 ).normalize();
  16544. _diff.copy( this.origin ).sub( _segCenter );
  16545. const segExtent = v0.distanceTo( v1 ) * 0.5;
  16546. const a01 = - this.direction.dot( _segDir );
  16547. const b0 = _diff.dot( this.direction );
  16548. const b1 = - _diff.dot( _segDir );
  16549. const c = _diff.lengthSq();
  16550. const det = Math.abs( 1 - a01 * a01 );
  16551. let s0, s1, sqrDist, extDet;
  16552. if ( det > 0 ) {
  16553. // The ray and segment are not parallel.
  16554. s0 = a01 * b1 - b0;
  16555. s1 = a01 * b0 - b1;
  16556. extDet = segExtent * det;
  16557. if ( s0 >= 0 ) {
  16558. if ( s1 >= - extDet ) {
  16559. if ( s1 <= extDet ) {
  16560. // region 0
  16561. // Minimum at interior points of ray and segment.
  16562. const invDet = 1 / det;
  16563. s0 *= invDet;
  16564. s1 *= invDet;
  16565. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  16566. } else {
  16567. // region 1
  16568. s1 = segExtent;
  16569. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16570. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16571. }
  16572. } else {
  16573. // region 5
  16574. s1 = - segExtent;
  16575. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16576. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16577. }
  16578. } else {
  16579. if ( s1 <= - extDet ) {
  16580. // region 4
  16581. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  16582. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16583. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16584. } else if ( s1 <= extDet ) {
  16585. // region 3
  16586. s0 = 0;
  16587. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16588. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  16589. } else {
  16590. // region 2
  16591. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  16592. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16593. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16594. }
  16595. }
  16596. } else {
  16597. // Ray and segment are parallel.
  16598. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  16599. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16600. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16601. }
  16602. if ( optionalPointOnRay ) {
  16603. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  16604. }
  16605. if ( optionalPointOnSegment ) {
  16606. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  16607. }
  16608. return sqrDist;
  16609. }
  16610. /**
  16611. * Intersects this ray with the given sphere, returning the intersection
  16612. * point or `null` if there is no intersection.
  16613. *
  16614. * @param {Sphere} sphere - The sphere to intersect.
  16615. * @param {Vector3} target - The target vector that is used to store the method's result.
  16616. * @return {?Vector3} The intersection point.
  16617. */
  16618. intersectSphere( sphere, target ) {
  16619. _vector$7.subVectors( sphere.center, this.origin );
  16620. const tca = _vector$7.dot( this.direction );
  16621. const d2 = _vector$7.dot( _vector$7 ) - tca * tca;
  16622. const radius2 = sphere.radius * sphere.radius;
  16623. if ( d2 > radius2 ) return null;
  16624. const thc = Math.sqrt( radius2 - d2 );
  16625. // t0 = first intersect point - entrance on front of sphere
  16626. const t0 = tca - thc;
  16627. // t1 = second intersect point - exit point on back of sphere
  16628. const t1 = tca + thc;
  16629. // test to see if t1 is behind the ray - if so, return null
  16630. if ( t1 < 0 ) return null;
  16631. // test to see if t0 is behind the ray:
  16632. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  16633. // in order to always return an intersect point that is in front of the ray.
  16634. if ( t0 < 0 ) return this.at( t1, target );
  16635. // else t0 is in front of the ray, so return the first collision point scaled by t0
  16636. return this.at( t0, target );
  16637. }
  16638. /**
  16639. * Returns `true` if this ray intersects with the given sphere.
  16640. *
  16641. * @param {Sphere} sphere - The sphere to intersect.
  16642. * @return {boolean} Whether this ray intersects with the given sphere or not.
  16643. */
  16644. intersectsSphere( sphere ) {
  16645. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  16646. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  16647. }
  16648. /**
  16649. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  16650. * does not intersect with the plane.
  16651. *
  16652. * @param {Plane} plane - The plane to compute the distance to.
  16653. * @return {?number} Whether this ray intersects with the given sphere or not.
  16654. */
  16655. distanceToPlane( plane ) {
  16656. const denominator = plane.normal.dot( this.direction );
  16657. if ( denominator === 0 ) {
  16658. // line is coplanar, return origin
  16659. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  16660. return 0;
  16661. }
  16662. // Null is preferable to undefined since undefined means.... it is undefined
  16663. return null;
  16664. }
  16665. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  16666. // Return if the ray never intersects the plane
  16667. return t >= 0 ? t : null;
  16668. }
  16669. /**
  16670. * Intersects this ray with the given plane, returning the intersection
  16671. * point or `null` if there is no intersection.
  16672. *
  16673. * @param {Plane} plane - The plane to intersect.
  16674. * @param {Vector3} target - The target vector that is used to store the method's result.
  16675. * @return {?Vector3} The intersection point.
  16676. */
  16677. intersectPlane( plane, target ) {
  16678. const t = this.distanceToPlane( plane );
  16679. if ( t === null ) {
  16680. return null;
  16681. }
  16682. return this.at( t, target );
  16683. }
  16684. /**
  16685. * Returns `true` if this ray intersects with the given plane.
  16686. *
  16687. * @param {Plane} plane - The plane to intersect.
  16688. * @return {boolean} Whether this ray intersects with the given plane or not.
  16689. */
  16690. intersectsPlane( plane ) {
  16691. // check if the ray lies on the plane first
  16692. const distToPoint = plane.distanceToPoint( this.origin );
  16693. if ( distToPoint === 0 ) {
  16694. return true;
  16695. }
  16696. const denominator = plane.normal.dot( this.direction );
  16697. if ( denominator * distToPoint < 0 ) {
  16698. return true;
  16699. }
  16700. // ray origin is behind the plane (and is pointing behind it)
  16701. return false;
  16702. }
  16703. /**
  16704. * Intersects this ray with the given bounding box, returning the intersection
  16705. * point or `null` if there is no intersection.
  16706. *
  16707. * @param {Box3} box - The box to intersect.
  16708. * @param {Vector3} target - The target vector that is used to store the method's result.
  16709. * @return {?Vector3} The intersection point.
  16710. */
  16711. intersectBox( box, target ) {
  16712. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  16713. const invdirx = 1 / this.direction.x,
  16714. invdiry = 1 / this.direction.y,
  16715. invdirz = 1 / this.direction.z;
  16716. const origin = this.origin;
  16717. if ( invdirx >= 0 ) {
  16718. tmin = ( box.min.x - origin.x ) * invdirx;
  16719. tmax = ( box.max.x - origin.x ) * invdirx;
  16720. } else {
  16721. tmin = ( box.max.x - origin.x ) * invdirx;
  16722. tmax = ( box.min.x - origin.x ) * invdirx;
  16723. }
  16724. if ( invdiry >= 0 ) {
  16725. tymin = ( box.min.y - origin.y ) * invdiry;
  16726. tymax = ( box.max.y - origin.y ) * invdiry;
  16727. } else {
  16728. tymin = ( box.max.y - origin.y ) * invdiry;
  16729. tymax = ( box.min.y - origin.y ) * invdiry;
  16730. }
  16731. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  16732. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  16733. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  16734. if ( invdirz >= 0 ) {
  16735. tzmin = ( box.min.z - origin.z ) * invdirz;
  16736. tzmax = ( box.max.z - origin.z ) * invdirz;
  16737. } else {
  16738. tzmin = ( box.max.z - origin.z ) * invdirz;
  16739. tzmax = ( box.min.z - origin.z ) * invdirz;
  16740. }
  16741. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  16742. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  16743. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  16744. //return point closest to the ray (positive side)
  16745. if ( tmax < 0 ) return null;
  16746. return this.at( tmin >= 0 ? tmin : tmax, target );
  16747. }
  16748. /**
  16749. * Returns `true` if this ray intersects with the given box.
  16750. *
  16751. * @param {Box3} box - The box to intersect.
  16752. * @return {boolean} Whether this ray intersects with the given box or not.
  16753. */
  16754. intersectsBox( box ) {
  16755. return this.intersectBox( box, _vector$7 ) !== null;
  16756. }
  16757. /**
  16758. * Intersects this ray with the given triangle, returning the intersection
  16759. * point or `null` if there is no intersection.
  16760. *
  16761. * @param {Vector3} a - The first vertex of the triangle.
  16762. * @param {Vector3} b - The second vertex of the triangle.
  16763. * @param {Vector3} c - The third vertex of the triangle.
  16764. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  16765. * @param {Vector3} target - The target vector that is used to store the method's result.
  16766. * @return {?Vector3} The intersection point.
  16767. */
  16768. intersectTriangle( a, b, c, backfaceCulling, target ) {
  16769. // Compute the offset origin, edges, and normal.
  16770. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  16771. _edge1.subVectors( b, a );
  16772. _edge2.subVectors( c, a );
  16773. _normal$1.crossVectors( _edge1, _edge2 );
  16774. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  16775. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  16776. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  16777. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  16778. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  16779. let DdN = this.direction.dot( _normal$1 );
  16780. let sign;
  16781. if ( DdN > 0 ) {
  16782. if ( backfaceCulling ) return null;
  16783. sign = 1;
  16784. } else if ( DdN < 0 ) {
  16785. sign = -1;
  16786. DdN = - DdN;
  16787. } else {
  16788. return null;
  16789. }
  16790. _diff.subVectors( this.origin, a );
  16791. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  16792. // b1 < 0, no intersection
  16793. if ( DdQxE2 < 0 ) {
  16794. return null;
  16795. }
  16796. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  16797. // b2 < 0, no intersection
  16798. if ( DdE1xQ < 0 ) {
  16799. return null;
  16800. }
  16801. // b1+b2 > 1, no intersection
  16802. if ( DdQxE2 + DdE1xQ > DdN ) {
  16803. return null;
  16804. }
  16805. // Line intersects triangle, check if ray does.
  16806. const QdN = - sign * _diff.dot( _normal$1 );
  16807. // t < 0, no intersection
  16808. if ( QdN < 0 ) {
  16809. return null;
  16810. }
  16811. // Ray intersects triangle.
  16812. return this.at( QdN / DdN, target );
  16813. }
  16814. /**
  16815. * Transforms this ray with the given 4x4 transformation matrix.
  16816. *
  16817. * @param {Matrix4} matrix4 - The transformation matrix.
  16818. * @return {Ray} A reference to this ray.
  16819. */
  16820. applyMatrix4( matrix4 ) {
  16821. this.origin.applyMatrix4( matrix4 );
  16822. this.direction.transformDirection( matrix4 );
  16823. return this;
  16824. }
  16825. /**
  16826. * Returns `true` if this ray is equal with the given one.
  16827. *
  16828. * @param {Ray} ray - The ray to test for equality.
  16829. * @return {boolean} Whether this ray is equal with the given one.
  16830. */
  16831. equals( ray ) {
  16832. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  16833. }
  16834. /**
  16835. * Returns a new ray with copied values from this instance.
  16836. *
  16837. * @return {Ray} A clone of this instance.
  16838. */
  16839. clone() {
  16840. return new this.constructor().copy( this );
  16841. }
  16842. }
  16843. /**
  16844. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  16845. *
  16846. * This material is not affected by lights.
  16847. *
  16848. * @augments Material
  16849. * @demo scenes/material-browser.html#MeshBasicMaterial
  16850. */
  16851. class MeshBasicMaterial extends Material {
  16852. /**
  16853. * Constructs a new mesh basic material.
  16854. *
  16855. * @param {Object} [parameters] - An object with one or more properties
  16856. * defining the material's appearance. Any property of the material
  16857. * (including any property from inherited materials) can be passed
  16858. * in here. Color values can be passed any type of value accepted
  16859. * by {@link Color#set}.
  16860. */
  16861. constructor( parameters ) {
  16862. super();
  16863. /**
  16864. * This flag can be used for type testing.
  16865. *
  16866. * @type {boolean}
  16867. * @readonly
  16868. * @default true
  16869. */
  16870. this.isMeshBasicMaterial = true;
  16871. this.type = 'MeshBasicMaterial';
  16872. /**
  16873. * Color of the material.
  16874. *
  16875. * @type {Color}
  16876. * @default (1,1,1)
  16877. */
  16878. this.color = new Color( 0xffffff ); // diffuse
  16879. /**
  16880. * The color map. May optionally include an alpha channel, typically combined
  16881. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  16882. * color is modulated by the diffuse `color`.
  16883. *
  16884. * @type {?Texture}
  16885. * @default null
  16886. */
  16887. this.map = null;
  16888. /**
  16889. * The light map. Requires a second set of UVs.
  16890. *
  16891. * @type {?Texture}
  16892. * @default null
  16893. */
  16894. this.lightMap = null;
  16895. /**
  16896. * Intensity of the baked light.
  16897. *
  16898. * @type {number}
  16899. * @default 1
  16900. */
  16901. this.lightMapIntensity = 1.0;
  16902. /**
  16903. * The red channel of this texture is used as the ambient occlusion map.
  16904. * Requires a second set of UVs.
  16905. *
  16906. * @type {?Texture}
  16907. * @default null
  16908. */
  16909. this.aoMap = null;
  16910. /**
  16911. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  16912. * disables ambient occlusion. Where intensity is `1` and the AO map's
  16913. * red channel is also `1`, ambient light is fully occluded on a surface.
  16914. *
  16915. * @type {number}
  16916. * @default 1
  16917. */
  16918. this.aoMapIntensity = 1.0;
  16919. /**
  16920. * Specular map used by the material.
  16921. *
  16922. * @type {?Texture}
  16923. * @default null
  16924. */
  16925. this.specularMap = null;
  16926. /**
  16927. * The alpha map is a grayscale texture that controls the opacity across the
  16928. * surface (black: fully transparent; white: fully opaque).
  16929. *
  16930. * Only the color of the texture is used, ignoring the alpha channel if one
  16931. * exists. For RGB and RGBA textures, the renderer will use the green channel
  16932. * when sampling this texture due to the extra bit of precision provided for
  16933. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  16934. * luminance/alpha textures will also still work as expected.
  16935. *
  16936. * @type {?Texture}
  16937. * @default null
  16938. */
  16939. this.alphaMap = null;
  16940. /**
  16941. * The environment map.
  16942. *
  16943. * @type {?Texture}
  16944. * @default null
  16945. */
  16946. this.envMap = null;
  16947. /**
  16948. * The rotation of the environment map in radians.
  16949. *
  16950. * @type {Euler}
  16951. * @default (0,0,0)
  16952. */
  16953. this.envMapRotation = new Euler();
  16954. /**
  16955. * How to combine the result of the surface's color with the environment map, if any.
  16956. *
  16957. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  16958. * blend between the two colors.
  16959. *
  16960. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  16961. * @default MultiplyOperation
  16962. */
  16963. this.combine = MultiplyOperation;
  16964. /**
  16965. * How much the environment map affects the surface.
  16966. * The valid range is between `0` (no reflections) and `1` (full reflections).
  16967. *
  16968. * @type {number}
  16969. * @default 1
  16970. */
  16971. this.reflectivity = 1;
  16972. /**
  16973. * The index of refraction (IOR) of air (approximately 1) divided by the
  16974. * index of refraction of the material. It is used with environment mapping
  16975. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  16976. * The refraction ratio should not exceed `1`.
  16977. *
  16978. * @type {number}
  16979. * @default 0.98
  16980. */
  16981. this.refractionRatio = 0.98;
  16982. /**
  16983. * Renders the geometry as a wireframe.
  16984. *
  16985. * @type {boolean}
  16986. * @default false
  16987. */
  16988. this.wireframe = false;
  16989. /**
  16990. * Controls the thickness of the wireframe.
  16991. *
  16992. * Can only be used with {@link SVGRenderer}.
  16993. *
  16994. * @type {number}
  16995. * @default 1
  16996. */
  16997. this.wireframeLinewidth = 1;
  16998. /**
  16999. * Defines appearance of wireframe ends.
  17000. *
  17001. * Can only be used with {@link SVGRenderer}.
  17002. *
  17003. * @type {('round'|'bevel'|'miter')}
  17004. * @default 'round'
  17005. */
  17006. this.wireframeLinecap = 'round';
  17007. /**
  17008. * Defines appearance of wireframe joints.
  17009. *
  17010. * Can only be used with {@link SVGRenderer}.
  17011. *
  17012. * @type {('round'|'bevel'|'miter')}
  17013. * @default 'round'
  17014. */
  17015. this.wireframeLinejoin = 'round';
  17016. /**
  17017. * Whether the material is affected by fog or not.
  17018. *
  17019. * @type {boolean}
  17020. * @default true
  17021. */
  17022. this.fog = true;
  17023. this.setValues( parameters );
  17024. }
  17025. copy( source ) {
  17026. super.copy( source );
  17027. this.color.copy( source.color );
  17028. this.map = source.map;
  17029. this.lightMap = source.lightMap;
  17030. this.lightMapIntensity = source.lightMapIntensity;
  17031. this.aoMap = source.aoMap;
  17032. this.aoMapIntensity = source.aoMapIntensity;
  17033. this.specularMap = source.specularMap;
  17034. this.alphaMap = source.alphaMap;
  17035. this.envMap = source.envMap;
  17036. this.envMapRotation.copy( source.envMapRotation );
  17037. this.combine = source.combine;
  17038. this.reflectivity = source.reflectivity;
  17039. this.refractionRatio = source.refractionRatio;
  17040. this.wireframe = source.wireframe;
  17041. this.wireframeLinewidth = source.wireframeLinewidth;
  17042. this.wireframeLinecap = source.wireframeLinecap;
  17043. this.wireframeLinejoin = source.wireframeLinejoin;
  17044. this.fog = source.fog;
  17045. return this;
  17046. }
  17047. }
  17048. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  17049. const _ray$3 = /*@__PURE__*/ new Ray();
  17050. const _sphere$6 = /*@__PURE__*/ new Sphere();
  17051. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  17052. const _vA = /*@__PURE__*/ new Vector3();
  17053. const _vB = /*@__PURE__*/ new Vector3();
  17054. const _vC = /*@__PURE__*/ new Vector3();
  17055. const _tempA = /*@__PURE__*/ new Vector3();
  17056. const _morphA = /*@__PURE__*/ new Vector3();
  17057. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  17058. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  17059. /**
  17060. * Class representing triangular polygon mesh based objects.
  17061. *
  17062. * ```js
  17063. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  17064. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  17065. * const mesh = new THREE.Mesh( geometry, material );
  17066. * scene.add( mesh );
  17067. * ```
  17068. *
  17069. * @augments Object3D
  17070. */
  17071. class Mesh extends Object3D {
  17072. /**
  17073. * Constructs a new mesh.
  17074. *
  17075. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17076. * @param {Material|Array<Material>} [material] - The mesh material.
  17077. */
  17078. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  17079. super();
  17080. /**
  17081. * This flag can be used for type testing.
  17082. *
  17083. * @type {boolean}
  17084. * @readonly
  17085. * @default true
  17086. */
  17087. this.isMesh = true;
  17088. this.type = 'Mesh';
  17089. /**
  17090. * The mesh geometry.
  17091. *
  17092. * @type {BufferGeometry}
  17093. */
  17094. this.geometry = geometry;
  17095. /**
  17096. * The mesh material.
  17097. *
  17098. * @type {Material|Array<Material>}
  17099. * @default MeshBasicMaterial
  17100. */
  17101. this.material = material;
  17102. /**
  17103. * A dictionary representing the morph targets in the geometry. The key is the
  17104. * morph targets name, the value its attribute index. This member is `undefined`
  17105. * by default and only set when morph targets are detected in the geometry.
  17106. *
  17107. * @type {Object<string,number>|undefined}
  17108. * @default undefined
  17109. */
  17110. this.morphTargetDictionary = undefined;
  17111. /**
  17112. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  17113. * is applied. This member is `undefined` by default and only set when morph targets are
  17114. * detected in the geometry.
  17115. *
  17116. * @type {Array<number>|undefined}
  17117. * @default undefined
  17118. */
  17119. this.morphTargetInfluences = undefined;
  17120. /**
  17121. * The number of instances of this mesh.
  17122. * Can only be used with {@link WebGPURenderer}.
  17123. *
  17124. * @type {number}
  17125. * @default 1
  17126. */
  17127. this.count = 1;
  17128. this.updateMorphTargets();
  17129. }
  17130. copy( source, recursive ) {
  17131. super.copy( source, recursive );
  17132. if ( source.morphTargetInfluences !== undefined ) {
  17133. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  17134. }
  17135. if ( source.morphTargetDictionary !== undefined ) {
  17136. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  17137. }
  17138. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  17139. this.geometry = source.geometry;
  17140. return this;
  17141. }
  17142. /**
  17143. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  17144. * to make sure existing morph targets can influence this 3D object.
  17145. */
  17146. updateMorphTargets() {
  17147. const geometry = this.geometry;
  17148. const morphAttributes = geometry.morphAttributes;
  17149. const keys = Object.keys( morphAttributes );
  17150. if ( keys.length > 0 ) {
  17151. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17152. if ( morphAttribute !== undefined ) {
  17153. this.morphTargetInfluences = [];
  17154. this.morphTargetDictionary = {};
  17155. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17156. const name = morphAttribute[ m ].name || String( m );
  17157. this.morphTargetInfluences.push( 0 );
  17158. this.morphTargetDictionary[ name ] = m;
  17159. }
  17160. }
  17161. }
  17162. }
  17163. /**
  17164. * Returns the local-space position of the vertex at the given index, taking into
  17165. * account the current animation state of both morph targets and skinning.
  17166. *
  17167. * @param {number} index - The vertex index.
  17168. * @param {Vector3} target - The target object that is used to store the method's result.
  17169. * @return {Vector3} The vertex position in local space.
  17170. */
  17171. getVertexPosition( index, target ) {
  17172. const geometry = this.geometry;
  17173. const position = geometry.attributes.position;
  17174. const morphPosition = geometry.morphAttributes.position;
  17175. const morphTargetsRelative = geometry.morphTargetsRelative;
  17176. target.fromBufferAttribute( position, index );
  17177. const morphInfluences = this.morphTargetInfluences;
  17178. if ( morphPosition && morphInfluences ) {
  17179. _morphA.set( 0, 0, 0 );
  17180. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  17181. const influence = morphInfluences[ i ];
  17182. const morphAttribute = morphPosition[ i ];
  17183. if ( influence === 0 ) continue;
  17184. _tempA.fromBufferAttribute( morphAttribute, index );
  17185. if ( morphTargetsRelative ) {
  17186. _morphA.addScaledVector( _tempA, influence );
  17187. } else {
  17188. _morphA.addScaledVector( _tempA.sub( target ), influence );
  17189. }
  17190. }
  17191. target.add( _morphA );
  17192. }
  17193. return target;
  17194. }
  17195. /**
  17196. * Computes intersection points between a casted ray and this line.
  17197. *
  17198. * @param {Raycaster} raycaster - The raycaster.
  17199. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17200. */
  17201. raycast( raycaster, intersects ) {
  17202. const geometry = this.geometry;
  17203. const material = this.material;
  17204. const matrixWorld = this.matrixWorld;
  17205. if ( material === undefined ) return;
  17206. // test with bounding sphere in world space
  17207. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17208. _sphere$6.copy( geometry.boundingSphere );
  17209. _sphere$6.applyMatrix4( matrixWorld );
  17210. // check distance from ray origin to bounding sphere
  17211. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  17212. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  17213. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  17214. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  17215. }
  17216. // convert ray to local space of mesh
  17217. _inverseMatrix$3.copy( matrixWorld ).invert();
  17218. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  17219. // test with bounding box in local space
  17220. if ( geometry.boundingBox !== null ) {
  17221. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  17222. }
  17223. // test for intersections with geometry
  17224. this._computeIntersections( raycaster, intersects, _ray$3 );
  17225. }
  17226. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  17227. let intersection;
  17228. const geometry = this.geometry;
  17229. const material = this.material;
  17230. const index = geometry.index;
  17231. const position = geometry.attributes.position;
  17232. const uv = geometry.attributes.uv;
  17233. const uv1 = geometry.attributes.uv1;
  17234. const normal = geometry.attributes.normal;
  17235. const groups = geometry.groups;
  17236. const drawRange = geometry.drawRange;
  17237. if ( index !== null ) {
  17238. // indexed buffer geometry
  17239. if ( Array.isArray( material ) ) {
  17240. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17241. const group = groups[ i ];
  17242. const groupMaterial = material[ group.materialIndex ];
  17243. const start = Math.max( group.start, drawRange.start );
  17244. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17245. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17246. const a = index.getX( j );
  17247. const b = index.getX( j + 1 );
  17248. const c = index.getX( j + 2 );
  17249. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17250. if ( intersection ) {
  17251. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  17252. intersection.face.materialIndex = group.materialIndex;
  17253. intersects.push( intersection );
  17254. }
  17255. }
  17256. }
  17257. } else {
  17258. const start = Math.max( 0, drawRange.start );
  17259. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17260. for ( let i = start, il = end; i < il; i += 3 ) {
  17261. const a = index.getX( i );
  17262. const b = index.getX( i + 1 );
  17263. const c = index.getX( i + 2 );
  17264. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17265. if ( intersection ) {
  17266. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  17267. intersects.push( intersection );
  17268. }
  17269. }
  17270. }
  17271. } else if ( position !== undefined ) {
  17272. // non-indexed buffer geometry
  17273. if ( Array.isArray( material ) ) {
  17274. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17275. const group = groups[ i ];
  17276. const groupMaterial = material[ group.materialIndex ];
  17277. const start = Math.max( group.start, drawRange.start );
  17278. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17279. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17280. const a = j;
  17281. const b = j + 1;
  17282. const c = j + 2;
  17283. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17284. if ( intersection ) {
  17285. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  17286. intersection.face.materialIndex = group.materialIndex;
  17287. intersects.push( intersection );
  17288. }
  17289. }
  17290. }
  17291. } else {
  17292. const start = Math.max( 0, drawRange.start );
  17293. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  17294. for ( let i = start, il = end; i < il; i += 3 ) {
  17295. const a = i;
  17296. const b = i + 1;
  17297. const c = i + 2;
  17298. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17299. if ( intersection ) {
  17300. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  17301. intersects.push( intersection );
  17302. }
  17303. }
  17304. }
  17305. }
  17306. }
  17307. }
  17308. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  17309. let intersect;
  17310. if ( material.side === BackSide ) {
  17311. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  17312. } else {
  17313. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  17314. }
  17315. if ( intersect === null ) return null;
  17316. _intersectionPointWorld.copy( point );
  17317. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  17318. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  17319. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  17320. return {
  17321. distance: distance,
  17322. point: _intersectionPointWorld.clone(),
  17323. object: object
  17324. };
  17325. }
  17326. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  17327. object.getVertexPosition( a, _vA );
  17328. object.getVertexPosition( b, _vB );
  17329. object.getVertexPosition( c, _vC );
  17330. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  17331. if ( intersection ) {
  17332. const barycoord = new Vector3();
  17333. Triangle.getBarycoord( _intersectionPoint, _vA, _vB, _vC, barycoord );
  17334. if ( uv ) {
  17335. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  17336. }
  17337. if ( uv1 ) {
  17338. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  17339. }
  17340. if ( normal ) {
  17341. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  17342. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  17343. intersection.normal.multiplyScalar( -1 );
  17344. }
  17345. }
  17346. const face = {
  17347. a: a,
  17348. b: b,
  17349. c: c,
  17350. normal: new Vector3(),
  17351. materialIndex: 0
  17352. };
  17353. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  17354. intersection.face = face;
  17355. intersection.barycoord = barycoord;
  17356. }
  17357. return intersection;
  17358. }
  17359. const _basePosition = /*@__PURE__*/ new Vector3();
  17360. const _skinIndex = /*@__PURE__*/ new Vector4();
  17361. const _skinWeight = /*@__PURE__*/ new Vector4();
  17362. const _vector3 = /*@__PURE__*/ new Vector3();
  17363. const _matrix4 = /*@__PURE__*/ new Matrix4();
  17364. const _vertex = /*@__PURE__*/ new Vector3();
  17365. const _sphere$5 = /*@__PURE__*/ new Sphere();
  17366. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  17367. const _ray$2 = /*@__PURE__*/ new Ray();
  17368. /**
  17369. * A mesh that has a {@link Skeleton} that can then be used to animate the
  17370. * vertices of the geometry with skinning/skeleton animation.
  17371. *
  17372. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  17373. * as buffer attributes in its geometry. These attribute define which bones affect a single
  17374. * vertex to a certain extend.
  17375. *
  17376. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  17377. * or {@link FBXLoader } import respective models.
  17378. *
  17379. * @augments Mesh
  17380. * @demo scenes/bones-browser.html
  17381. */
  17382. class SkinnedMesh extends Mesh {
  17383. /**
  17384. * Constructs a new skinned mesh.
  17385. *
  17386. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17387. * @param {Material|Array<Material>} [material] - The mesh material.
  17388. */
  17389. constructor( geometry, material ) {
  17390. super( geometry, material );
  17391. /**
  17392. * This flag can be used for type testing.
  17393. *
  17394. * @type {boolean}
  17395. * @readonly
  17396. * @default true
  17397. */
  17398. this.isSkinnedMesh = true;
  17399. this.type = 'SkinnedMesh';
  17400. /**
  17401. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  17402. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  17403. * across multiple skinned meshes.
  17404. *
  17405. * @type {(AttachedBindMode|DetachedBindMode)}
  17406. * @default AttachedBindMode
  17407. */
  17408. this.bindMode = AttachedBindMode;
  17409. /**
  17410. * The base matrix that is used for the bound bone transforms.
  17411. *
  17412. * @type {Matrix4}
  17413. */
  17414. this.bindMatrix = new Matrix4();
  17415. /**
  17416. * The base matrix that is used for resetting the bound bone transforms.
  17417. *
  17418. * @type {Matrix4}
  17419. */
  17420. this.bindMatrixInverse = new Matrix4();
  17421. /**
  17422. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  17423. *
  17424. * @type {?Box3}
  17425. * @default null
  17426. */
  17427. this.boundingBox = null;
  17428. /**
  17429. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  17430. *
  17431. * @type {?Sphere}
  17432. * @default null
  17433. */
  17434. this.boundingSphere = null;
  17435. }
  17436. /**
  17437. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  17438. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  17439. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  17440. * the current animation state.
  17441. */
  17442. computeBoundingBox() {
  17443. const geometry = this.geometry;
  17444. if ( this.boundingBox === null ) {
  17445. this.boundingBox = new Box3();
  17446. }
  17447. this.boundingBox.makeEmpty();
  17448. const positionAttribute = geometry.getAttribute( 'position' );
  17449. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17450. this.getVertexPosition( i, _vertex );
  17451. this.boundingBox.expandByPoint( _vertex );
  17452. }
  17453. }
  17454. /**
  17455. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  17456. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  17457. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  17458. * per frame in order to reflect the current animation state.
  17459. */
  17460. computeBoundingSphere() {
  17461. const geometry = this.geometry;
  17462. if ( this.boundingSphere === null ) {
  17463. this.boundingSphere = new Sphere();
  17464. }
  17465. this.boundingSphere.makeEmpty();
  17466. const positionAttribute = geometry.getAttribute( 'position' );
  17467. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17468. this.getVertexPosition( i, _vertex );
  17469. this.boundingSphere.expandByPoint( _vertex );
  17470. }
  17471. }
  17472. copy( source, recursive ) {
  17473. super.copy( source, recursive );
  17474. this.bindMode = source.bindMode;
  17475. this.bindMatrix.copy( source.bindMatrix );
  17476. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17477. this.skeleton = source.skeleton;
  17478. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  17479. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  17480. return this;
  17481. }
  17482. raycast( raycaster, intersects ) {
  17483. const material = this.material;
  17484. const matrixWorld = this.matrixWorld;
  17485. if ( material === undefined ) return;
  17486. // test with bounding sphere in world space
  17487. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  17488. _sphere$5.copy( this.boundingSphere );
  17489. _sphere$5.applyMatrix4( matrixWorld );
  17490. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  17491. // convert ray to local space of skinned mesh
  17492. _inverseMatrix$2.copy( matrixWorld ).invert();
  17493. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  17494. // test with bounding box in local space
  17495. if ( this.boundingBox !== null ) {
  17496. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  17497. }
  17498. // test for intersections with geometry
  17499. this._computeIntersections( raycaster, intersects, _ray$2 );
  17500. }
  17501. getVertexPosition( index, target ) {
  17502. super.getVertexPosition( index, target );
  17503. this.applyBoneTransform( index, target );
  17504. return target;
  17505. }
  17506. /**
  17507. * Binds the given skeleton to the skinned mesh.
  17508. *
  17509. * @param {Skeleton} skeleton - The skeleton to bind.
  17510. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  17511. * the skinned mesh's world matrix will be used instead.
  17512. */
  17513. bind( skeleton, bindMatrix ) {
  17514. this.skeleton = skeleton;
  17515. if ( bindMatrix === undefined ) {
  17516. this.updateMatrixWorld( true );
  17517. this.skeleton.calculateInverses();
  17518. bindMatrix = this.matrixWorld;
  17519. }
  17520. this.bindMatrix.copy( bindMatrix );
  17521. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17522. }
  17523. /**
  17524. * This method sets the skinned mesh in the rest pose).
  17525. */
  17526. pose() {
  17527. this.skeleton.pose();
  17528. }
  17529. /**
  17530. * Normalizes the skin weights which are defined as a buffer attribute
  17531. * in the skinned mesh's geometry.
  17532. */
  17533. normalizeSkinWeights() {
  17534. const vector = new Vector4();
  17535. const skinWeight = this.geometry.attributes.skinWeight;
  17536. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17537. vector.fromBufferAttribute( skinWeight, i );
  17538. const scale = 1.0 / vector.manhattanLength();
  17539. if ( scale !== Infinity ) {
  17540. vector.multiplyScalar( scale );
  17541. } else {
  17542. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17543. }
  17544. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17545. }
  17546. }
  17547. updateMatrixWorld( force ) {
  17548. super.updateMatrixWorld( force );
  17549. if ( this.bindMode === AttachedBindMode ) {
  17550. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17551. } else if ( this.bindMode === DetachedBindMode ) {
  17552. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17553. } else {
  17554. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17555. }
  17556. }
  17557. /**
  17558. * Applies the bone transform associated with the given index to the given
  17559. * vertex position. Returns the updated vector.
  17560. *
  17561. * @param {number} index - The vertex index.
  17562. * @param {Vector3} target - The target object that is used to store the method's result.
  17563. * the skinned mesh's world matrix will be used instead.
  17564. * @return {Vector3} The updated vertex position.
  17565. */
  17566. applyBoneTransform( index, target ) {
  17567. const skeleton = this.skeleton;
  17568. const geometry = this.geometry;
  17569. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17570. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17571. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  17572. target.set( 0, 0, 0 );
  17573. for ( let i = 0; i < 4; i ++ ) {
  17574. const weight = _skinWeight.getComponent( i );
  17575. if ( weight !== 0 ) {
  17576. const boneIndex = _skinIndex.getComponent( i );
  17577. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17578. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  17579. }
  17580. }
  17581. return target.applyMatrix4( this.bindMatrixInverse );
  17582. }
  17583. }
  17584. /**
  17585. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  17586. * the {@link SkinnedMesh}.
  17587. *
  17588. * ```js
  17589. * const root = new THREE.Bone();
  17590. * const child = new THREE.Bone();
  17591. *
  17592. * root.add( child );
  17593. * child.position.y = 5;
  17594. * ```
  17595. *
  17596. * @augments Object3D
  17597. */
  17598. class Bone extends Object3D {
  17599. /**
  17600. * Constructs a new bone.
  17601. */
  17602. constructor() {
  17603. super();
  17604. /**
  17605. * This flag can be used for type testing.
  17606. *
  17607. * @type {boolean}
  17608. * @readonly
  17609. * @default true
  17610. */
  17611. this.isBone = true;
  17612. this.type = 'Bone';
  17613. }
  17614. }
  17615. /**
  17616. * Creates a texture directly from raw buffer data.
  17617. *
  17618. * The interpretation of the data depends on type and format: If the type is
  17619. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  17620. * texel data. If the format is `RGBAFormat`, data needs four values for
  17621. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  17622. *
  17623. * @augments Texture
  17624. */
  17625. class DataTexture extends Texture {
  17626. /**
  17627. * Constructs a new data texture.
  17628. *
  17629. * @param {?TypedArray} [data=null] - The buffer data.
  17630. * @param {number} [width=1] - The width of the texture.
  17631. * @param {number} [height=1] - The height of the texture.
  17632. * @param {number} [format=RGBAFormat] - The texture format.
  17633. * @param {number} [type=UnsignedByteType] - The texture type.
  17634. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  17635. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  17636. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  17637. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  17638. * @param {number} [minFilter=NearestFilter] - The min filter value.
  17639. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  17640. * @param {string} [colorSpace=NoColorSpace] - The color space.
  17641. */
  17642. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  17643. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  17644. /**
  17645. * This flag can be used for type testing.
  17646. *
  17647. * @type {boolean}
  17648. * @readonly
  17649. * @default true
  17650. */
  17651. this.isDataTexture = true;
  17652. /**
  17653. * The image definition of a data texture.
  17654. *
  17655. * @type {{data:TypedArray,width:number,height:number}}
  17656. */
  17657. this.image = { data: data, width: width, height: height };
  17658. /**
  17659. * Whether to generate mipmaps (if possible) for a texture.
  17660. *
  17661. * Overwritten and set to `false` by default.
  17662. *
  17663. * @type {boolean}
  17664. * @default false
  17665. */
  17666. this.generateMipmaps = false;
  17667. /**
  17668. * If set to `true`, the texture is flipped along the vertical axis when
  17669. * uploaded to the GPU.
  17670. *
  17671. * Overwritten and set to `false` by default.
  17672. *
  17673. * @type {boolean}
  17674. * @default false
  17675. */
  17676. this.flipY = false;
  17677. /**
  17678. * Specifies the alignment requirements for the start of each pixel row in memory.
  17679. *
  17680. * Overwritten and set to `1` by default.
  17681. *
  17682. * @type {boolean}
  17683. * @default 1
  17684. */
  17685. this.unpackAlignment = 1;
  17686. }
  17687. }
  17688. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  17689. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  17690. /**
  17691. * Class for representing the armatures in `three.js`. The skeleton
  17692. * is defined by a hierarchy of bones.
  17693. *
  17694. * ```js
  17695. * const bones = [];
  17696. *
  17697. * const shoulder = new THREE.Bone();
  17698. * const elbow = new THREE.Bone();
  17699. * const hand = new THREE.Bone();
  17700. *
  17701. * shoulder.add( elbow );
  17702. * elbow.add( hand );
  17703. *
  17704. * bones.push( shoulder , elbow, hand);
  17705. *
  17706. * shoulder.position.y = -5;
  17707. * elbow.position.y = 0;
  17708. * hand.position.y = 5;
  17709. *
  17710. * const armSkeleton = new THREE.Skeleton( bones );
  17711. * ```
  17712. */
  17713. class Skeleton {
  17714. /**
  17715. * Constructs a new skeleton.
  17716. *
  17717. * @param {Array<Bone>} [bones] - An array of bones.
  17718. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  17719. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  17720. */
  17721. constructor( bones = [], boneInverses = [] ) {
  17722. this.uuid = generateUUID();
  17723. /**
  17724. * An array of bones defining the skeleton.
  17725. *
  17726. * @type {Array<Bone>}
  17727. */
  17728. this.bones = bones.slice( 0 );
  17729. /**
  17730. * An array of bone inverse matrices.
  17731. *
  17732. * @type {Array<Matrix4>}
  17733. */
  17734. this.boneInverses = boneInverses;
  17735. /**
  17736. * An array buffer holding the bone data.
  17737. * Input data for {@link Skeleton#boneTexture}.
  17738. *
  17739. * @type {?Float32Array}
  17740. * @default null
  17741. */
  17742. this.boneMatrices = null;
  17743. /**
  17744. * An array buffer holding the bone data of the previous frame.
  17745. * Required for computing velocity. Maintained in {@link SkinningNode}.
  17746. *
  17747. * @type {?Float32Array}
  17748. * @default null
  17749. */
  17750. this.previousBoneMatrices = null;
  17751. /**
  17752. * A texture holding the bone data for use
  17753. * in the vertex shader.
  17754. *
  17755. * @type {?DataTexture}
  17756. * @default null
  17757. */
  17758. this.boneTexture = null;
  17759. this.init();
  17760. }
  17761. /**
  17762. * Initializes the skeleton. This method gets automatically called by the constructor
  17763. * but depending on how the skeleton is created it might be necessary to call this method
  17764. * manually.
  17765. */
  17766. init() {
  17767. const bones = this.bones;
  17768. const boneInverses = this.boneInverses;
  17769. this.boneMatrices = new Float32Array( bones.length * 16 );
  17770. // calculate inverse bone matrices if necessary
  17771. if ( boneInverses.length === 0 ) {
  17772. this.calculateInverses();
  17773. } else {
  17774. // handle special case
  17775. if ( bones.length !== boneInverses.length ) {
  17776. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  17777. this.boneInverses = [];
  17778. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17779. this.boneInverses.push( new Matrix4() );
  17780. }
  17781. }
  17782. }
  17783. }
  17784. /**
  17785. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  17786. * and fills it with new matrices.
  17787. */
  17788. calculateInverses() {
  17789. this.boneInverses.length = 0;
  17790. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17791. const inverse = new Matrix4();
  17792. if ( this.bones[ i ] ) {
  17793. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  17794. }
  17795. this.boneInverses.push( inverse );
  17796. }
  17797. }
  17798. /**
  17799. * Resets the skeleton to the base pose.
  17800. */
  17801. pose() {
  17802. // recover the bind-time world matrices
  17803. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17804. const bone = this.bones[ i ];
  17805. if ( bone ) {
  17806. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  17807. }
  17808. }
  17809. // compute the local matrices, positions, rotations and scales
  17810. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17811. const bone = this.bones[ i ];
  17812. if ( bone ) {
  17813. if ( bone.parent && bone.parent.isBone ) {
  17814. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  17815. bone.matrix.multiply( bone.matrixWorld );
  17816. } else {
  17817. bone.matrix.copy( bone.matrixWorld );
  17818. }
  17819. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  17820. }
  17821. }
  17822. }
  17823. /**
  17824. * Resets the skeleton to the base pose.
  17825. */
  17826. update() {
  17827. const bones = this.bones;
  17828. const boneInverses = this.boneInverses;
  17829. const boneMatrices = this.boneMatrices;
  17830. const boneTexture = this.boneTexture;
  17831. // flatten bone matrices to array
  17832. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  17833. // compute the offset between the current and the original transform
  17834. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  17835. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  17836. _offsetMatrix.toArray( boneMatrices, i * 16 );
  17837. }
  17838. if ( boneTexture !== null ) {
  17839. boneTexture.needsUpdate = true;
  17840. }
  17841. }
  17842. /**
  17843. * Returns a new skeleton with copied values from this instance.
  17844. *
  17845. * @return {Skeleton} A clone of this instance.
  17846. */
  17847. clone() {
  17848. return new Skeleton( this.bones, this.boneInverses );
  17849. }
  17850. /**
  17851. * Computes a data texture for passing bone data to the vertex shader.
  17852. *
  17853. * @return {Skeleton} A reference of this instance.
  17854. */
  17855. computeBoneTexture() {
  17856. // layout (1 matrix = 4 pixels)
  17857. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17858. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17859. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17860. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17861. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17862. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  17863. size = Math.ceil( size / 4 ) * 4;
  17864. size = Math.max( size, 4 );
  17865. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17866. boneMatrices.set( this.boneMatrices ); // copy current values
  17867. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17868. boneTexture.needsUpdate = true;
  17869. this.boneMatrices = boneMatrices;
  17870. this.boneTexture = boneTexture;
  17871. return this;
  17872. }
  17873. /**
  17874. * Searches through the skeleton's bone array and returns the first with a
  17875. * matching name.
  17876. *
  17877. * @param {string} name - The name of the bone.
  17878. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  17879. */
  17880. getBoneByName( name ) {
  17881. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17882. const bone = this.bones[ i ];
  17883. if ( bone.name === name ) {
  17884. return bone;
  17885. }
  17886. }
  17887. return undefined;
  17888. }
  17889. /**
  17890. * Frees the GPU-related resources allocated by this instance. Call this
  17891. * method whenever this instance is no longer used in your app.
  17892. */
  17893. dispose( ) {
  17894. if ( this.boneTexture !== null ) {
  17895. this.boneTexture.dispose();
  17896. this.boneTexture = null;
  17897. }
  17898. }
  17899. /**
  17900. * Setups the skeleton by the given JSON and bones.
  17901. *
  17902. * @param {Object} json - The skeleton as serialized JSON.
  17903. * @param {Object<string, Bone>} bones - An array of bones.
  17904. * @return {Skeleton} A reference of this instance.
  17905. */
  17906. fromJSON( json, bones ) {
  17907. this.uuid = json.uuid;
  17908. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  17909. const uuid = json.bones[ i ];
  17910. let bone = bones[ uuid ];
  17911. if ( bone === undefined ) {
  17912. warn( 'Skeleton: No bone found with UUID:', uuid );
  17913. bone = new Bone();
  17914. }
  17915. this.bones.push( bone );
  17916. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  17917. }
  17918. this.init();
  17919. return this;
  17920. }
  17921. /**
  17922. * Serializes the skeleton into JSON.
  17923. *
  17924. * @return {Object} A JSON object representing the serialized skeleton.
  17925. * @see {@link ObjectLoader#parse}
  17926. */
  17927. toJSON() {
  17928. const data = {
  17929. metadata: {
  17930. version: 4.7,
  17931. type: 'Skeleton',
  17932. generator: 'Skeleton.toJSON'
  17933. },
  17934. bones: [],
  17935. boneInverses: []
  17936. };
  17937. data.uuid = this.uuid;
  17938. const bones = this.bones;
  17939. const boneInverses = this.boneInverses;
  17940. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  17941. const bone = bones[ i ];
  17942. data.bones.push( bone.uuid );
  17943. const boneInverse = boneInverses[ i ];
  17944. data.boneInverses.push( boneInverse.toArray() );
  17945. }
  17946. return data;
  17947. }
  17948. }
  17949. /**
  17950. * An instanced version of a buffer attribute.
  17951. *
  17952. * @augments BufferAttribute
  17953. */
  17954. class InstancedBufferAttribute extends BufferAttribute {
  17955. /**
  17956. * Constructs a new instanced buffer attribute.
  17957. *
  17958. * @param {TypedArray} array - The array holding the attribute data.
  17959. * @param {number} itemSize - The item size.
  17960. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17961. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  17962. */
  17963. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  17964. super( array, itemSize, normalized );
  17965. /**
  17966. * This flag can be used for type testing.
  17967. *
  17968. * @type {boolean}
  17969. * @readonly
  17970. * @default true
  17971. */
  17972. this.isInstancedBufferAttribute = true;
  17973. /**
  17974. * Defines how often a value of this buffer attribute should be repeated. A
  17975. * value of one means that each value of the instanced attribute is used for
  17976. * a single instance. A value of two means that each value is used for two
  17977. * consecutive instances (and so on).
  17978. *
  17979. * @type {number}
  17980. * @default 1
  17981. */
  17982. this.meshPerAttribute = meshPerAttribute;
  17983. }
  17984. copy( source ) {
  17985. super.copy( source );
  17986. this.meshPerAttribute = source.meshPerAttribute;
  17987. return this;
  17988. }
  17989. toJSON() {
  17990. const data = super.toJSON();
  17991. data.meshPerAttribute = this.meshPerAttribute;
  17992. data.isInstancedBufferAttribute = true;
  17993. return data;
  17994. }
  17995. }
  17996. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  17997. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  17998. const _instanceIntersects = [];
  17999. const _box3 = /*@__PURE__*/ new Box3();
  18000. const _identity = /*@__PURE__*/ new Matrix4();
  18001. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18002. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18003. /**
  18004. * A special version of a mesh with instanced rendering support. Use
  18005. * this class if you have to render a large number of objects with the same
  18006. * geometry and material(s) but with different world transformations. The usage
  18007. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18008. * improve the overall rendering performance in your application.
  18009. *
  18010. * @augments Mesh
  18011. */
  18012. class InstancedMesh extends Mesh {
  18013. /**
  18014. * Constructs a new instanced mesh.
  18015. *
  18016. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18017. * @param {Material|Array<Material>} [material] - The mesh material.
  18018. * @param {number} count - The number of instances.
  18019. */
  18020. constructor( geometry, material, count ) {
  18021. super( geometry, material );
  18022. /**
  18023. * This flag can be used for type testing.
  18024. *
  18025. * @type {boolean}
  18026. * @readonly
  18027. * @default true
  18028. */
  18029. this.isInstancedMesh = true;
  18030. /**
  18031. * Represents the local transformation of all instances. You have to set its
  18032. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18033. * via {@link InstancedMesh#setMatrixAt}.
  18034. *
  18035. * @type {InstancedBufferAttribute}
  18036. */
  18037. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18038. /**
  18039. * Represents the local transformation of all instances of the previous frame.
  18040. * Required for computing velocity. Maintained in {@link InstanceNode}.
  18041. *
  18042. * @type {?InstancedBufferAttribute}
  18043. * @default null
  18044. */
  18045. this.previousInstanceMatrix = null;
  18046. /**
  18047. * Represents the color of all instances. You have to set its
  18048. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18049. * via {@link InstancedMesh#setColorAt}.
  18050. *
  18051. * @type {?InstancedBufferAttribute}
  18052. * @default null
  18053. */
  18054. this.instanceColor = null;
  18055. /**
  18056. * Represents the morph target weights of all instances. You have to set its
  18057. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18058. * via {@link InstancedMesh#setMorphAt}.
  18059. *
  18060. * @type {?DataTexture}
  18061. * @default null
  18062. */
  18063. this.morphTexture = null;
  18064. /**
  18065. * The number of instances.
  18066. *
  18067. * @type {number}
  18068. */
  18069. this.count = count;
  18070. /**
  18071. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18072. *
  18073. * @type {?Box3}
  18074. * @default null
  18075. */
  18076. this.boundingBox = null;
  18077. /**
  18078. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18079. *
  18080. * @type {?Sphere}
  18081. * @default null
  18082. */
  18083. this.boundingSphere = null;
  18084. for ( let i = 0; i < count; i ++ ) {
  18085. this.setMatrixAt( i, _identity );
  18086. }
  18087. }
  18088. /**
  18089. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18090. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18091. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18092. */
  18093. computeBoundingBox() {
  18094. const geometry = this.geometry;
  18095. const count = this.count;
  18096. if ( this.boundingBox === null ) {
  18097. this.boundingBox = new Box3();
  18098. }
  18099. if ( geometry.boundingBox === null ) {
  18100. geometry.computeBoundingBox();
  18101. }
  18102. this.boundingBox.makeEmpty();
  18103. for ( let i = 0; i < count; i ++ ) {
  18104. this.getMatrixAt( i, _instanceLocalMatrix );
  18105. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18106. this.boundingBox.union( _box3 );
  18107. }
  18108. }
  18109. /**
  18110. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  18111. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  18112. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18113. */
  18114. computeBoundingSphere() {
  18115. const geometry = this.geometry;
  18116. const count = this.count;
  18117. if ( this.boundingSphere === null ) {
  18118. this.boundingSphere = new Sphere();
  18119. }
  18120. if ( geometry.boundingSphere === null ) {
  18121. geometry.computeBoundingSphere();
  18122. }
  18123. this.boundingSphere.makeEmpty();
  18124. for ( let i = 0; i < count; i ++ ) {
  18125. this.getMatrixAt( i, _instanceLocalMatrix );
  18126. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18127. this.boundingSphere.union( _sphere$4 );
  18128. }
  18129. }
  18130. copy( source, recursive ) {
  18131. super.copy( source, recursive );
  18132. this.instanceMatrix.copy( source.instanceMatrix );
  18133. if ( source.previousInstanceMatrix !== null ) this.previousInstanceMatrix = source.previousInstanceMatrix.clone();
  18134. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  18135. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18136. this.count = source.count;
  18137. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18138. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18139. return this;
  18140. }
  18141. /**
  18142. * Gets the color of the defined instance.
  18143. *
  18144. * @param {number} index - The instance index.
  18145. * @param {Color} color - The target object that is used to store the method's result.
  18146. */
  18147. getColorAt( index, color ) {
  18148. color.fromArray( this.instanceColor.array, index * 3 );
  18149. }
  18150. /**
  18151. * Gets the local transformation matrix of the defined instance.
  18152. *
  18153. * @param {number} index - The instance index.
  18154. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  18155. */
  18156. getMatrixAt( index, matrix ) {
  18157. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18158. }
  18159. /**
  18160. * Gets the morph target weights of the defined instance.
  18161. *
  18162. * @param {number} index - The instance index.
  18163. * @param {Mesh} object - The target object that is used to store the method's result.
  18164. */
  18165. getMorphAt( index, object ) {
  18166. const objectInfluences = object.morphTargetInfluences;
  18167. const array = this.morphTexture.source.data.data;
  18168. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  18169. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  18170. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18171. objectInfluences[ i ] = array[ dataIndex + i ];
  18172. }
  18173. }
  18174. raycast( raycaster, intersects ) {
  18175. const matrixWorld = this.matrixWorld;
  18176. const raycastTimes = this.count;
  18177. _mesh$1.geometry = this.geometry;
  18178. _mesh$1.material = this.material;
  18179. if ( _mesh$1.material === undefined ) return;
  18180. // test with bounding sphere first
  18181. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18182. _sphere$4.copy( this.boundingSphere );
  18183. _sphere$4.applyMatrix4( matrixWorld );
  18184. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  18185. // now test each instance
  18186. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18187. // calculate the world matrix for each instance
  18188. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18189. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18190. // the mesh represents this single instance
  18191. _mesh$1.matrixWorld = _instanceWorldMatrix;
  18192. _mesh$1.raycast( raycaster, _instanceIntersects );
  18193. // process the result of raycast
  18194. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18195. const intersect = _instanceIntersects[ i ];
  18196. intersect.instanceId = instanceId;
  18197. intersect.object = this;
  18198. intersects.push( intersect );
  18199. }
  18200. _instanceIntersects.length = 0;
  18201. }
  18202. }
  18203. /**
  18204. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  18205. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  18206. *
  18207. * @param {number} index - The instance index.
  18208. * @param {Color} color - The instance color.
  18209. */
  18210. setColorAt( index, color ) {
  18211. if ( this.instanceColor === null ) {
  18212. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  18213. }
  18214. color.toArray( this.instanceColor.array, index * 3 );
  18215. }
  18216. /**
  18217. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  18218. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  18219. *
  18220. * @param {number} index - The instance index.
  18221. * @param {Matrix4} matrix - The local transformation.
  18222. */
  18223. setMatrixAt( index, matrix ) {
  18224. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18225. }
  18226. /**
  18227. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  18228. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  18229. *
  18230. * @param {number} index - The instance index.
  18231. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  18232. * of a single instance.
  18233. */
  18234. setMorphAt( index, object ) {
  18235. const objectInfluences = object.morphTargetInfluences;
  18236. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  18237. if ( this.morphTexture === null ) {
  18238. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  18239. }
  18240. const array = this.morphTexture.source.data.data;
  18241. let morphInfluencesSum = 0;
  18242. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18243. morphInfluencesSum += objectInfluences[ i ];
  18244. }
  18245. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  18246. const dataIndex = len * index;
  18247. array[ dataIndex ] = morphBaseInfluence;
  18248. array.set( objectInfluences, dataIndex + 1 );
  18249. }
  18250. updateMorphTargets() {
  18251. }
  18252. /**
  18253. * Frees the GPU-related resources allocated by this instance. Call this
  18254. * method whenever this instance is no longer used in your app.
  18255. */
  18256. dispose() {
  18257. this.dispatchEvent( { type: 'dispose' } );
  18258. if ( this.morphTexture !== null ) {
  18259. this.morphTexture.dispose();
  18260. this.morphTexture = null;
  18261. }
  18262. }
  18263. }
  18264. const _vector1 = /*@__PURE__*/ new Vector3();
  18265. const _vector2 = /*@__PURE__*/ new Vector3();
  18266. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  18267. /**
  18268. * A two dimensional surface that extends infinitely in 3D space, represented
  18269. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  18270. * by a unit length normal vector and a constant.
  18271. */
  18272. class Plane {
  18273. /**
  18274. * Constructs a new plane.
  18275. *
  18276. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  18277. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  18278. */
  18279. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  18280. /**
  18281. * This flag can be used for type testing.
  18282. *
  18283. * @type {boolean}
  18284. * @readonly
  18285. * @default true
  18286. */
  18287. this.isPlane = true;
  18288. /**
  18289. * A unit length vector defining the normal of the plane.
  18290. *
  18291. * @type {Vector3}
  18292. */
  18293. this.normal = normal;
  18294. /**
  18295. * The signed distance from the origin to the plane.
  18296. *
  18297. * @type {number}
  18298. * @default 0
  18299. */
  18300. this.constant = constant;
  18301. }
  18302. /**
  18303. * Sets the plane components by copying the given values.
  18304. *
  18305. * @param {Vector3} normal - The normal.
  18306. * @param {number} constant - The constant.
  18307. * @return {Plane} A reference to this plane.
  18308. */
  18309. set( normal, constant ) {
  18310. this.normal.copy( normal );
  18311. this.constant = constant;
  18312. return this;
  18313. }
  18314. /**
  18315. * Sets the plane components by defining `x`, `y`, `z` as the
  18316. * plane normal and `w` as the constant.
  18317. *
  18318. * @param {number} x - The value for the normal's x component.
  18319. * @param {number} y - The value for the normal's y component.
  18320. * @param {number} z - The value for the normal's z component.
  18321. * @param {number} w - The constant value.
  18322. * @return {Plane} A reference to this plane.
  18323. */
  18324. setComponents( x, y, z, w ) {
  18325. this.normal.set( x, y, z );
  18326. this.constant = w;
  18327. return this;
  18328. }
  18329. /**
  18330. * Sets the plane from the given normal and coplanar point (that is a point
  18331. * that lies onto the plane).
  18332. *
  18333. * @param {Vector3} normal - The normal.
  18334. * @param {Vector3} point - A coplanar point.
  18335. * @return {Plane} A reference to this plane.
  18336. */
  18337. setFromNormalAndCoplanarPoint( normal, point ) {
  18338. this.normal.copy( normal );
  18339. this.constant = - point.dot( this.normal );
  18340. return this;
  18341. }
  18342. /**
  18343. * Sets the plane from three coplanar points. The winding order is
  18344. * assumed to be counter-clockwise, and determines the direction of
  18345. * the plane normal.
  18346. *
  18347. * @param {Vector3} a - The first coplanar point.
  18348. * @param {Vector3} b - The second coplanar point.
  18349. * @param {Vector3} c - The third coplanar point.
  18350. * @return {Plane} A reference to this plane.
  18351. */
  18352. setFromCoplanarPoints( a, b, c ) {
  18353. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  18354. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  18355. this.setFromNormalAndCoplanarPoint( normal, a );
  18356. return this;
  18357. }
  18358. /**
  18359. * Copies the values of the given plane to this instance.
  18360. *
  18361. * @param {Plane} plane - The plane to copy.
  18362. * @return {Plane} A reference to this plane.
  18363. */
  18364. copy( plane ) {
  18365. this.normal.copy( plane.normal );
  18366. this.constant = plane.constant;
  18367. return this;
  18368. }
  18369. /**
  18370. * Normalizes the plane normal and adjusts the constant accordingly.
  18371. *
  18372. * @return {Plane} A reference to this plane.
  18373. */
  18374. normalize() {
  18375. // Note: will lead to a divide by zero if the plane is invalid.
  18376. const inverseNormalLength = 1.0 / this.normal.length();
  18377. this.normal.multiplyScalar( inverseNormalLength );
  18378. this.constant *= inverseNormalLength;
  18379. return this;
  18380. }
  18381. /**
  18382. * Negates both the plane normal and the constant.
  18383. *
  18384. * @return {Plane} A reference to this plane.
  18385. */
  18386. negate() {
  18387. this.constant *= -1;
  18388. this.normal.negate();
  18389. return this;
  18390. }
  18391. /**
  18392. * Returns the signed distance from the given point to this plane.
  18393. *
  18394. * @param {Vector3} point - The point to compute the distance for.
  18395. * @return {number} The signed distance.
  18396. */
  18397. distanceToPoint( point ) {
  18398. return this.normal.dot( point ) + this.constant;
  18399. }
  18400. /**
  18401. * Returns the signed distance from the given sphere to this plane.
  18402. *
  18403. * @param {Sphere} sphere - The sphere to compute the distance for.
  18404. * @return {number} The signed distance.
  18405. */
  18406. distanceToSphere( sphere ) {
  18407. return this.distanceToPoint( sphere.center ) - sphere.radius;
  18408. }
  18409. /**
  18410. * Projects a the given point onto the plane.
  18411. *
  18412. * @param {Vector3} point - The point to project.
  18413. * @param {Vector3} target - The target vector that is used to store the method's result.
  18414. * @return {Vector3} The projected point on the plane.
  18415. */
  18416. projectPoint( point, target ) {
  18417. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  18418. }
  18419. /**
  18420. * Returns the intersection point of the passed line and the plane. Returns
  18421. * `null` if the line does not intersect. Returns the line's starting point if
  18422. * the line is coplanar with the plane.
  18423. *
  18424. * @param {Line3} line - The line to compute the intersection for.
  18425. * @param {Vector3} target - The target vector that is used to store the method's result.
  18426. * @return {?Vector3} The intersection point.
  18427. */
  18428. intersectLine( line, target ) {
  18429. const direction = line.delta( _vector1 );
  18430. const denominator = this.normal.dot( direction );
  18431. if ( denominator === 0 ) {
  18432. // line is coplanar, return origin
  18433. if ( this.distanceToPoint( line.start ) === 0 ) {
  18434. return target.copy( line.start );
  18435. }
  18436. // Unsure if this is the correct method to handle this case.
  18437. return null;
  18438. }
  18439. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  18440. if ( t < 0 || t > 1 ) {
  18441. return null;
  18442. }
  18443. return target.copy( line.start ).addScaledVector( direction, t );
  18444. }
  18445. /**
  18446. * Returns `true` if the given line segment intersects with (passes through) the plane.
  18447. *
  18448. * @param {Line3} line - The line to test.
  18449. * @return {boolean} Whether the given line segment intersects with the plane or not.
  18450. */
  18451. intersectsLine( line ) {
  18452. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  18453. const startSign = this.distanceToPoint( line.start );
  18454. const endSign = this.distanceToPoint( line.end );
  18455. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  18456. }
  18457. /**
  18458. * Returns `true` if the given bounding box intersects with the plane.
  18459. *
  18460. * @param {Box3} box - The bounding box to test.
  18461. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  18462. */
  18463. intersectsBox( box ) {
  18464. return box.intersectsPlane( this );
  18465. }
  18466. /**
  18467. * Returns `true` if the given bounding sphere intersects with the plane.
  18468. *
  18469. * @param {Sphere} sphere - The bounding sphere to test.
  18470. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  18471. */
  18472. intersectsSphere( sphere ) {
  18473. return sphere.intersectsPlane( this );
  18474. }
  18475. /**
  18476. * Returns a coplanar vector to the plane, by calculating the
  18477. * projection of the normal at the origin onto the plane.
  18478. *
  18479. * @param {Vector3} target - The target vector that is used to store the method's result.
  18480. * @return {Vector3} The coplanar point.
  18481. */
  18482. coplanarPoint( target ) {
  18483. return target.copy( this.normal ).multiplyScalar( - this.constant );
  18484. }
  18485. /**
  18486. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  18487. *
  18488. * The optional normal matrix can be pre-computed like so:
  18489. * ```js
  18490. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  18491. * ```
  18492. *
  18493. * @param {Matrix4} matrix - The transformation matrix.
  18494. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  18495. * @return {Plane} A reference to this plane.
  18496. */
  18497. applyMatrix4( matrix, optionalNormalMatrix ) {
  18498. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  18499. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  18500. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  18501. this.constant = - referencePoint.dot( normal );
  18502. return this;
  18503. }
  18504. /**
  18505. * Translates the plane by the distance defined by the given offset vector.
  18506. * Note that this only affects the plane constant and will not affect the normal vector.
  18507. *
  18508. * @param {Vector3} offset - The offset vector.
  18509. * @return {Plane} A reference to this plane.
  18510. */
  18511. translate( offset ) {
  18512. this.constant -= offset.dot( this.normal );
  18513. return this;
  18514. }
  18515. /**
  18516. * Returns `true` if this plane is equal with the given one.
  18517. *
  18518. * @param {Plane} plane - The plane to test for equality.
  18519. * @return {boolean} Whether this plane is equal with the given one.
  18520. */
  18521. equals( plane ) {
  18522. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  18523. }
  18524. /**
  18525. * Returns a new plane with copied values from this instance.
  18526. *
  18527. * @return {Plane} A clone of this instance.
  18528. */
  18529. clone() {
  18530. return new this.constructor().copy( this );
  18531. }
  18532. }
  18533. const _sphere$3 = /*@__PURE__*/ new Sphere();
  18534. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  18535. const _vector$6 = /*@__PURE__*/ new Vector3();
  18536. /**
  18537. * Frustums are used to determine what is inside the camera's field of view.
  18538. * They help speed up the rendering process - objects which lie outside a camera's
  18539. * frustum can safely be excluded from rendering.
  18540. *
  18541. * This class is mainly intended for use internally by a renderer.
  18542. */
  18543. class Frustum {
  18544. /**
  18545. * Constructs a new frustum.
  18546. *
  18547. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18548. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18549. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18550. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18551. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18552. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18553. */
  18554. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  18555. /**
  18556. * This array holds the planes that enclose the frustum.
  18557. *
  18558. * @type {Array<Plane>}
  18559. */
  18560. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  18561. }
  18562. /**
  18563. * Sets the frustum planes by copying the given planes.
  18564. *
  18565. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18566. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18567. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18568. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18569. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18570. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18571. * @return {Frustum} A reference to this frustum.
  18572. */
  18573. set( p0, p1, p2, p3, p4, p5 ) {
  18574. const planes = this.planes;
  18575. planes[ 0 ].copy( p0 );
  18576. planes[ 1 ].copy( p1 );
  18577. planes[ 2 ].copy( p2 );
  18578. planes[ 3 ].copy( p3 );
  18579. planes[ 4 ].copy( p4 );
  18580. planes[ 5 ].copy( p5 );
  18581. return this;
  18582. }
  18583. /**
  18584. * Copies the values of the given frustum to this instance.
  18585. *
  18586. * @param {Frustum} frustum - The frustum to copy.
  18587. * @return {Frustum} A reference to this frustum.
  18588. */
  18589. copy( frustum ) {
  18590. const planes = this.planes;
  18591. for ( let i = 0; i < 6; i ++ ) {
  18592. planes[ i ].copy( frustum.planes[ i ] );
  18593. }
  18594. return this;
  18595. }
  18596. /**
  18597. * Sets the frustum planes from the given projection matrix.
  18598. *
  18599. * @param {Matrix4} m - The projection matrix.
  18600. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  18601. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  18602. * @return {Frustum} A reference to this frustum.
  18603. */
  18604. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  18605. const planes = this.planes;
  18606. const me = m.elements;
  18607. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  18608. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  18609. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  18610. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  18611. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  18612. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  18613. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  18614. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  18615. if ( reversedDepth ) {
  18616. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  18617. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  18618. } else {
  18619. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  18620. if ( coordinateSystem === WebGLCoordinateSystem ) {
  18621. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  18622. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  18623. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  18624. } else {
  18625. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  18626. }
  18627. }
  18628. return this;
  18629. }
  18630. /**
  18631. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  18632. *
  18633. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  18634. *
  18635. * @param {Object3D} object - The 3D object to test.
  18636. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  18637. */
  18638. intersectsObject( object ) {
  18639. if ( object.boundingSphere !== undefined ) {
  18640. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  18641. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  18642. } else {
  18643. const geometry = object.geometry;
  18644. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18645. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  18646. }
  18647. return this.intersectsSphere( _sphere$3 );
  18648. }
  18649. /**
  18650. * Returns `true` if the given sprite is intersecting this frustum.
  18651. *
  18652. * @param {Sprite} sprite - The sprite to test.
  18653. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  18654. */
  18655. intersectsSprite( sprite ) {
  18656. _sphere$3.center.set( 0, 0, 0 );
  18657. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  18658. _sphere$3.radius = 0.7071067811865476 + offset;
  18659. _sphere$3.applyMatrix4( sprite.matrixWorld );
  18660. return this.intersectsSphere( _sphere$3 );
  18661. }
  18662. /**
  18663. * Returns `true` if the given bounding sphere is intersecting this frustum.
  18664. *
  18665. * @param {Sphere} sphere - The bounding sphere to test.
  18666. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  18667. */
  18668. intersectsSphere( sphere ) {
  18669. const planes = this.planes;
  18670. const center = sphere.center;
  18671. const negRadius = - sphere.radius;
  18672. for ( let i = 0; i < 6; i ++ ) {
  18673. const distance = planes[ i ].distanceToPoint( center );
  18674. if ( distance < negRadius ) {
  18675. return false;
  18676. }
  18677. }
  18678. return true;
  18679. }
  18680. /**
  18681. * Returns `true` if the given bounding box is intersecting this frustum.
  18682. *
  18683. * @param {Box3} box - The bounding box to test.
  18684. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  18685. */
  18686. intersectsBox( box ) {
  18687. const planes = this.planes;
  18688. for ( let i = 0; i < 6; i ++ ) {
  18689. const plane = planes[ i ];
  18690. // corner at max distance
  18691. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  18692. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  18693. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  18694. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  18695. return false;
  18696. }
  18697. }
  18698. return true;
  18699. }
  18700. /**
  18701. * Returns `true` if the given point lies within the frustum.
  18702. *
  18703. * @param {Vector3} point - The point to test.
  18704. * @return {boolean} Whether the point lies within this frustum or not.
  18705. */
  18706. containsPoint( point ) {
  18707. const planes = this.planes;
  18708. for ( let i = 0; i < 6; i ++ ) {
  18709. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  18710. return false;
  18711. }
  18712. }
  18713. return true;
  18714. }
  18715. /**
  18716. * Returns a new frustum with copied values from this instance.
  18717. *
  18718. * @return {Frustum} A clone of this instance.
  18719. */
  18720. clone() {
  18721. return new this.constructor().copy( this );
  18722. }
  18723. }
  18724. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  18725. const _frustum$1 = /*@__PURE__*/ new Frustum();
  18726. /**
  18727. * FrustumArray is used to determine if an object is visible in at least one camera
  18728. * from an array of cameras. This is particularly useful for multi-view renderers.
  18729. */
  18730. class FrustumArray {
  18731. /**
  18732. * Constructs a new frustum array.
  18733. *
  18734. */
  18735. constructor() {
  18736. /**
  18737. * The coordinate system to use.
  18738. *
  18739. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  18740. * @default WebGLCoordinateSystem
  18741. */
  18742. this.coordinateSystem = WebGLCoordinateSystem;
  18743. }
  18744. /**
  18745. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  18746. * from the camera array.
  18747. *
  18748. * @param {Object3D} object - The 3D object to test.
  18749. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18750. * @return {boolean} Whether the 3D object is visible in any camera.
  18751. */
  18752. intersectsObject( object, cameraArray ) {
  18753. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  18754. return false;
  18755. }
  18756. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18757. const camera = cameraArray.cameras[ i ];
  18758. _projScreenMatrix$1.multiplyMatrices(
  18759. camera.projectionMatrix,
  18760. camera.matrixWorldInverse
  18761. );
  18762. _frustum$1.setFromProjectionMatrix(
  18763. _projScreenMatrix$1,
  18764. camera.coordinateSystem,
  18765. camera.reversedDepth
  18766. );
  18767. if ( _frustum$1.intersectsObject( object ) ) {
  18768. return true; // Object is visible in at least one camera
  18769. }
  18770. }
  18771. return false; // Not visible in any camera
  18772. }
  18773. /**
  18774. * Returns `true` if the given sprite is intersecting any frustum
  18775. * from the camera array.
  18776. *
  18777. * @param {Sprite} sprite - The sprite to test.
  18778. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18779. * @return {boolean} Whether the sprite is visible in any camera.
  18780. */
  18781. intersectsSprite( sprite, cameraArray ) {
  18782. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18783. return false;
  18784. }
  18785. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18786. const camera = cameraArray.cameras[ i ];
  18787. _projScreenMatrix$1.multiplyMatrices(
  18788. camera.projectionMatrix,
  18789. camera.matrixWorldInverse
  18790. );
  18791. _frustum$1.setFromProjectionMatrix(
  18792. _projScreenMatrix$1,
  18793. camera.coordinateSystem,
  18794. camera.reversedDepth
  18795. );
  18796. if ( _frustum$1.intersectsSprite( sprite ) ) {
  18797. return true; // Sprite is visible in at least one camera
  18798. }
  18799. }
  18800. return false; // Not visible in any camera
  18801. }
  18802. /**
  18803. * Returns `true` if the given bounding sphere is intersecting any frustum
  18804. * from the camera array.
  18805. *
  18806. * @param {Sphere} sphere - The bounding sphere to test.
  18807. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18808. * @return {boolean} Whether the sphere is visible in any camera.
  18809. */
  18810. intersectsSphere( sphere, cameraArray ) {
  18811. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18812. return false;
  18813. }
  18814. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18815. const camera = cameraArray.cameras[ i ];
  18816. _projScreenMatrix$1.multiplyMatrices(
  18817. camera.projectionMatrix,
  18818. camera.matrixWorldInverse
  18819. );
  18820. _frustum$1.setFromProjectionMatrix(
  18821. _projScreenMatrix$1,
  18822. camera.coordinateSystem,
  18823. camera.reversedDepth
  18824. );
  18825. if ( _frustum$1.intersectsSphere( sphere ) ) {
  18826. return true; // Sphere is visible in at least one camera
  18827. }
  18828. }
  18829. return false; // Not visible in any camera
  18830. }
  18831. /**
  18832. * Returns `true` if the given bounding box is intersecting any frustum
  18833. * from the camera array.
  18834. *
  18835. * @param {Box3} box - The bounding box to test.
  18836. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18837. * @return {boolean} Whether the box is visible in any camera.
  18838. */
  18839. intersectsBox( box, cameraArray ) {
  18840. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18841. return false;
  18842. }
  18843. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18844. const camera = cameraArray.cameras[ i ];
  18845. _projScreenMatrix$1.multiplyMatrices(
  18846. camera.projectionMatrix,
  18847. camera.matrixWorldInverse
  18848. );
  18849. _frustum$1.setFromProjectionMatrix(
  18850. _projScreenMatrix$1,
  18851. camera.coordinateSystem,
  18852. camera.reversedDepth
  18853. );
  18854. if ( _frustum$1.intersectsBox( box ) ) {
  18855. return true; // Box is visible in at least one camera
  18856. }
  18857. }
  18858. return false; // Not visible in any camera
  18859. }
  18860. /**
  18861. * Returns `true` if the given point lies within any frustum
  18862. * from the camera array.
  18863. *
  18864. * @param {Vector3} point - The point to test.
  18865. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18866. * @return {boolean} Whether the point is visible in any camera.
  18867. */
  18868. containsPoint( point, cameraArray ) {
  18869. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18870. return false;
  18871. }
  18872. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18873. const camera = cameraArray.cameras[ i ];
  18874. _projScreenMatrix$1.multiplyMatrices(
  18875. camera.projectionMatrix,
  18876. camera.matrixWorldInverse
  18877. );
  18878. _frustum$1.setFromProjectionMatrix(
  18879. _projScreenMatrix$1,
  18880. camera.coordinateSystem,
  18881. camera.reversedDepth
  18882. );
  18883. if ( _frustum$1.containsPoint( point ) ) {
  18884. return true; // Point is visible in at least one camera
  18885. }
  18886. }
  18887. return false; // Not visible in any camera
  18888. }
  18889. /**
  18890. * Returns a new frustum array with copied values from this instance.
  18891. *
  18892. * @return {FrustumArray} A clone of this instance.
  18893. */
  18894. clone() {
  18895. return new FrustumArray();
  18896. }
  18897. }
  18898. function ascIdSort( a, b ) {
  18899. return a - b;
  18900. }
  18901. function sortOpaque( a, b ) {
  18902. return a.z - b.z;
  18903. }
  18904. function sortTransparent( a, b ) {
  18905. return b.z - a.z;
  18906. }
  18907. class MultiDrawRenderList {
  18908. constructor() {
  18909. this.index = 0;
  18910. this.pool = [];
  18911. this.list = [];
  18912. }
  18913. push( start, count, z, index ) {
  18914. const pool = this.pool;
  18915. const list = this.list;
  18916. if ( this.index >= pool.length ) {
  18917. pool.push( {
  18918. start: -1,
  18919. count: -1,
  18920. z: -1,
  18921. index: -1,
  18922. } );
  18923. }
  18924. const item = pool[ this.index ];
  18925. list.push( item );
  18926. this.index ++;
  18927. item.start = start;
  18928. item.count = count;
  18929. item.z = z;
  18930. item.index = index;
  18931. }
  18932. reset() {
  18933. this.list.length = 0;
  18934. this.index = 0;
  18935. }
  18936. }
  18937. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  18938. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  18939. const _frustum = /*@__PURE__*/ new Frustum();
  18940. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  18941. const _box$1 = /*@__PURE__*/ new Box3();
  18942. const _sphere$2 = /*@__PURE__*/ new Sphere();
  18943. const _vector$5 = /*@__PURE__*/ new Vector3();
  18944. const _forward$1 = /*@__PURE__*/ new Vector3();
  18945. const _temp = /*@__PURE__*/ new Vector3();
  18946. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  18947. const _mesh = /*@__PURE__*/ new Mesh();
  18948. const _batchIntersects = [];
  18949. // copies data from attribute "src" into "target" starting at "targetOffset"
  18950. function copyAttributeData( src, target, targetOffset = 0 ) {
  18951. const itemSize = target.itemSize;
  18952. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  18953. // use the component getters and setters if the array data cannot
  18954. // be copied directly
  18955. const vertexCount = src.count;
  18956. for ( let i = 0; i < vertexCount; i ++ ) {
  18957. for ( let c = 0; c < itemSize; c ++ ) {
  18958. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  18959. }
  18960. }
  18961. } else {
  18962. // faster copy approach using typed array set function
  18963. target.array.set( src.array, targetOffset * itemSize );
  18964. }
  18965. target.needsUpdate = true;
  18966. }
  18967. // safely copies array contents to a potentially smaller array
  18968. function copyArrayContents( src, target ) {
  18969. if ( src.constructor !== target.constructor ) {
  18970. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  18971. const len = Math.min( src.length, target.length );
  18972. for ( let i = 0; i < len; i ++ ) {
  18973. target[ i ] = src[ i ];
  18974. }
  18975. } else {
  18976. // if the arrays use the same data layout we can use a fast block copy
  18977. const len = Math.min( src.length, target.length );
  18978. target.set( new src.constructor( src.buffer, 0, len ) );
  18979. }
  18980. }
  18981. /**
  18982. * A special version of a mesh with multi draw batch rendering support. Use
  18983. * this class if you have to render a large number of objects with the same
  18984. * material but with different geometries or world transformations. The usage of
  18985. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  18986. * rendering performance in your application.
  18987. *
  18988. * ```js
  18989. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  18990. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  18991. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  18992. *
  18993. * // initialize and add geometries into the batched mesh
  18994. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  18995. * const boxGeometryId = batchedMesh.addGeometry( box );
  18996. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  18997. *
  18998. * // create instances of those geometries
  18999. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19000. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19001. *
  19002. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19003. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19004. *
  19005. * // position the geometries
  19006. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19007. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19008. *
  19009. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19010. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19011. *
  19012. * scene.add( batchedMesh );
  19013. * ```
  19014. *
  19015. * @augments Mesh
  19016. */
  19017. class BatchedMesh extends Mesh {
  19018. /**
  19019. * Constructs a new batched mesh.
  19020. *
  19021. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19022. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19023. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19024. * @param {Material|Array<Material>} [material] - The mesh material.
  19025. */
  19026. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19027. super( new BufferGeometry(), material );
  19028. /**
  19029. * This flag can be used for type testing.
  19030. *
  19031. * @type {boolean}
  19032. * @readonly
  19033. * @default true
  19034. */
  19035. this.isBatchedMesh = true;
  19036. /**
  19037. * When set ot `true`, the individual objects of a batch are frustum culled.
  19038. *
  19039. * @type {boolean}
  19040. * @default true
  19041. */
  19042. this.perObjectFrustumCulled = true;
  19043. /**
  19044. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19045. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19046. * rendered front to back.
  19047. *
  19048. * @type {boolean}
  19049. * @default true
  19050. */
  19051. this.sortObjects = true;
  19052. /**
  19053. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19054. *
  19055. * @type {?Box3}
  19056. * @default null
  19057. */
  19058. this.boundingBox = null;
  19059. /**
  19060. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19061. *
  19062. * @type {?Sphere}
  19063. * @default null
  19064. */
  19065. this.boundingSphere = null;
  19066. /**
  19067. * Takes a sort a function that is run before render. The function takes a list of instances to
  19068. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19069. * sort with.
  19070. *
  19071. * @type {?Function}
  19072. * @default null
  19073. */
  19074. this.customSort = null;
  19075. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19076. this._instanceInfo = [];
  19077. this._geometryInfo = [];
  19078. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19079. this._availableInstanceIds = [];
  19080. this._availableGeometryIds = [];
  19081. // used to track where the next point is that geometry should be inserted
  19082. this._nextIndexStart = 0;
  19083. this._nextVertexStart = 0;
  19084. this._geometryCount = 0;
  19085. // flags
  19086. this._visibilityChanged = true;
  19087. this._geometryInitialized = false;
  19088. // cached user options
  19089. this._maxInstanceCount = maxInstanceCount;
  19090. this._maxVertexCount = maxVertexCount;
  19091. this._maxIndexCount = maxIndexCount;
  19092. // buffers for multi draw
  19093. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19094. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19095. this._multiDrawCount = 0;
  19096. this._multiDrawInstances = null;
  19097. // Local matrix per geometry by using data texture
  19098. this._matricesTexture = null;
  19099. this._indirectTexture = null;
  19100. this._colorsTexture = null;
  19101. this._initMatricesTexture();
  19102. this._initIndirectTexture();
  19103. }
  19104. /**
  19105. * The maximum number of individual instances that can be stored in the batch.
  19106. *
  19107. * @type {number}
  19108. * @readonly
  19109. */
  19110. get maxInstanceCount() {
  19111. return this._maxInstanceCount;
  19112. }
  19113. /**
  19114. * The instance count.
  19115. *
  19116. * @type {number}
  19117. * @readonly
  19118. */
  19119. get instanceCount() {
  19120. return this._instanceInfo.length - this._availableInstanceIds.length;
  19121. }
  19122. /**
  19123. * The number of unused vertices.
  19124. *
  19125. * @type {number}
  19126. * @readonly
  19127. */
  19128. get unusedVertexCount() {
  19129. return this._maxVertexCount - this._nextVertexStart;
  19130. }
  19131. /**
  19132. * The number of unused indices.
  19133. *
  19134. * @type {number}
  19135. * @readonly
  19136. */
  19137. get unusedIndexCount() {
  19138. return this._maxIndexCount - this._nextIndexStart;
  19139. }
  19140. _initMatricesTexture() {
  19141. // layout (1 matrix = 4 pixels)
  19142. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19143. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19144. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19145. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19146. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19147. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  19148. size = Math.ceil( size / 4 ) * 4;
  19149. size = Math.max( size, 4 );
  19150. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19151. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19152. this._matricesTexture = matricesTexture;
  19153. }
  19154. _initIndirectTexture() {
  19155. let size = Math.sqrt( this._maxInstanceCount );
  19156. size = Math.ceil( size );
  19157. const indirectArray = new Uint32Array( size * size );
  19158. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  19159. this._indirectTexture = indirectTexture;
  19160. }
  19161. _initColorsTexture() {
  19162. let size = Math.sqrt( this._maxInstanceCount );
  19163. size = Math.ceil( size );
  19164. // 4 floats per RGBA pixel initialized to white
  19165. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19166. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19167. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19168. this._colorsTexture = colorsTexture;
  19169. }
  19170. _initializeGeometry( reference ) {
  19171. const geometry = this.geometry;
  19172. const maxVertexCount = this._maxVertexCount;
  19173. const maxIndexCount = this._maxIndexCount;
  19174. if ( this._geometryInitialized === false ) {
  19175. for ( const attributeName in reference.attributes ) {
  19176. const srcAttribute = reference.getAttribute( attributeName );
  19177. const { array, itemSize, normalized } = srcAttribute;
  19178. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19179. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19180. geometry.setAttribute( attributeName, dstAttribute );
  19181. }
  19182. if ( reference.getIndex() !== null ) {
  19183. // Reserve last u16 index for primitive restart.
  19184. const indexArray = maxVertexCount > 65535
  19185. ? new Uint32Array( maxIndexCount )
  19186. : new Uint16Array( maxIndexCount );
  19187. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19188. }
  19189. this._geometryInitialized = true;
  19190. }
  19191. }
  19192. // Make sure the geometry is compatible with the existing combined geometry attributes
  19193. _validateGeometry( geometry ) {
  19194. // check to ensure the geometries are using consistent attributes and indices
  19195. const batchGeometry = this.geometry;
  19196. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19197. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  19198. }
  19199. for ( const attributeName in batchGeometry.attributes ) {
  19200. if ( ! geometry.hasAttribute( attributeName ) ) {
  19201. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19202. }
  19203. const srcAttribute = geometry.getAttribute( attributeName );
  19204. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19205. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19206. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19207. }
  19208. }
  19209. }
  19210. /**
  19211. * Validates the instance defined by the given ID.
  19212. *
  19213. * @param {number} instanceId - The instance to validate.
  19214. */
  19215. validateInstanceId( instanceId ) {
  19216. const instanceInfo = this._instanceInfo;
  19217. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  19218. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  19219. }
  19220. }
  19221. /**
  19222. * Validates the geometry defined by the given ID.
  19223. *
  19224. * @param {number} geometryId - The geometry to validate.
  19225. */
  19226. validateGeometryId( geometryId ) {
  19227. const geometryInfoList = this._geometryInfo;
  19228. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19229. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  19230. }
  19231. }
  19232. /**
  19233. * Takes a sort a function that is run before render. The function takes a list of instances to
  19234. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  19235. *
  19236. * @param {Function} func - The custom sort function.
  19237. * @return {BatchedMesh} A reference to this batched mesh.
  19238. */
  19239. setCustomSort( func ) {
  19240. this.customSort = func;
  19241. return this;
  19242. }
  19243. /**
  19244. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  19245. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  19246. * otherwise they are `null`.
  19247. */
  19248. computeBoundingBox() {
  19249. if ( this.boundingBox === null ) {
  19250. this.boundingBox = new Box3();
  19251. }
  19252. const boundingBox = this.boundingBox;
  19253. const instanceInfo = this._instanceInfo;
  19254. boundingBox.makeEmpty();
  19255. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19256. if ( instanceInfo[ i ].active === false ) continue;
  19257. const geometryId = instanceInfo[ i ].geometryIndex;
  19258. this.getMatrixAt( i, _matrix$1 );
  19259. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  19260. boundingBox.union( _box$1 );
  19261. }
  19262. }
  19263. /**
  19264. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  19265. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  19266. * otherwise they are `null`.
  19267. */
  19268. computeBoundingSphere() {
  19269. if ( this.boundingSphere === null ) {
  19270. this.boundingSphere = new Sphere();
  19271. }
  19272. const boundingSphere = this.boundingSphere;
  19273. const instanceInfo = this._instanceInfo;
  19274. boundingSphere.makeEmpty();
  19275. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19276. if ( instanceInfo[ i ].active === false ) continue;
  19277. const geometryId = instanceInfo[ i ].geometryIndex;
  19278. this.getMatrixAt( i, _matrix$1 );
  19279. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  19280. boundingSphere.union( _sphere$2 );
  19281. }
  19282. }
  19283. /**
  19284. * Adds a new instance to the batch using the geometry of the given ID and returns
  19285. * a new id referring to the new instance to be used by other functions.
  19286. *
  19287. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  19288. * @return {number} The instance ID.
  19289. */
  19290. addInstance( geometryId ) {
  19291. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  19292. // ensure we're not over geometry
  19293. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  19294. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  19295. }
  19296. const instanceInfo = {
  19297. visible: true,
  19298. active: true,
  19299. geometryIndex: geometryId,
  19300. };
  19301. let drawId = null;
  19302. // Prioritize using previously freed instance ids
  19303. if ( this._availableInstanceIds.length > 0 ) {
  19304. this._availableInstanceIds.sort( ascIdSort );
  19305. drawId = this._availableInstanceIds.shift();
  19306. this._instanceInfo[ drawId ] = instanceInfo;
  19307. } else {
  19308. drawId = this._instanceInfo.length;
  19309. this._instanceInfo.push( instanceInfo );
  19310. }
  19311. const matricesTexture = this._matricesTexture;
  19312. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  19313. matricesTexture.needsUpdate = true;
  19314. const colorsTexture = this._colorsTexture;
  19315. if ( colorsTexture ) {
  19316. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  19317. colorsTexture.needsUpdate = true;
  19318. }
  19319. this._visibilityChanged = true;
  19320. return drawId;
  19321. }
  19322. /**
  19323. * Adds the given geometry to the batch and returns the associated
  19324. * geometry id referring to it to be used in other functions.
  19325. *
  19326. * @param {BufferGeometry} geometry - The geometry to add.
  19327. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  19328. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  19329. * to set a new geometry at this index at a later time that is larger than the original geometry.
  19330. * Defaults to the length of the given geometry vertex buffer.
  19331. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  19332. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  19333. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  19334. * the length of the given geometry index buffer.
  19335. * @return {number} The geometry ID.
  19336. */
  19337. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  19338. this._initializeGeometry( geometry );
  19339. this._validateGeometry( geometry );
  19340. const geometryInfo = {
  19341. // geometry information
  19342. vertexStart: -1,
  19343. vertexCount: -1,
  19344. reservedVertexCount: -1,
  19345. indexStart: -1,
  19346. indexCount: -1,
  19347. reservedIndexCount: -1,
  19348. // draw range information
  19349. start: -1,
  19350. count: -1,
  19351. // state
  19352. boundingBox: null,
  19353. boundingSphere: null,
  19354. active: true,
  19355. };
  19356. const geometryInfoList = this._geometryInfo;
  19357. geometryInfo.vertexStart = this._nextVertexStart;
  19358. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  19359. const index = geometry.getIndex();
  19360. const hasIndex = index !== null;
  19361. if ( hasIndex ) {
  19362. geometryInfo.indexStart = this._nextIndexStart;
  19363. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  19364. }
  19365. if (
  19366. geometryInfo.indexStart !== -1 &&
  19367. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  19368. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  19369. ) {
  19370. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19371. }
  19372. // update id
  19373. let geometryId;
  19374. if ( this._availableGeometryIds.length > 0 ) {
  19375. this._availableGeometryIds.sort( ascIdSort );
  19376. geometryId = this._availableGeometryIds.shift();
  19377. geometryInfoList[ geometryId ] = geometryInfo;
  19378. } else {
  19379. geometryId = this._geometryCount;
  19380. this._geometryCount ++;
  19381. geometryInfoList.push( geometryInfo );
  19382. }
  19383. // update the geometry
  19384. this.setGeometryAt( geometryId, geometry );
  19385. // increment the next geometry position
  19386. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  19387. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  19388. return geometryId;
  19389. }
  19390. /**
  19391. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  19392. * is not enough space reserved for geometry. Calling this will change all instances that are
  19393. * rendering that geometry.
  19394. *
  19395. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  19396. * @param {BufferGeometry} geometry - The new geometry.
  19397. * @return {number} The geometry ID.
  19398. */
  19399. setGeometryAt( geometryId, geometry ) {
  19400. if ( geometryId >= this._geometryCount ) {
  19401. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  19402. }
  19403. this._validateGeometry( geometry );
  19404. const batchGeometry = this.geometry;
  19405. const hasIndex = batchGeometry.getIndex() !== null;
  19406. const dstIndex = batchGeometry.getIndex();
  19407. const srcIndex = geometry.getIndex();
  19408. const geometryInfo = this._geometryInfo[ geometryId ];
  19409. if (
  19410. hasIndex &&
  19411. srcIndex.count > geometryInfo.reservedIndexCount ||
  19412. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  19413. ) {
  19414. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  19415. }
  19416. // copy geometry buffer data over
  19417. const vertexStart = geometryInfo.vertexStart;
  19418. const reservedVertexCount = geometryInfo.reservedVertexCount;
  19419. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  19420. for ( const attributeName in batchGeometry.attributes ) {
  19421. // copy attribute data
  19422. const srcAttribute = geometry.getAttribute( attributeName );
  19423. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19424. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19425. // fill the rest in with zeroes
  19426. const itemSize = srcAttribute.itemSize;
  19427. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  19428. const index = vertexStart + i;
  19429. for ( let c = 0; c < itemSize; c ++ ) {
  19430. dstAttribute.setComponent( index, c, 0 );
  19431. }
  19432. }
  19433. dstAttribute.needsUpdate = true;
  19434. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  19435. }
  19436. // copy index
  19437. if ( hasIndex ) {
  19438. const indexStart = geometryInfo.indexStart;
  19439. const reservedIndexCount = geometryInfo.reservedIndexCount;
  19440. geometryInfo.indexCount = geometry.getIndex().count;
  19441. // copy index data over
  19442. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19443. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19444. }
  19445. // fill the rest in with zeroes
  19446. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  19447. dstIndex.setX( indexStart + i, vertexStart );
  19448. }
  19449. dstIndex.needsUpdate = true;
  19450. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  19451. }
  19452. // update the draw range
  19453. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19454. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  19455. // store the bounding boxes
  19456. geometryInfo.boundingBox = null;
  19457. if ( geometry.boundingBox !== null ) {
  19458. geometryInfo.boundingBox = geometry.boundingBox.clone();
  19459. }
  19460. geometryInfo.boundingSphere = null;
  19461. if ( geometry.boundingSphere !== null ) {
  19462. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  19463. }
  19464. this._visibilityChanged = true;
  19465. return geometryId;
  19466. }
  19467. /**
  19468. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  19469. * this geometry will also be removed as a side effect.
  19470. *
  19471. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  19472. * @return {BatchedMesh} A reference to this batched mesh.
  19473. */
  19474. deleteGeometry( geometryId ) {
  19475. const geometryInfoList = this._geometryInfo;
  19476. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19477. return this;
  19478. }
  19479. // delete any instances associated with this geometry
  19480. const instanceInfo = this._instanceInfo;
  19481. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19482. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  19483. this.deleteInstance( i );
  19484. }
  19485. }
  19486. geometryInfoList[ geometryId ].active = false;
  19487. this._availableGeometryIds.push( geometryId );
  19488. this._visibilityChanged = true;
  19489. return this;
  19490. }
  19491. /**
  19492. * Deletes an existing instance from the batch using the given ID.
  19493. *
  19494. * @param {number} instanceId - The ID of the instance to remove from the batch.
  19495. * @return {BatchedMesh} A reference to this batched mesh.
  19496. */
  19497. deleteInstance( instanceId ) {
  19498. this.validateInstanceId( instanceId );
  19499. this._instanceInfo[ instanceId ].active = false;
  19500. this._availableInstanceIds.push( instanceId );
  19501. this._visibilityChanged = true;
  19502. return this;
  19503. }
  19504. /**
  19505. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  19506. * previously deleted geometry, freeing up space to add new geometry.
  19507. *
  19508. * @return {BatchedMesh} A reference to this batched mesh.
  19509. */
  19510. optimize() {
  19511. // track the next indices to copy data to
  19512. let nextVertexStart = 0;
  19513. let nextIndexStart = 0;
  19514. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  19515. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  19516. const geometryInfoList = this._geometryInfo;
  19517. const indices = geometryInfoList
  19518. .map( ( e, i ) => i )
  19519. .sort( ( a, b ) => {
  19520. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  19521. } );
  19522. const geometry = this.geometry;
  19523. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  19524. // if a geometry range is inactive then don't copy anything
  19525. const index = indices[ i ];
  19526. const geometryInfo = geometryInfoList[ index ];
  19527. if ( geometryInfo.active === false ) {
  19528. continue;
  19529. }
  19530. // if a geometry contains an index buffer then shift it, as well
  19531. if ( geometry.index !== null ) {
  19532. if ( geometryInfo.indexStart !== nextIndexStart ) {
  19533. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  19534. const index = geometry.index;
  19535. const array = index.array;
  19536. // shift the index pointers based on how the vertex data will shift
  19537. // adjusting the index must happen first so the original vertex start value is available
  19538. const elementDelta = nextVertexStart - vertexStart;
  19539. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  19540. array[ j ] = array[ j ] + elementDelta;
  19541. }
  19542. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  19543. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  19544. index.needsUpdate = true;
  19545. geometryInfo.indexStart = nextIndexStart;
  19546. }
  19547. nextIndexStart += geometryInfo.reservedIndexCount;
  19548. }
  19549. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  19550. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  19551. const { vertexStart, reservedVertexCount } = geometryInfo;
  19552. const attributes = geometry.attributes;
  19553. for ( const key in attributes ) {
  19554. const attribute = attributes[ key ];
  19555. const { array, itemSize } = attribute;
  19556. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  19557. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  19558. attribute.needsUpdate = true;
  19559. }
  19560. geometryInfo.vertexStart = nextVertexStart;
  19561. }
  19562. nextVertexStart += geometryInfo.reservedVertexCount;
  19563. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19564. }
  19565. this._nextIndexStart = nextIndexStart;
  19566. this._nextVertexStart = nextVertexStart;
  19567. this._visibilityChanged = true;
  19568. return this;
  19569. }
  19570. /**
  19571. * Returns the bounding box for the given geometry.
  19572. *
  19573. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  19574. * @param {Box3} target - The target object that is used to store the method's result.
  19575. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  19576. */
  19577. getBoundingBoxAt( geometryId, target ) {
  19578. if ( geometryId >= this._geometryCount ) {
  19579. return null;
  19580. }
  19581. // compute bounding box
  19582. const geometry = this.geometry;
  19583. const geometryInfo = this._geometryInfo[ geometryId ];
  19584. if ( geometryInfo.boundingBox === null ) {
  19585. const box = new Box3();
  19586. const index = geometry.index;
  19587. const position = geometry.attributes.position;
  19588. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19589. let iv = i;
  19590. if ( index ) {
  19591. iv = index.getX( iv );
  19592. }
  19593. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  19594. }
  19595. geometryInfo.boundingBox = box;
  19596. }
  19597. target.copy( geometryInfo.boundingBox );
  19598. return target;
  19599. }
  19600. /**
  19601. * Returns the bounding sphere for the given geometry.
  19602. *
  19603. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  19604. * @param {Sphere} target - The target object that is used to store the method's result.
  19605. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  19606. */
  19607. getBoundingSphereAt( geometryId, target ) {
  19608. if ( geometryId >= this._geometryCount ) {
  19609. return null;
  19610. }
  19611. // compute bounding sphere
  19612. const geometry = this.geometry;
  19613. const geometryInfo = this._geometryInfo[ geometryId ];
  19614. if ( geometryInfo.boundingSphere === null ) {
  19615. const sphere = new Sphere();
  19616. this.getBoundingBoxAt( geometryId, _box$1 );
  19617. _box$1.getCenter( sphere.center );
  19618. const index = geometry.index;
  19619. const position = geometry.attributes.position;
  19620. let maxRadiusSq = 0;
  19621. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19622. let iv = i;
  19623. if ( index ) {
  19624. iv = index.getX( iv );
  19625. }
  19626. _vector$5.fromBufferAttribute( position, iv );
  19627. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  19628. }
  19629. sphere.radius = Math.sqrt( maxRadiusSq );
  19630. geometryInfo.boundingSphere = sphere;
  19631. }
  19632. target.copy( geometryInfo.boundingSphere );
  19633. return target;
  19634. }
  19635. /**
  19636. * Sets the given local transformation matrix to the defined instance.
  19637. * Negatively scaled matrices are not supported.
  19638. *
  19639. * @param {number} instanceId - The ID of an instance to set the matrix of.
  19640. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  19641. * @return {BatchedMesh} A reference to this batched mesh.
  19642. */
  19643. setMatrixAt( instanceId, matrix ) {
  19644. this.validateInstanceId( instanceId );
  19645. const matricesTexture = this._matricesTexture;
  19646. const matricesArray = this._matricesTexture.image.data;
  19647. matrix.toArray( matricesArray, instanceId * 16 );
  19648. matricesTexture.needsUpdate = true;
  19649. return this;
  19650. }
  19651. /**
  19652. * Returns the local transformation matrix of the defined instance.
  19653. *
  19654. * @param {number} instanceId - The ID of an instance to get the matrix of.
  19655. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19656. * @return {Matrix4} The instance's local transformation matrix.
  19657. */
  19658. getMatrixAt( instanceId, matrix ) {
  19659. this.validateInstanceId( instanceId );
  19660. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  19661. }
  19662. /**
  19663. * Sets the given color to the defined instance.
  19664. *
  19665. * @param {number} instanceId - The ID of an instance to set the color of.
  19666. * @param {Color|Vector4} color - The color to set the instance to. Use a `Vector4` to also define alpha.
  19667. * @return {BatchedMesh} A reference to this batched mesh.
  19668. */
  19669. setColorAt( instanceId, color ) {
  19670. this.validateInstanceId( instanceId );
  19671. if ( this._colorsTexture === null ) {
  19672. this._initColorsTexture();
  19673. }
  19674. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  19675. this._colorsTexture.needsUpdate = true;
  19676. return this;
  19677. }
  19678. /**
  19679. * Returns the color of the defined instance.
  19680. *
  19681. * @param {number} instanceId - The ID of an instance to get the color of.
  19682. * @param {Color|Vector4} color - The target object that is used to store the method's result.
  19683. * @return {Color|Vector4} The instance's color. Use a `Vector4` to also retrieve alpha.
  19684. */
  19685. getColorAt( instanceId, color ) {
  19686. this.validateInstanceId( instanceId );
  19687. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  19688. }
  19689. /**
  19690. * Sets the visibility of the instance.
  19691. *
  19692. * @param {number} instanceId - The id of the instance to set the visibility of.
  19693. * @param {boolean} visible - Whether the instance is visible or not.
  19694. * @return {BatchedMesh} A reference to this batched mesh.
  19695. */
  19696. setVisibleAt( instanceId, visible ) {
  19697. this.validateInstanceId( instanceId );
  19698. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  19699. return this;
  19700. }
  19701. this._instanceInfo[ instanceId ].visible = visible;
  19702. this._visibilityChanged = true;
  19703. return this;
  19704. }
  19705. /**
  19706. * Returns the visibility state of the defined instance.
  19707. *
  19708. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  19709. * @return {boolean} Whether the instance is visible or not.
  19710. */
  19711. getVisibleAt( instanceId ) {
  19712. this.validateInstanceId( instanceId );
  19713. return this._instanceInfo[ instanceId ].visible;
  19714. }
  19715. /**
  19716. * Sets the geometry ID of the instance at the given index.
  19717. *
  19718. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  19719. * @param {number} geometryId - The geometry ID to be use by the instance.
  19720. * @return {BatchedMesh} A reference to this batched mesh.
  19721. */
  19722. setGeometryIdAt( instanceId, geometryId ) {
  19723. this.validateInstanceId( instanceId );
  19724. this.validateGeometryId( geometryId );
  19725. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  19726. return this;
  19727. }
  19728. /**
  19729. * Returns the geometry ID of the defined instance.
  19730. *
  19731. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  19732. * @return {number} The instance's geometry ID.
  19733. */
  19734. getGeometryIdAt( instanceId ) {
  19735. this.validateInstanceId( instanceId );
  19736. return this._instanceInfo[ instanceId ].geometryIndex;
  19737. }
  19738. /**
  19739. * Get the range representing the subset of triangles related to the attached geometry,
  19740. * indicating the starting offset and count, or `null` if invalid.
  19741. *
  19742. * @param {number} geometryId - The id of the geometry to get the range of.
  19743. * @param {Object} [target] - The target object that is used to store the method's result.
  19744. * @return {{
  19745. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  19746. * indexStart:number,indexCount:number,reservedIndexCount:number,
  19747. * start:number,count:number
  19748. * }} The result object with range data.
  19749. */
  19750. getGeometryRangeAt( geometryId, target = {} ) {
  19751. this.validateGeometryId( geometryId );
  19752. const geometryInfo = this._geometryInfo[ geometryId ];
  19753. target.vertexStart = geometryInfo.vertexStart;
  19754. target.vertexCount = geometryInfo.vertexCount;
  19755. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  19756. target.indexStart = geometryInfo.indexStart;
  19757. target.indexCount = geometryInfo.indexCount;
  19758. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  19759. target.start = geometryInfo.start;
  19760. target.count = geometryInfo.count;
  19761. return target;
  19762. }
  19763. /**
  19764. * Resizes the necessary buffers to support the provided number of instances.
  19765. * If the provided arguments shrink the number of instances but there are not enough
  19766. * unused Ids at the end of the list then an error is thrown.
  19767. *
  19768. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  19769. */
  19770. setInstanceCount( maxInstanceCount ) {
  19771. // shrink the available instances as much as possible
  19772. const availableInstanceIds = this._availableInstanceIds;
  19773. const instanceInfo = this._instanceInfo;
  19774. availableInstanceIds.sort( ascIdSort );
  19775. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  19776. instanceInfo.pop();
  19777. availableInstanceIds.pop();
  19778. }
  19779. // throw an error if it can't be shrunk to the desired size
  19780. if ( maxInstanceCount < instanceInfo.length ) {
  19781. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  19782. }
  19783. // copy the multi draw counts
  19784. const multiDrawCounts = new Int32Array( maxInstanceCount );
  19785. const multiDrawStarts = new Int32Array( maxInstanceCount );
  19786. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  19787. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  19788. this._multiDrawCounts = multiDrawCounts;
  19789. this._multiDrawStarts = multiDrawStarts;
  19790. this._maxInstanceCount = maxInstanceCount;
  19791. // update texture data for instance sampling
  19792. const indirectTexture = this._indirectTexture;
  19793. const matricesTexture = this._matricesTexture;
  19794. const colorsTexture = this._colorsTexture;
  19795. indirectTexture.dispose();
  19796. this._initIndirectTexture();
  19797. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  19798. matricesTexture.dispose();
  19799. this._initMatricesTexture();
  19800. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  19801. if ( colorsTexture ) {
  19802. colorsTexture.dispose();
  19803. this._initColorsTexture();
  19804. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  19805. }
  19806. }
  19807. /**
  19808. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  19809. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  19810. * end of the geometry attributes then an error is thrown.
  19811. *
  19812. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  19813. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  19814. */
  19815. setGeometrySize( maxVertexCount, maxIndexCount ) {
  19816. // Check if we can shrink to the requested vertex attribute size
  19817. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  19818. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  19819. if ( requiredVertexLength > maxVertexCount ) {
  19820. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  19821. }
  19822. // Check if we can shrink to the requested index attribute size
  19823. if ( this.geometry.index ) {
  19824. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  19825. if ( requiredIndexLength > maxIndexCount ) {
  19826. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  19827. }
  19828. }
  19829. //
  19830. // dispose of the previous geometry
  19831. const oldGeometry = this.geometry;
  19832. oldGeometry.dispose();
  19833. // recreate the geometry needed based on the previous variant
  19834. this._maxVertexCount = maxVertexCount;
  19835. this._maxIndexCount = maxIndexCount;
  19836. if ( this._geometryInitialized ) {
  19837. this._geometryInitialized = false;
  19838. this.geometry = new BufferGeometry();
  19839. this._initializeGeometry( oldGeometry );
  19840. }
  19841. // copy data from the previous geometry
  19842. const geometry = this.geometry;
  19843. if ( oldGeometry.index ) {
  19844. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  19845. }
  19846. for ( const key in oldGeometry.attributes ) {
  19847. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  19848. }
  19849. }
  19850. raycast( raycaster, intersects ) {
  19851. const instanceInfo = this._instanceInfo;
  19852. const geometryInfoList = this._geometryInfo;
  19853. const matrixWorld = this.matrixWorld;
  19854. const batchGeometry = this.geometry;
  19855. // iterate over each geometry
  19856. _mesh.material = this.material;
  19857. _mesh.geometry.index = batchGeometry.index;
  19858. _mesh.geometry.attributes = batchGeometry.attributes;
  19859. if ( _mesh.geometry.boundingBox === null ) {
  19860. _mesh.geometry.boundingBox = new Box3();
  19861. }
  19862. if ( _mesh.geometry.boundingSphere === null ) {
  19863. _mesh.geometry.boundingSphere = new Sphere();
  19864. }
  19865. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19866. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  19867. continue;
  19868. }
  19869. const geometryId = instanceInfo[ i ].geometryIndex;
  19870. const geometryInfo = geometryInfoList[ geometryId ];
  19871. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  19872. // get the intersects
  19873. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  19874. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  19875. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  19876. _mesh.raycast( raycaster, _batchIntersects );
  19877. // add batch id to the intersects
  19878. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  19879. const intersect = _batchIntersects[ j ];
  19880. intersect.object = this;
  19881. intersect.batchId = i;
  19882. intersects.push( intersect );
  19883. }
  19884. _batchIntersects.length = 0;
  19885. }
  19886. _mesh.material = null;
  19887. _mesh.geometry.index = null;
  19888. _mesh.geometry.attributes = {};
  19889. _mesh.geometry.setDrawRange( 0, Infinity );
  19890. }
  19891. copy( source ) {
  19892. super.copy( source );
  19893. this.geometry = source.geometry.clone();
  19894. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  19895. this.sortObjects = source.sortObjects;
  19896. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  19897. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  19898. this._geometryInfo = source._geometryInfo.map( info => ( {
  19899. ...info,
  19900. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  19901. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  19902. } ) );
  19903. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  19904. this._availableInstanceIds = source._availableInstanceIds.slice();
  19905. this._availableGeometryIds = source._availableGeometryIds.slice();
  19906. this._nextIndexStart = source._nextIndexStart;
  19907. this._nextVertexStart = source._nextVertexStart;
  19908. this._geometryCount = source._geometryCount;
  19909. this._maxInstanceCount = source._maxInstanceCount;
  19910. this._maxVertexCount = source._maxVertexCount;
  19911. this._maxIndexCount = source._maxIndexCount;
  19912. this._geometryInitialized = source._geometryInitialized;
  19913. this._multiDrawCounts = source._multiDrawCounts.slice();
  19914. this._multiDrawStarts = source._multiDrawStarts.slice();
  19915. this._indirectTexture = source._indirectTexture.clone();
  19916. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  19917. this._matricesTexture = source._matricesTexture.clone();
  19918. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  19919. if ( this._colorsTexture !== null ) {
  19920. this._colorsTexture = source._colorsTexture.clone();
  19921. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  19922. }
  19923. return this;
  19924. }
  19925. /**
  19926. * Frees the GPU-related resources allocated by this instance. Call this
  19927. * method whenever this instance is no longer used in your app.
  19928. */
  19929. dispose() {
  19930. // Assuming the geometry is not shared with other meshes
  19931. this.geometry.dispose();
  19932. this._matricesTexture.dispose();
  19933. this._matricesTexture = null;
  19934. this._indirectTexture.dispose();
  19935. this._indirectTexture = null;
  19936. if ( this._colorsTexture !== null ) {
  19937. this._colorsTexture.dispose();
  19938. this._colorsTexture = null;
  19939. }
  19940. }
  19941. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  19942. // if visibility has not changed and frustum culling and object sorting is not required
  19943. // then skip iterating over all items
  19944. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  19945. return;
  19946. }
  19947. // the indexed version of the multi draw function requires specifying the start
  19948. // offset in bytes.
  19949. const index = geometry.getIndex();
  19950. let bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  19951. // the "wireframe" attribute implicitly creates a line attribute in the renderer, which is double
  19952. // the vertices to draw (3 lines per triangle) so we multiply the draw counts / starts and make
  19953. // assumptions about the index buffer byte size.
  19954. let multiDrawMultiplier = 1;
  19955. if ( material.wireframe ) {
  19956. multiDrawMultiplier = 2;
  19957. bytesPerElement = geometry.attributes.position.count > 65535 ? 4 : 2;
  19958. }
  19959. const instanceInfo = this._instanceInfo;
  19960. const multiDrawStarts = this._multiDrawStarts;
  19961. const multiDrawCounts = this._multiDrawCounts;
  19962. const geometryInfoList = this._geometryInfo;
  19963. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  19964. const indirectTexture = this._indirectTexture;
  19965. const indirectArray = indirectTexture.image.data;
  19966. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  19967. // prepare the frustum in the local frame
  19968. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  19969. _matrix$1
  19970. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  19971. .multiply( this.matrixWorld );
  19972. _frustum.setFromProjectionMatrix(
  19973. _matrix$1,
  19974. camera.coordinateSystem,
  19975. camera.reversedDepth
  19976. );
  19977. }
  19978. let multiDrawCount = 0;
  19979. if ( this.sortObjects ) {
  19980. // get the camera position in the local frame
  19981. _matrix$1.copy( this.matrixWorld ).invert();
  19982. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  19983. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  19984. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19985. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  19986. const geometryId = instanceInfo[ i ].geometryIndex;
  19987. // get the bounds in world space
  19988. this.getMatrixAt( i, _matrix$1 );
  19989. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  19990. // determine whether the batched geometry is within the frustum
  19991. let culled = false;
  19992. if ( perObjectFrustumCulled ) {
  19993. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  19994. }
  19995. if ( ! culled ) {
  19996. // get the distance from camera used for sorting
  19997. const geometryInfo = geometryInfoList[ geometryId ];
  19998. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  19999. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20000. }
  20001. }
  20002. }
  20003. // Sort the draw ranges and prep for rendering
  20004. const list = _renderList.list;
  20005. const customSort = this.customSort;
  20006. if ( customSort === null ) {
  20007. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20008. } else {
  20009. customSort.call( this, list, camera );
  20010. }
  20011. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20012. const item = list[ i ];
  20013. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement * multiDrawMultiplier;
  20014. multiDrawCounts[ multiDrawCount ] = item.count * multiDrawMultiplier;
  20015. indirectArray[ multiDrawCount ] = item.index;
  20016. multiDrawCount ++;
  20017. }
  20018. _renderList.reset();
  20019. } else {
  20020. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20021. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20022. const geometryId = instanceInfo[ i ].geometryIndex;
  20023. // determine whether the batched geometry is within the frustum
  20024. let culled = false;
  20025. if ( perObjectFrustumCulled ) {
  20026. // get the bounds in world space
  20027. this.getMatrixAt( i, _matrix$1 );
  20028. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20029. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20030. }
  20031. if ( ! culled ) {
  20032. const geometryInfo = geometryInfoList[ geometryId ];
  20033. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement * multiDrawMultiplier;
  20034. multiDrawCounts[ multiDrawCount ] = geometryInfo.count * multiDrawMultiplier;
  20035. indirectArray[ multiDrawCount ] = i;
  20036. multiDrawCount ++;
  20037. }
  20038. }
  20039. }
  20040. }
  20041. indirectTexture.needsUpdate = true;
  20042. this._multiDrawCount = multiDrawCount;
  20043. this._visibilityChanged = false;
  20044. }
  20045. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20046. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20047. }
  20048. }
  20049. /**
  20050. * A material for rendering line primitives.
  20051. *
  20052. * Materials define the appearance of renderable 3D objects.
  20053. *
  20054. * ```js
  20055. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20056. * ```
  20057. *
  20058. * @augments Material
  20059. */
  20060. class LineBasicMaterial extends Material {
  20061. /**
  20062. * Constructs a new line basic material.
  20063. *
  20064. * @param {Object} [parameters] - An object with one or more properties
  20065. * defining the material's appearance. Any property of the material
  20066. * (including any property from inherited materials) can be passed
  20067. * in here. Color values can be passed any type of value accepted
  20068. * by {@link Color#set}.
  20069. */
  20070. constructor( parameters ) {
  20071. super();
  20072. /**
  20073. * This flag can be used for type testing.
  20074. *
  20075. * @type {boolean}
  20076. * @readonly
  20077. * @default true
  20078. */
  20079. this.isLineBasicMaterial = true;
  20080. this.type = 'LineBasicMaterial';
  20081. /**
  20082. * Color of the material.
  20083. *
  20084. * @type {Color}
  20085. * @default (1,1,1)
  20086. */
  20087. this.color = new Color( 0xffffff );
  20088. /**
  20089. * Sets the color of the lines using data from a texture. The texture map
  20090. * color is modulated by the diffuse `color`.
  20091. *
  20092. * @type {?Texture}
  20093. * @default null
  20094. */
  20095. this.map = null;
  20096. /**
  20097. * Controls line thickness or lines.
  20098. *
  20099. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20100. * ignore this setting and always render line primitives with a
  20101. * width of one pixel.
  20102. *
  20103. * @type {number}
  20104. * @default 1
  20105. */
  20106. this.linewidth = 1;
  20107. /**
  20108. * Defines appearance of line ends.
  20109. *
  20110. * Can only be used with {@link SVGRenderer}.
  20111. *
  20112. * @type {('butt'|'round'|'square')}
  20113. * @default 'round'
  20114. */
  20115. this.linecap = 'round';
  20116. /**
  20117. * Defines appearance of line joints.
  20118. *
  20119. * Can only be used with {@link SVGRenderer}.
  20120. *
  20121. * @type {('round'|'bevel'|'miter')}
  20122. * @default 'round'
  20123. */
  20124. this.linejoin = 'round';
  20125. /**
  20126. * Whether the material is affected by fog or not.
  20127. *
  20128. * @type {boolean}
  20129. * @default true
  20130. */
  20131. this.fog = true;
  20132. this.setValues( parameters );
  20133. }
  20134. copy( source ) {
  20135. super.copy( source );
  20136. this.color.copy( source.color );
  20137. this.map = source.map;
  20138. this.linewidth = source.linewidth;
  20139. this.linecap = source.linecap;
  20140. this.linejoin = source.linejoin;
  20141. this.fog = source.fog;
  20142. return this;
  20143. }
  20144. }
  20145. const _vStart = /*@__PURE__*/ new Vector3();
  20146. const _vEnd = /*@__PURE__*/ new Vector3();
  20147. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20148. const _ray$1 = /*@__PURE__*/ new Ray();
  20149. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20150. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20151. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20152. /**
  20153. * A continuous line. The line are rendered by connecting consecutive
  20154. * vertices with straight lines.
  20155. *
  20156. * ```js
  20157. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  20158. *
  20159. * const points = [];
  20160. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  20161. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  20162. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  20163. *
  20164. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  20165. *
  20166. * const line = new THREE.Line( geometry, material );
  20167. * scene.add( line );
  20168. * ```
  20169. *
  20170. * @augments Object3D
  20171. */
  20172. class Line extends Object3D {
  20173. /**
  20174. * Constructs a new line.
  20175. *
  20176. * @param {BufferGeometry} [geometry] - The line geometry.
  20177. * @param {Material|Array<Material>} [material] - The line material.
  20178. */
  20179. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20180. super();
  20181. /**
  20182. * This flag can be used for type testing.
  20183. *
  20184. * @type {boolean}
  20185. * @readonly
  20186. * @default true
  20187. */
  20188. this.isLine = true;
  20189. this.type = 'Line';
  20190. /**
  20191. * The line geometry.
  20192. *
  20193. * @type {BufferGeometry}
  20194. */
  20195. this.geometry = geometry;
  20196. /**
  20197. * The line material.
  20198. *
  20199. * @type {Material|Array<Material>}
  20200. * @default LineBasicMaterial
  20201. */
  20202. this.material = material;
  20203. /**
  20204. * A dictionary representing the morph targets in the geometry. The key is the
  20205. * morph targets name, the value its attribute index. This member is `undefined`
  20206. * by default and only set when morph targets are detected in the geometry.
  20207. *
  20208. * @type {Object<string,number>|undefined}
  20209. * @default undefined
  20210. */
  20211. this.morphTargetDictionary = undefined;
  20212. /**
  20213. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20214. * is applied. This member is `undefined` by default and only set when morph targets are
  20215. * detected in the geometry.
  20216. *
  20217. * @type {Array<number>|undefined}
  20218. * @default undefined
  20219. */
  20220. this.morphTargetInfluences = undefined;
  20221. this.updateMorphTargets();
  20222. }
  20223. copy( source, recursive ) {
  20224. super.copy( source, recursive );
  20225. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20226. this.geometry = source.geometry;
  20227. return this;
  20228. }
  20229. /**
  20230. * Computes an array of distance values which are necessary for rendering dashed lines.
  20231. * For each vertex in the geometry, the method calculates the cumulative length from the
  20232. * current point to the very beginning of the line.
  20233. *
  20234. * @return {Line} A reference to this line.
  20235. */
  20236. computeLineDistances() {
  20237. const geometry = this.geometry;
  20238. // we assume non-indexed geometry
  20239. if ( geometry.index === null ) {
  20240. const positionAttribute = geometry.attributes.position;
  20241. const lineDistances = [ 0 ];
  20242. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20243. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20244. _vEnd.fromBufferAttribute( positionAttribute, i );
  20245. lineDistances[ i ] = lineDistances[ i - 1 ];
  20246. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20247. }
  20248. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20249. } else {
  20250. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20251. }
  20252. return this;
  20253. }
  20254. /**
  20255. * Computes intersection points between a casted ray and this line.
  20256. *
  20257. * @param {Raycaster} raycaster - The raycaster.
  20258. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20259. */
  20260. raycast( raycaster, intersects ) {
  20261. const geometry = this.geometry;
  20262. const matrixWorld = this.matrixWorld;
  20263. const threshold = raycaster.params.Line.threshold;
  20264. const drawRange = geometry.drawRange;
  20265. // Checking boundingSphere distance to ray
  20266. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20267. _sphere$1.copy( geometry.boundingSphere );
  20268. _sphere$1.applyMatrix4( matrixWorld );
  20269. _sphere$1.radius += threshold;
  20270. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20271. //
  20272. _inverseMatrix$1.copy( matrixWorld ).invert();
  20273. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20274. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20275. const localThresholdSq = localThreshold * localThreshold;
  20276. const step = this.isLineSegments ? 2 : 1;
  20277. const index = geometry.index;
  20278. const attributes = geometry.attributes;
  20279. const positionAttribute = attributes.position;
  20280. if ( index !== null ) {
  20281. const start = Math.max( 0, drawRange.start );
  20282. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20283. for ( let i = start, l = end - 1; i < l; i += step ) {
  20284. const a = index.getX( i );
  20285. const b = index.getX( i + 1 );
  20286. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  20287. if ( intersect ) {
  20288. intersects.push( intersect );
  20289. }
  20290. }
  20291. if ( this.isLineLoop ) {
  20292. const a = index.getX( end - 1 );
  20293. const b = index.getX( start );
  20294. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  20295. if ( intersect ) {
  20296. intersects.push( intersect );
  20297. }
  20298. }
  20299. } else {
  20300. const start = Math.max( 0, drawRange.start );
  20301. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20302. for ( let i = start, l = end - 1; i < l; i += step ) {
  20303. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  20304. if ( intersect ) {
  20305. intersects.push( intersect );
  20306. }
  20307. }
  20308. if ( this.isLineLoop ) {
  20309. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  20310. if ( intersect ) {
  20311. intersects.push( intersect );
  20312. }
  20313. }
  20314. }
  20315. }
  20316. /**
  20317. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  20318. * to make sure existing morph targets can influence this 3D object.
  20319. */
  20320. updateMorphTargets() {
  20321. const geometry = this.geometry;
  20322. const morphAttributes = geometry.morphAttributes;
  20323. const keys = Object.keys( morphAttributes );
  20324. if ( keys.length > 0 ) {
  20325. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20326. if ( morphAttribute !== undefined ) {
  20327. this.morphTargetInfluences = [];
  20328. this.morphTargetDictionary = {};
  20329. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20330. const name = morphAttribute[ m ].name || String( m );
  20331. this.morphTargetInfluences.push( 0 );
  20332. this.morphTargetDictionary[ name ] = m;
  20333. }
  20334. }
  20335. }
  20336. }
  20337. }
  20338. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  20339. const positionAttribute = object.geometry.attributes.position;
  20340. _vStart.fromBufferAttribute( positionAttribute, a );
  20341. _vEnd.fromBufferAttribute( positionAttribute, b );
  20342. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  20343. if ( distSq > thresholdSq ) return;
  20344. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  20345. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  20346. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20347. return {
  20348. distance: distance,
  20349. // What do we want? intersection point on the ray or on the segment??
  20350. // point: raycaster.ray.at( distance ),
  20351. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  20352. index: i,
  20353. face: null,
  20354. faceIndex: null,
  20355. barycoord: null,
  20356. object: object
  20357. };
  20358. }
  20359. const _start = /*@__PURE__*/ new Vector3();
  20360. const _end = /*@__PURE__*/ new Vector3();
  20361. /**
  20362. * A series of lines drawn between pairs of vertices.
  20363. *
  20364. * @augments Line
  20365. */
  20366. class LineSegments extends Line {
  20367. /**
  20368. * Constructs a new line segments.
  20369. *
  20370. * @param {BufferGeometry} [geometry] - The line geometry.
  20371. * @param {Material|Array<Material>} [material] - The line material.
  20372. */
  20373. constructor( geometry, material ) {
  20374. super( geometry, material );
  20375. /**
  20376. * This flag can be used for type testing.
  20377. *
  20378. * @type {boolean}
  20379. * @readonly
  20380. * @default true
  20381. */
  20382. this.isLineSegments = true;
  20383. this.type = 'LineSegments';
  20384. }
  20385. computeLineDistances() {
  20386. const geometry = this.geometry;
  20387. // we assume non-indexed geometry
  20388. if ( geometry.index === null ) {
  20389. const positionAttribute = geometry.attributes.position;
  20390. const lineDistances = [];
  20391. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20392. _start.fromBufferAttribute( positionAttribute, i );
  20393. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20394. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20395. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20396. }
  20397. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20398. } else {
  20399. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20400. }
  20401. return this;
  20402. }
  20403. }
  20404. /**
  20405. * A continuous line. This is nearly the same as {@link Line} the only difference
  20406. * is that the last vertex is connected with the first vertex in order to close
  20407. * the line to form a loop.
  20408. *
  20409. * @augments Line
  20410. */
  20411. class LineLoop extends Line {
  20412. /**
  20413. * Constructs a new line loop.
  20414. *
  20415. * @param {BufferGeometry} [geometry] - The line geometry.
  20416. * @param {Material|Array<Material>} [material] - The line material.
  20417. */
  20418. constructor( geometry, material ) {
  20419. super( geometry, material );
  20420. /**
  20421. * This flag can be used for type testing.
  20422. *
  20423. * @type {boolean}
  20424. * @readonly
  20425. * @default true
  20426. */
  20427. this.isLineLoop = true;
  20428. this.type = 'LineLoop';
  20429. }
  20430. }
  20431. /**
  20432. * A material for rendering point primitives.
  20433. *
  20434. * Materials define the appearance of renderable 3D objects.
  20435. *
  20436. * ```js
  20437. * const vertices = [];
  20438. *
  20439. * for ( let i = 0; i < 10000; i ++ ) {
  20440. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  20441. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  20442. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  20443. *
  20444. * vertices.push( x, y, z );
  20445. * }
  20446. *
  20447. * const geometry = new THREE.BufferGeometry();
  20448. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  20449. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  20450. * const points = new THREE.Points( geometry, material );
  20451. * scene.add( points );
  20452. * ```
  20453. *
  20454. * @augments Material
  20455. */
  20456. class PointsMaterial extends Material {
  20457. /**
  20458. * Constructs a new points material.
  20459. *
  20460. * @param {Object} [parameters] - An object with one or more properties
  20461. * defining the material's appearance. Any property of the material
  20462. * (including any property from inherited materials) can be passed
  20463. * in here. Color values can be passed any type of value accepted
  20464. * by {@link Color#set}.
  20465. */
  20466. constructor( parameters ) {
  20467. super();
  20468. /**
  20469. * This flag can be used for type testing.
  20470. *
  20471. * @type {boolean}
  20472. * @readonly
  20473. * @default true
  20474. */
  20475. this.isPointsMaterial = true;
  20476. this.type = 'PointsMaterial';
  20477. /**
  20478. * Color of the material.
  20479. *
  20480. * @type {Color}
  20481. * @default (1,1,1)
  20482. */
  20483. this.color = new Color( 0xffffff );
  20484. /**
  20485. * The color map. May optionally include an alpha channel, typically combined
  20486. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  20487. * color is modulated by the diffuse `color`.
  20488. *
  20489. * @type {?Texture}
  20490. * @default null
  20491. */
  20492. this.map = null;
  20493. /**
  20494. * The alpha map is a grayscale texture that controls the opacity across the
  20495. * surface (black: fully transparent; white: fully opaque).
  20496. *
  20497. * Only the color of the texture is used, ignoring the alpha channel if one
  20498. * exists. For RGB and RGBA textures, the renderer will use the green channel
  20499. * when sampling this texture due to the extra bit of precision provided for
  20500. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  20501. * luminance/alpha textures will also still work as expected.
  20502. *
  20503. * @type {?Texture}
  20504. * @default null
  20505. */
  20506. this.alphaMap = null;
  20507. /**
  20508. * Defines the size of the points in pixels.
  20509. *
  20510. * Might be capped if the value exceeds hardware dependent parameters like [gl.ALIASED_POINT_SIZE_RANGE](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getParamete).
  20511. *
  20512. * @type {number}
  20513. * @default 1
  20514. */
  20515. this.size = 1;
  20516. /**
  20517. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  20518. *
  20519. * @type {boolean}
  20520. * @default true
  20521. */
  20522. this.sizeAttenuation = true;
  20523. /**
  20524. * Whether the material is affected by fog or not.
  20525. *
  20526. * @type {boolean}
  20527. * @default true
  20528. */
  20529. this.fog = true;
  20530. this.setValues( parameters );
  20531. }
  20532. copy( source ) {
  20533. super.copy( source );
  20534. this.color.copy( source.color );
  20535. this.map = source.map;
  20536. this.alphaMap = source.alphaMap;
  20537. this.size = source.size;
  20538. this.sizeAttenuation = source.sizeAttenuation;
  20539. this.fog = source.fog;
  20540. return this;
  20541. }
  20542. }
  20543. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20544. const _ray = /*@__PURE__*/ new Ray();
  20545. const _sphere = /*@__PURE__*/ new Sphere();
  20546. const _position$3 = /*@__PURE__*/ new Vector3();
  20547. /**
  20548. * A class for displaying points or point clouds.
  20549. *
  20550. * @augments Object3D
  20551. */
  20552. class Points extends Object3D {
  20553. /**
  20554. * Constructs a new point cloud.
  20555. *
  20556. * @param {BufferGeometry} [geometry] - The points geometry.
  20557. * @param {Material|Array<Material>} [material] - The points material.
  20558. */
  20559. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20560. super();
  20561. /**
  20562. * This flag can be used for type testing.
  20563. *
  20564. * @type {boolean}
  20565. * @readonly
  20566. * @default true
  20567. */
  20568. this.isPoints = true;
  20569. this.type = 'Points';
  20570. /**
  20571. * The points geometry.
  20572. *
  20573. * @type {BufferGeometry}
  20574. */
  20575. this.geometry = geometry;
  20576. /**
  20577. * The line material.
  20578. *
  20579. * @type {Material|Array<Material>}
  20580. * @default PointsMaterial
  20581. */
  20582. this.material = material;
  20583. /**
  20584. * A dictionary representing the morph targets in the geometry. The key is the
  20585. * morph targets name, the value its attribute index. This member is `undefined`
  20586. * by default and only set when morph targets are detected in the geometry.
  20587. *
  20588. * @type {Object<string,number>|undefined}
  20589. * @default undefined
  20590. */
  20591. this.morphTargetDictionary = undefined;
  20592. /**
  20593. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20594. * is applied. This member is `undefined` by default and only set when morph targets are
  20595. * detected in the geometry.
  20596. *
  20597. * @type {Array<number>|undefined}
  20598. * @default undefined
  20599. */
  20600. this.morphTargetInfluences = undefined;
  20601. this.updateMorphTargets();
  20602. }
  20603. copy( source, recursive ) {
  20604. super.copy( source, recursive );
  20605. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20606. this.geometry = source.geometry;
  20607. return this;
  20608. }
  20609. /**
  20610. * Computes intersection points between a casted ray and this point cloud.
  20611. *
  20612. * @param {Raycaster} raycaster - The raycaster.
  20613. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20614. */
  20615. raycast( raycaster, intersects ) {
  20616. const geometry = this.geometry;
  20617. const matrixWorld = this.matrixWorld;
  20618. const threshold = raycaster.params.Points.threshold;
  20619. const drawRange = geometry.drawRange;
  20620. // Checking boundingSphere distance to ray
  20621. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20622. _sphere.copy( geometry.boundingSphere );
  20623. _sphere.applyMatrix4( matrixWorld );
  20624. _sphere.radius += threshold;
  20625. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20626. //
  20627. _inverseMatrix.copy( matrixWorld ).invert();
  20628. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20629. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20630. const localThresholdSq = localThreshold * localThreshold;
  20631. const index = geometry.index;
  20632. const attributes = geometry.attributes;
  20633. const positionAttribute = attributes.position;
  20634. if ( index !== null ) {
  20635. const start = Math.max( 0, drawRange.start );
  20636. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20637. for ( let i = start, il = end; i < il; i ++ ) {
  20638. const a = index.getX( i );
  20639. _position$3.fromBufferAttribute( positionAttribute, a );
  20640. testPoint( _position$3, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20641. }
  20642. } else {
  20643. const start = Math.max( 0, drawRange.start );
  20644. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20645. for ( let i = start, l = end; i < l; i ++ ) {
  20646. _position$3.fromBufferAttribute( positionAttribute, i );
  20647. testPoint( _position$3, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20648. }
  20649. }
  20650. }
  20651. /**
  20652. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  20653. * to make sure existing morph targets can influence this 3D object.
  20654. */
  20655. updateMorphTargets() {
  20656. const geometry = this.geometry;
  20657. const morphAttributes = geometry.morphAttributes;
  20658. const keys = Object.keys( morphAttributes );
  20659. if ( keys.length > 0 ) {
  20660. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20661. if ( morphAttribute !== undefined ) {
  20662. this.morphTargetInfluences = [];
  20663. this.morphTargetDictionary = {};
  20664. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20665. const name = morphAttribute[ m ].name || String( m );
  20666. this.morphTargetInfluences.push( 0 );
  20667. this.morphTargetDictionary[ name ] = m;
  20668. }
  20669. }
  20670. }
  20671. }
  20672. }
  20673. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20674. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20675. if ( rayPointDistanceSq < localThresholdSq ) {
  20676. const intersectPoint = new Vector3();
  20677. _ray.closestPointToPoint( point, intersectPoint );
  20678. intersectPoint.applyMatrix4( matrixWorld );
  20679. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20680. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20681. intersects.push( {
  20682. distance: distance,
  20683. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20684. point: intersectPoint,
  20685. index: index,
  20686. face: null,
  20687. faceIndex: null,
  20688. barycoord: null,
  20689. object: object
  20690. } );
  20691. }
  20692. }
  20693. /**
  20694. * A texture for use with a video.
  20695. *
  20696. * ```js
  20697. * // assuming you have created a HTML video element with id="video"
  20698. * const video = document.getElementById( 'video' );
  20699. * const texture = new THREE.VideoTexture( video );
  20700. * ```
  20701. *
  20702. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  20703. * set to THREE.SRGBColorSpace.
  20704. *
  20705. * Note: After the initial use of a texture, its dimensions, format, and type
  20706. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  20707. *
  20708. * @augments Texture
  20709. */
  20710. class VideoTexture extends Texture {
  20711. /**
  20712. * Constructs a new video texture.
  20713. *
  20714. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  20715. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  20716. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  20717. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  20718. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  20719. * @param {number} [minFilter=LinearFilter] - The min filter value.
  20720. * @param {number} [format=RGBAFormat] - The texture format.
  20721. * @param {number} [type=UnsignedByteType] - The texture type.
  20722. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  20723. */
  20724. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  20725. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20726. /**
  20727. * This flag can be used for type testing.
  20728. *
  20729. * @type {boolean}
  20730. * @readonly
  20731. * @default true
  20732. */
  20733. this.isVideoTexture = true;
  20734. /**
  20735. * Whether to generate mipmaps (if possible) for a texture.
  20736. *
  20737. * Overwritten and set to `false` by default.
  20738. *
  20739. * @type {boolean}
  20740. * @default false
  20741. */
  20742. this.generateMipmaps = false;
  20743. /**
  20744. * The video frame request callback identifier, which is a positive integer.
  20745. *
  20746. * Value of 0 represents no scheduled rVFC.
  20747. *
  20748. * @private
  20749. * @type {number}
  20750. */
  20751. this._requestVideoFrameCallbackId = 0;
  20752. const scope = this;
  20753. function updateVideo() {
  20754. scope.needsUpdate = true;
  20755. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  20756. }
  20757. if ( 'requestVideoFrameCallback' in video ) {
  20758. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  20759. }
  20760. }
  20761. clone() {
  20762. return new this.constructor( this.image ).copy( this );
  20763. }
  20764. /**
  20765. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  20766. * to `true` every time a new frame is available.
  20767. *
  20768. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  20769. */
  20770. update() {
  20771. const video = this.image;
  20772. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  20773. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  20774. this.needsUpdate = true;
  20775. }
  20776. }
  20777. dispose() {
  20778. if ( this._requestVideoFrameCallbackId !== 0 ) {
  20779. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  20780. this._requestVideoFrameCallbackId = 0;
  20781. }
  20782. super.dispose();
  20783. }
  20784. }
  20785. /**
  20786. * This class can be used as an alternative way to define video data. Instead of using
  20787. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  20788. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  20789. * video frames are decoded with the WebCodecs API.
  20790. *
  20791. * ```js
  20792. * const texture = new THREE.VideoFrameTexture();
  20793. * texture.setFrame( frame );
  20794. * ```
  20795. *
  20796. * @augments VideoTexture
  20797. */
  20798. class VideoFrameTexture extends VideoTexture {
  20799. /**
  20800. * Constructs a new video frame texture.
  20801. *
  20802. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  20803. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  20804. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  20805. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  20806. * @param {number} [minFilter=LinearFilter] - The min filter value.
  20807. * @param {number} [format=RGBAFormat] - The texture format.
  20808. * @param {number} [type=UnsignedByteType] - The texture type.
  20809. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  20810. */
  20811. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20812. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20813. /**
  20814. * This flag can be used for type testing.
  20815. *
  20816. * @type {boolean}
  20817. * @readonly
  20818. * @default true
  20819. */
  20820. this.isVideoFrameTexture = true;
  20821. }
  20822. /**
  20823. * This method overwritten with an empty implementation since
  20824. * this type of texture is updated via `setFrame()`.
  20825. */
  20826. update() {}
  20827. clone() {
  20828. return new this.constructor().copy( this ); // restoring Texture.clone()
  20829. }
  20830. /**
  20831. * Sets the current frame of the video. This will automatically update the texture
  20832. * so the data can be used for rendering.
  20833. *
  20834. * @param {VideoFrame} frame - The video frame.
  20835. */
  20836. setFrame( frame ) {
  20837. this.image = frame;
  20838. this.needsUpdate = true;
  20839. }
  20840. }
  20841. /**
  20842. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  20843. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  20844. * as a texture for further usage.
  20845. *
  20846. * ```js
  20847. * const pixelRatio = window.devicePixelRatio;
  20848. * const textureSize = 128 * pixelRatio;
  20849. *
  20850. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  20851. *
  20852. * // calculate start position for copying part of the frame data
  20853. * const vector = new Vector2();
  20854. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  20855. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  20856. *
  20857. * renderer.render( scene, camera );
  20858. *
  20859. * // copy part of the rendered frame into the framebuffer texture
  20860. * renderer.copyFramebufferToTexture( frameTexture, vector );
  20861. * ```
  20862. *
  20863. * @augments Texture
  20864. */
  20865. class FramebufferTexture extends Texture {
  20866. /**
  20867. * Constructs a new framebuffer texture.
  20868. *
  20869. * @param {number} [width] - The width of the texture.
  20870. * @param {number} [height] - The height of the texture.
  20871. */
  20872. constructor( width, height ) {
  20873. super( { width, height } );
  20874. /**
  20875. * This flag can be used for type testing.
  20876. *
  20877. * @type {boolean}
  20878. * @readonly
  20879. * @default true
  20880. */
  20881. this.isFramebufferTexture = true;
  20882. /**
  20883. * How the texture is sampled when a texel covers more than one pixel.
  20884. *
  20885. * Overwritten and set to `NearestFilter` by default to disable filtering.
  20886. *
  20887. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  20888. * @default NearestFilter
  20889. */
  20890. this.magFilter = NearestFilter;
  20891. /**
  20892. * How the texture is sampled when a texel covers less than one pixel.
  20893. *
  20894. * Overwritten and set to `NearestFilter` by default to disable filtering.
  20895. *
  20896. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  20897. * @default NearestFilter
  20898. */
  20899. this.minFilter = NearestFilter;
  20900. /**
  20901. * Whether to generate mipmaps (if possible) for a texture.
  20902. *
  20903. * Overwritten and set to `false` by default.
  20904. *
  20905. * @type {boolean}
  20906. * @default false
  20907. */
  20908. this.generateMipmaps = false;
  20909. this.needsUpdate = true;
  20910. }
  20911. }
  20912. /**
  20913. * Creates a texture based on data in compressed form.
  20914. *
  20915. * These texture are usually loaded with {@link CompressedTextureLoader}.
  20916. *
  20917. * @augments Texture
  20918. */
  20919. class CompressedTexture extends Texture {
  20920. /**
  20921. * Constructs a new compressed texture.
  20922. *
  20923. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  20924. * the data and dimensions.
  20925. * @param {number} width - The width of the texture.
  20926. * @param {number} height - The height of the texture.
  20927. * @param {number} [format=RGBAFormat] - The texture format.
  20928. * @param {number} [type=UnsignedByteType] - The texture type.
  20929. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  20930. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  20931. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  20932. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  20933. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  20934. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  20935. * @param {string} [colorSpace=NoColorSpace] - The color space.
  20936. */
  20937. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  20938. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  20939. /**
  20940. * This flag can be used for type testing.
  20941. *
  20942. * @type {boolean}
  20943. * @readonly
  20944. * @default true
  20945. */
  20946. this.isCompressedTexture = true;
  20947. /**
  20948. * The image property of a compressed texture just defines its dimensions.
  20949. *
  20950. * @type {{width:number,height:number}}
  20951. */
  20952. this.image = { width: width, height: height };
  20953. /**
  20954. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  20955. *
  20956. * @type {Array<Object>}
  20957. */
  20958. this.mipmaps = mipmaps;
  20959. /**
  20960. * If set to `true`, the texture is flipped along the vertical axis when
  20961. * uploaded to the GPU.
  20962. *
  20963. * Overwritten and set to `false` by default since it is not possible to
  20964. * flip compressed textures.
  20965. *
  20966. * @type {boolean}
  20967. * @default false
  20968. * @readonly
  20969. */
  20970. this.flipY = false;
  20971. /**
  20972. * Whether to generate mipmaps (if possible) for a texture.
  20973. *
  20974. * Overwritten and set to `false` by default since it is not
  20975. * possible to generate mipmaps for compressed data. Mipmaps
  20976. * must be embedded in the compressed texture file.
  20977. *
  20978. * @type {boolean}
  20979. * @default false
  20980. * @readonly
  20981. */
  20982. this.generateMipmaps = false;
  20983. }
  20984. }
  20985. /**
  20986. * Creates a texture 2D array based on data in compressed form.
  20987. *
  20988. * These texture are usually loaded with {@link CompressedTextureLoader}.
  20989. *
  20990. * @augments CompressedTexture
  20991. */
  20992. class CompressedArrayTexture extends CompressedTexture {
  20993. /**
  20994. * Constructs a new compressed array texture.
  20995. *
  20996. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  20997. * the data and dimensions.
  20998. * @param {number} width - The width of the texture.
  20999. * @param {number} height - The height of the texture.
  21000. * @param {number} depth - The depth of the texture.
  21001. * @param {number} [format=RGBAFormat] - The min filter value.
  21002. * @param {number} [type=UnsignedByteType] - The min filter value.
  21003. */
  21004. constructor( mipmaps, width, height, depth, format, type ) {
  21005. super( mipmaps, width, height, format, type );
  21006. /**
  21007. * This flag can be used for type testing.
  21008. *
  21009. * @type {boolean}
  21010. * @readonly
  21011. * @default true
  21012. */
  21013. this.isCompressedArrayTexture = true;
  21014. /**
  21015. * The image property of a compressed texture just defines its dimensions.
  21016. *
  21017. * @name CompressedArrayTexture#image
  21018. * @type {{width:number,height:number,depth:number}}
  21019. */
  21020. this.image.depth = depth;
  21021. /**
  21022. * This defines how the texture is wrapped in the depth and corresponds to
  21023. * *W* in UVW mapping.
  21024. *
  21025. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21026. * @default ClampToEdgeWrapping
  21027. */
  21028. this.wrapR = ClampToEdgeWrapping;
  21029. /**
  21030. * A set of all layers which need to be updated in the texture.
  21031. *
  21032. * @type {Set<number>}
  21033. */
  21034. this.layerUpdates = new Set();
  21035. }
  21036. /**
  21037. * Describes that a specific layer of the texture needs to be updated.
  21038. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21039. * entire compressed texture array is sent to the GPU. Marking specific
  21040. * layers will only transmit subsets of all mipmaps associated with a
  21041. * specific depth in the array which is often much more performant.
  21042. *
  21043. * @param {number} layerIndex - The layer index that should be updated.
  21044. */
  21045. addLayerUpdate( layerIndex ) {
  21046. this.layerUpdates.add( layerIndex );
  21047. }
  21048. /**
  21049. * Resets the layer updates registry.
  21050. */
  21051. clearLayerUpdates() {
  21052. this.layerUpdates.clear();
  21053. }
  21054. }
  21055. /**
  21056. * Creates a cube texture based on data in compressed form.
  21057. *
  21058. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21059. *
  21060. * @augments CompressedTexture
  21061. */
  21062. class CompressedCubeTexture extends CompressedTexture {
  21063. /**
  21064. * Constructs a new compressed texture.
  21065. *
  21066. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21067. * @param {number} [format=RGBAFormat] - The texture format.
  21068. * @param {number} [type=UnsignedByteType] - The texture type.
  21069. */
  21070. constructor( images, format, type ) {
  21071. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21072. /**
  21073. * This flag can be used for type testing.
  21074. *
  21075. * @type {boolean}
  21076. * @readonly
  21077. * @default true
  21078. */
  21079. this.isCompressedCubeTexture = true;
  21080. /**
  21081. * This flag can be used for type testing.
  21082. *
  21083. * @type {boolean}
  21084. * @readonly
  21085. * @default true
  21086. */
  21087. this.isCubeTexture = true;
  21088. this.image = images;
  21089. }
  21090. }
  21091. /**
  21092. * Creates a cube texture made up of six images.
  21093. *
  21094. * ```js
  21095. * const loader = new THREE.CubeTextureLoader();
  21096. * loader.setPath( 'textures/cube/pisa/' );
  21097. *
  21098. * const textureCube = loader.load( [
  21099. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  21100. * ] );
  21101. *
  21102. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  21103. * ```
  21104. *
  21105. * @augments Texture
  21106. */
  21107. class CubeTexture extends Texture {
  21108. /**
  21109. * Constructs a new cube texture.
  21110. *
  21111. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  21112. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21113. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21114. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21115. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21116. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21117. * @param {number} [format=RGBAFormat] - The texture format.
  21118. * @param {number} [type=UnsignedByteType] - The texture type.
  21119. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21120. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  21121. */
  21122. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  21123. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21124. /**
  21125. * This flag can be used for type testing.
  21126. *
  21127. * @type {boolean}
  21128. * @readonly
  21129. * @default true
  21130. */
  21131. this.isCubeTexture = true;
  21132. /**
  21133. * If set to `true`, the texture is flipped along the vertical axis when
  21134. * uploaded to the GPU.
  21135. *
  21136. * Overwritten and set to `false` by default.
  21137. *
  21138. * @type {boolean}
  21139. * @default false
  21140. */
  21141. this.flipY = false;
  21142. }
  21143. /**
  21144. * Alias for {@link CubeTexture#image}.
  21145. *
  21146. * @type {Array<Image>}
  21147. */
  21148. get images() {
  21149. return this.image;
  21150. }
  21151. set images( value ) {
  21152. this.image = value;
  21153. }
  21154. }
  21155. /**
  21156. * Creates a texture from a canvas element.
  21157. *
  21158. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21159. * to `true` immediately since a canvas can directly be used for rendering.
  21160. *
  21161. * @augments Texture
  21162. */
  21163. class CanvasTexture extends Texture {
  21164. /**
  21165. * Constructs a new texture.
  21166. *
  21167. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21168. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21169. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21170. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21171. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21172. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21173. * @param {number} [format=RGBAFormat] - The texture format.
  21174. * @param {number} [type=UnsignedByteType] - The texture type.
  21175. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21176. */
  21177. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21178. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21179. /**
  21180. * This flag can be used for type testing.
  21181. *
  21182. * @type {boolean}
  21183. * @readonly
  21184. * @default true
  21185. */
  21186. this.isCanvasTexture = true;
  21187. this.needsUpdate = true;
  21188. }
  21189. }
  21190. /**
  21191. * This class can be used to automatically save the depth information of a
  21192. * rendering into a texture.
  21193. *
  21194. * @augments Texture
  21195. */
  21196. class DepthTexture extends Texture {
  21197. /**
  21198. * Constructs a new depth texture.
  21199. *
  21200. * @param {number} width - The width of the texture.
  21201. * @param {number} height - The height of the texture.
  21202. * @param {number} [type=UnsignedIntType] - The texture type.
  21203. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21204. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21205. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21206. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21207. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21208. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21209. * @param {number} [format=DepthFormat] - The texture format.
  21210. * @param {number} [depth=1] - The depth of the texture.
  21211. */
  21212. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  21213. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  21214. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  21215. }
  21216. const image = { width: width, height: height, depth: depth };
  21217. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21218. /**
  21219. * This flag can be used for type testing.
  21220. *
  21221. * @type {boolean}
  21222. * @readonly
  21223. * @default true
  21224. */
  21225. this.isDepthTexture = true;
  21226. /**
  21227. * If set to `true`, the texture is flipped along the vertical axis when
  21228. * uploaded to the GPU.
  21229. *
  21230. * Overwritten and set to `false` by default.
  21231. *
  21232. * @type {boolean}
  21233. * @default false
  21234. */
  21235. this.flipY = false;
  21236. /**
  21237. * Whether to generate mipmaps (if possible) for a texture.
  21238. *
  21239. * Overwritten and set to `false` by default.
  21240. *
  21241. * @type {boolean}
  21242. * @default false
  21243. */
  21244. this.generateMipmaps = false;
  21245. /**
  21246. * Code corresponding to the depth compare function.
  21247. *
  21248. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  21249. * @default null
  21250. */
  21251. this.compareFunction = null;
  21252. }
  21253. copy( source ) {
  21254. super.copy( source );
  21255. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  21256. this.compareFunction = source.compareFunction;
  21257. return this;
  21258. }
  21259. toJSON( meta ) {
  21260. const data = super.toJSON( meta );
  21261. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  21262. return data;
  21263. }
  21264. }
  21265. /**
  21266. * This class can be used to automatically save the depth information of a
  21267. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  21268. *
  21269. * @augments DepthTexture
  21270. */
  21271. class CubeDepthTexture extends DepthTexture {
  21272. /**
  21273. * Constructs a new cube depth texture.
  21274. *
  21275. * @param {number} size - The size (width and height) of each cube face.
  21276. * @param {number} [type=UnsignedIntType] - The texture type.
  21277. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21278. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21279. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21280. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  21281. * @param {number} [minFilter=NearestFilter] - The min filter value.
  21282. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21283. * @param {number} [format=DepthFormat] - The texture format.
  21284. */
  21285. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  21286. // Create 6 identical image descriptors for the cube faces
  21287. const image = { width: size, height: size, depth: 1 };
  21288. const images = [ image, image, image, image, image, image ];
  21289. // Call DepthTexture constructor with width, height
  21290. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  21291. // Replace the single image with the array of 6 images
  21292. this.image = images;
  21293. /**
  21294. * This flag can be used for type testing.
  21295. *
  21296. * @type {boolean}
  21297. * @readonly
  21298. * @default true
  21299. */
  21300. this.isCubeDepthTexture = true;
  21301. /**
  21302. * Set to true for cube texture handling in WebGLTextures.
  21303. *
  21304. * @type {boolean}
  21305. * @readonly
  21306. * @default true
  21307. */
  21308. this.isCubeTexture = true;
  21309. }
  21310. /**
  21311. * Alias for {@link CubeDepthTexture#image}.
  21312. *
  21313. * @type {Array<Image>}
  21314. */
  21315. get images() {
  21316. return this.image;
  21317. }
  21318. set images( value ) {
  21319. this.image = value;
  21320. }
  21321. }
  21322. /**
  21323. * Represents a texture created externally with the same renderer context.
  21324. *
  21325. * This may be a texture from a protected media stream, device camera feed,
  21326. * or other data feeds like a depth sensor.
  21327. *
  21328. * Note that this class is only supported in {@link WebGLRenderer}, and in
  21329. * the {@link WebGPURenderer} WebGPU backend.
  21330. *
  21331. * @augments Texture
  21332. */
  21333. class ExternalTexture extends Texture {
  21334. /**
  21335. * Creates a new raw texture.
  21336. *
  21337. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  21338. */
  21339. constructor( sourceTexture = null ) {
  21340. super();
  21341. /**
  21342. * The external source texture.
  21343. *
  21344. * @type {?(WebGLTexture|GPUTexture)}
  21345. * @default null
  21346. */
  21347. this.sourceTexture = sourceTexture;
  21348. /**
  21349. * This flag can be used for type testing.
  21350. *
  21351. * @type {boolean}
  21352. * @readonly
  21353. * @default true
  21354. */
  21355. this.isExternalTexture = true;
  21356. }
  21357. copy( source ) {
  21358. super.copy( source );
  21359. this.sourceTexture = source.sourceTexture;
  21360. return this;
  21361. }
  21362. }
  21363. /**
  21364. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  21365. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  21366. * of the axes.
  21367. *
  21368. * ```js
  21369. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  21370. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21371. * const cube = new THREE.Mesh( geometry, material );
  21372. * scene.add( cube );
  21373. * ```
  21374. *
  21375. * @augments BufferGeometry
  21376. * @demo scenes/geometry-browser.html#BoxGeometry
  21377. */
  21378. class BoxGeometry extends BufferGeometry {
  21379. /**
  21380. * Constructs a new box geometry.
  21381. *
  21382. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  21383. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  21384. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  21385. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  21386. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  21387. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  21388. */
  21389. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  21390. super();
  21391. this.type = 'BoxGeometry';
  21392. /**
  21393. * Holds the constructor parameters that have been
  21394. * used to generate the geometry. Any modification
  21395. * after instantiation does not change the geometry.
  21396. *
  21397. * @type {Object}
  21398. */
  21399. this.parameters = {
  21400. width: width,
  21401. height: height,
  21402. depth: depth,
  21403. widthSegments: widthSegments,
  21404. heightSegments: heightSegments,
  21405. depthSegments: depthSegments
  21406. };
  21407. const scope = this;
  21408. // segments
  21409. widthSegments = Math.floor( widthSegments );
  21410. heightSegments = Math.floor( heightSegments );
  21411. depthSegments = Math.floor( depthSegments );
  21412. // buffers
  21413. const indices = [];
  21414. const vertices = [];
  21415. const normals = [];
  21416. const uvs = [];
  21417. // helper variables
  21418. let numberOfVertices = 0;
  21419. let groupStart = 0;
  21420. // build each side of the box geometry
  21421. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  21422. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  21423. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  21424. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  21425. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  21426. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  21427. // build geometry
  21428. this.setIndex( indices );
  21429. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21430. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21431. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21432. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  21433. const segmentWidth = width / gridX;
  21434. const segmentHeight = height / gridY;
  21435. const widthHalf = width / 2;
  21436. const heightHalf = height / 2;
  21437. const depthHalf = depth / 2;
  21438. const gridX1 = gridX + 1;
  21439. const gridY1 = gridY + 1;
  21440. let vertexCounter = 0;
  21441. let groupCount = 0;
  21442. const vector = new Vector3();
  21443. // generate vertices, normals and uvs
  21444. for ( let iy = 0; iy < gridY1; iy ++ ) {
  21445. const y = iy * segmentHeight - heightHalf;
  21446. for ( let ix = 0; ix < gridX1; ix ++ ) {
  21447. const x = ix * segmentWidth - widthHalf;
  21448. // set values to correct vector component
  21449. vector[ u ] = x * udir;
  21450. vector[ v ] = y * vdir;
  21451. vector[ w ] = depthHalf;
  21452. // now apply vector to vertex buffer
  21453. vertices.push( vector.x, vector.y, vector.z );
  21454. // set values to correct vector component
  21455. vector[ u ] = 0;
  21456. vector[ v ] = 0;
  21457. vector[ w ] = depth > 0 ? 1 : -1;
  21458. // now apply vector to normal buffer
  21459. normals.push( vector.x, vector.y, vector.z );
  21460. // uvs
  21461. uvs.push( ix / gridX );
  21462. uvs.push( 1 - ( iy / gridY ) );
  21463. // counters
  21464. vertexCounter += 1;
  21465. }
  21466. }
  21467. // indices
  21468. // 1. you need three indices to draw a single face
  21469. // 2. a single segment consists of two faces
  21470. // 3. so we need to generate six (2*3) indices per segment
  21471. for ( let iy = 0; iy < gridY; iy ++ ) {
  21472. for ( let ix = 0; ix < gridX; ix ++ ) {
  21473. const a = numberOfVertices + ix + gridX1 * iy;
  21474. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  21475. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  21476. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  21477. // faces
  21478. indices.push( a, b, d );
  21479. indices.push( b, c, d );
  21480. // increase counter
  21481. groupCount += 6;
  21482. }
  21483. }
  21484. // add a group to the geometry. this will ensure multi material support
  21485. scope.addGroup( groupStart, groupCount, materialIndex );
  21486. // calculate new start value for groups
  21487. groupStart += groupCount;
  21488. // update total number of vertices
  21489. numberOfVertices += vertexCounter;
  21490. }
  21491. }
  21492. copy( source ) {
  21493. super.copy( source );
  21494. this.parameters = Object.assign( {}, source.parameters );
  21495. return this;
  21496. }
  21497. /**
  21498. * Factory method for creating an instance of this class from the given
  21499. * JSON object.
  21500. *
  21501. * @param {Object} data - A JSON object representing the serialized geometry.
  21502. * @return {BoxGeometry} A new instance.
  21503. */
  21504. static fromJSON( data ) {
  21505. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  21506. }
  21507. }
  21508. /**
  21509. * A geometry class for representing a capsule.
  21510. *
  21511. * ```js
  21512. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  21513. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21514. * const capsule = new THREE.Mesh( geometry, material );
  21515. * scene.add( capsule );
  21516. * ```
  21517. *
  21518. * @augments BufferGeometry
  21519. * @demo scenes/geometry-browser.html#CapsuleGeometry
  21520. */
  21521. class CapsuleGeometry extends BufferGeometry {
  21522. /**
  21523. * Constructs a new capsule geometry.
  21524. *
  21525. * @param {number} [radius=1] - Radius of the capsule.
  21526. * @param {number} [height=1] - Height of the middle section.
  21527. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  21528. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  21529. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  21530. */
  21531. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  21532. super();
  21533. this.type = 'CapsuleGeometry';
  21534. /**
  21535. * Holds the constructor parameters that have been
  21536. * used to generate the geometry. Any modification
  21537. * after instantiation does not change the geometry.
  21538. *
  21539. * @type {Object}
  21540. */
  21541. this.parameters = {
  21542. radius: radius,
  21543. height: height,
  21544. capSegments: capSegments,
  21545. radialSegments: radialSegments,
  21546. heightSegments: heightSegments,
  21547. };
  21548. height = Math.max( 0, height );
  21549. capSegments = Math.max( 1, Math.floor( capSegments ) );
  21550. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  21551. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  21552. // buffers
  21553. const indices = [];
  21554. const vertices = [];
  21555. const normals = [];
  21556. const uvs = [];
  21557. // helper variables
  21558. const halfHeight = height / 2;
  21559. const capArcLength = ( Math.PI / 2 ) * radius;
  21560. const cylinderPartLength = height;
  21561. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  21562. const numVerticalSegments = capSegments * 2 + heightSegments;
  21563. const verticesPerRow = radialSegments + 1;
  21564. const normal = new Vector3();
  21565. const vertex = new Vector3();
  21566. // generate vertices, normals, and uvs
  21567. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  21568. let currentArcLength = 0;
  21569. let profileY = 0;
  21570. let profileRadius = 0;
  21571. let normalYComponent = 0;
  21572. if ( iy <= capSegments ) {
  21573. // bottom cap
  21574. const segmentProgress = iy / capSegments;
  21575. const angle = ( segmentProgress * Math.PI ) / 2;
  21576. profileY = - halfHeight - radius * Math.cos( angle );
  21577. profileRadius = radius * Math.sin( angle );
  21578. normalYComponent = - radius * Math.cos( angle );
  21579. currentArcLength = segmentProgress * capArcLength;
  21580. } else if ( iy <= capSegments + heightSegments ) {
  21581. // middle section
  21582. const segmentProgress = ( iy - capSegments ) / heightSegments;
  21583. profileY = - halfHeight + segmentProgress * height;
  21584. profileRadius = radius;
  21585. normalYComponent = 0;
  21586. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  21587. } else {
  21588. // top cap
  21589. const segmentProgress =
  21590. ( iy - capSegments - heightSegments ) / capSegments;
  21591. const angle = ( segmentProgress * Math.PI ) / 2;
  21592. profileY = halfHeight + radius * Math.sin( angle );
  21593. profileRadius = radius * Math.cos( angle );
  21594. normalYComponent = radius * Math.sin( angle );
  21595. currentArcLength =
  21596. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  21597. }
  21598. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  21599. // special case for the poles
  21600. let uOffset = 0;
  21601. if ( iy === 0 ) {
  21602. uOffset = 0.5 / radialSegments;
  21603. } else if ( iy === numVerticalSegments ) {
  21604. uOffset = -0.5 / radialSegments;
  21605. }
  21606. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  21607. const u = ix / radialSegments;
  21608. const theta = u * Math.PI * 2;
  21609. const sinTheta = Math.sin( theta );
  21610. const cosTheta = Math.cos( theta );
  21611. // vertex
  21612. vertex.x = - profileRadius * cosTheta;
  21613. vertex.y = profileY;
  21614. vertex.z = profileRadius * sinTheta;
  21615. vertices.push( vertex.x, vertex.y, vertex.z );
  21616. // normal
  21617. normal.set(
  21618. - profileRadius * cosTheta,
  21619. normalYComponent,
  21620. profileRadius * sinTheta
  21621. );
  21622. normal.normalize();
  21623. normals.push( normal.x, normal.y, normal.z );
  21624. // uv
  21625. uvs.push( u + uOffset, v );
  21626. }
  21627. if ( iy > 0 ) {
  21628. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  21629. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  21630. const i1 = prevIndexRow + ix;
  21631. const i2 = prevIndexRow + ix + 1;
  21632. const i3 = iy * verticesPerRow + ix;
  21633. const i4 = iy * verticesPerRow + ix + 1;
  21634. indices.push( i1, i2, i3 );
  21635. indices.push( i2, i4, i3 );
  21636. }
  21637. }
  21638. }
  21639. // build geometry
  21640. this.setIndex( indices );
  21641. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21642. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21643. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21644. }
  21645. copy( source ) {
  21646. super.copy( source );
  21647. this.parameters = Object.assign( {}, source.parameters );
  21648. return this;
  21649. }
  21650. /**
  21651. * Factory method for creating an instance of this class from the given
  21652. * JSON object.
  21653. *
  21654. * @param {Object} data - A JSON object representing the serialized geometry.
  21655. * @return {CapsuleGeometry} A new instance.
  21656. */
  21657. static fromJSON( data ) {
  21658. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  21659. }
  21660. }
  21661. /**
  21662. * A simple shape of Euclidean geometry. It is constructed from a
  21663. * number of triangular segments that are oriented around a central point and
  21664. * extend as far out as a given radius. It is built counter-clockwise from a
  21665. * start angle and a given central angle. It can also be used to create
  21666. * regular polygons, where the number of segments determines the number of
  21667. * sides.
  21668. *
  21669. * ```js
  21670. * const geometry = new THREE.CircleGeometry( 5, 32 );
  21671. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21672. * const circle = new THREE.Mesh( geometry, material );
  21673. * scene.add( circle )
  21674. * ```
  21675. *
  21676. * @augments BufferGeometry
  21677. * @demo scenes/geometry-browser.html#CircleGeometry
  21678. */
  21679. class CircleGeometry extends BufferGeometry {
  21680. /**
  21681. * Constructs a new circle geometry.
  21682. *
  21683. * @param {number} [radius=1] - Radius of the circle.
  21684. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  21685. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  21686. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  21687. * of the circular sector in radians. The default value results in a complete circle.
  21688. */
  21689. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21690. super();
  21691. this.type = 'CircleGeometry';
  21692. /**
  21693. * Holds the constructor parameters that have been
  21694. * used to generate the geometry. Any modification
  21695. * after instantiation does not change the geometry.
  21696. *
  21697. * @type {Object}
  21698. */
  21699. this.parameters = {
  21700. radius: radius,
  21701. segments: segments,
  21702. thetaStart: thetaStart,
  21703. thetaLength: thetaLength
  21704. };
  21705. segments = Math.max( 3, segments );
  21706. // buffers
  21707. const indices = [];
  21708. const vertices = [];
  21709. const normals = [];
  21710. const uvs = [];
  21711. // helper variables
  21712. const vertex = new Vector3();
  21713. const uv = new Vector2();
  21714. // center point
  21715. vertices.push( 0, 0, 0 );
  21716. normals.push( 0, 0, 1 );
  21717. uvs.push( 0.5, 0.5 );
  21718. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  21719. const segment = thetaStart + s / segments * thetaLength;
  21720. // vertex
  21721. vertex.x = radius * Math.cos( segment );
  21722. vertex.y = radius * Math.sin( segment );
  21723. vertices.push( vertex.x, vertex.y, vertex.z );
  21724. // normal
  21725. normals.push( 0, 0, 1 );
  21726. // uvs
  21727. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  21728. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  21729. uvs.push( uv.x, uv.y );
  21730. }
  21731. // indices
  21732. for ( let i = 1; i <= segments; i ++ ) {
  21733. indices.push( i, i + 1, 0 );
  21734. }
  21735. // build geometry
  21736. this.setIndex( indices );
  21737. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21738. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21739. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21740. }
  21741. copy( source ) {
  21742. super.copy( source );
  21743. this.parameters = Object.assign( {}, source.parameters );
  21744. return this;
  21745. }
  21746. /**
  21747. * Factory method for creating an instance of this class from the given
  21748. * JSON object.
  21749. *
  21750. * @param {Object} data - A JSON object representing the serialized geometry.
  21751. * @return {CircleGeometry} A new instance.
  21752. */
  21753. static fromJSON( data ) {
  21754. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  21755. }
  21756. }
  21757. /**
  21758. * A geometry class for representing a cylinder.
  21759. *
  21760. * ```js
  21761. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  21762. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21763. * const cylinder = new THREE.Mesh( geometry, material );
  21764. * scene.add( cylinder );
  21765. * ```
  21766. *
  21767. * @augments BufferGeometry
  21768. * @demo scenes/geometry-browser.html#CylinderGeometry
  21769. */
  21770. class CylinderGeometry extends BufferGeometry {
  21771. /**
  21772. * Constructs a new cylinder geometry.
  21773. *
  21774. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  21775. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  21776. * @param {number} [height=1] - Height of the cylinder.
  21777. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  21778. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  21779. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  21780. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  21781. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  21782. * The default value results in a complete cylinder.
  21783. */
  21784. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21785. super();
  21786. this.type = 'CylinderGeometry';
  21787. /**
  21788. * Holds the constructor parameters that have been
  21789. * used to generate the geometry. Any modification
  21790. * after instantiation does not change the geometry.
  21791. *
  21792. * @type {Object}
  21793. */
  21794. this.parameters = {
  21795. radiusTop: radiusTop,
  21796. radiusBottom: radiusBottom,
  21797. height: height,
  21798. radialSegments: radialSegments,
  21799. heightSegments: heightSegments,
  21800. openEnded: openEnded,
  21801. thetaStart: thetaStart,
  21802. thetaLength: thetaLength
  21803. };
  21804. const scope = this;
  21805. radialSegments = Math.floor( radialSegments );
  21806. heightSegments = Math.floor( heightSegments );
  21807. // buffers
  21808. const indices = [];
  21809. const vertices = [];
  21810. const normals = [];
  21811. const uvs = [];
  21812. // helper variables
  21813. let index = 0;
  21814. const indexArray = [];
  21815. const halfHeight = height / 2;
  21816. let groupStart = 0;
  21817. // generate geometry
  21818. generateTorso();
  21819. if ( openEnded === false ) {
  21820. if ( radiusTop > 0 ) generateCap( true );
  21821. if ( radiusBottom > 0 ) generateCap( false );
  21822. }
  21823. // build geometry
  21824. this.setIndex( indices );
  21825. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21826. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21827. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21828. function generateTorso() {
  21829. const normal = new Vector3();
  21830. const vertex = new Vector3();
  21831. let groupCount = 0;
  21832. // this will be used to calculate the normal
  21833. const slope = ( radiusBottom - radiusTop ) / height;
  21834. // generate vertices, normals and uvs
  21835. for ( let y = 0; y <= heightSegments; y ++ ) {
  21836. const indexRow = [];
  21837. const v = y / heightSegments;
  21838. // calculate the radius of the current row
  21839. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21840. for ( let x = 0; x <= radialSegments; x ++ ) {
  21841. const u = x / radialSegments;
  21842. const theta = u * thetaLength + thetaStart;
  21843. const sinTheta = Math.sin( theta );
  21844. const cosTheta = Math.cos( theta );
  21845. // vertex
  21846. vertex.x = radius * sinTheta;
  21847. vertex.y = - v * height + halfHeight;
  21848. vertex.z = radius * cosTheta;
  21849. vertices.push( vertex.x, vertex.y, vertex.z );
  21850. // normal
  21851. normal.set( sinTheta, slope, cosTheta ).normalize();
  21852. normals.push( normal.x, normal.y, normal.z );
  21853. // uv
  21854. uvs.push( u, 1 - v );
  21855. // save index of vertex in respective row
  21856. indexRow.push( index ++ );
  21857. }
  21858. // now save vertices of the row in our index array
  21859. indexArray.push( indexRow );
  21860. }
  21861. // generate indices
  21862. for ( let x = 0; x < radialSegments; x ++ ) {
  21863. for ( let y = 0; y < heightSegments; y ++ ) {
  21864. // we use the index array to access the correct indices
  21865. const a = indexArray[ y ][ x ];
  21866. const b = indexArray[ y + 1 ][ x ];
  21867. const c = indexArray[ y + 1 ][ x + 1 ];
  21868. const d = indexArray[ y ][ x + 1 ];
  21869. // faces
  21870. if ( radiusTop > 0 || y !== 0 ) {
  21871. indices.push( a, b, d );
  21872. groupCount += 3;
  21873. }
  21874. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  21875. indices.push( b, c, d );
  21876. groupCount += 3;
  21877. }
  21878. }
  21879. }
  21880. // add a group to the geometry. this will ensure multi material support
  21881. scope.addGroup( groupStart, groupCount, 0 );
  21882. // calculate new start value for groups
  21883. groupStart += groupCount;
  21884. }
  21885. function generateCap( top ) {
  21886. // save the index of the first center vertex
  21887. const centerIndexStart = index;
  21888. const uv = new Vector2();
  21889. const vertex = new Vector3();
  21890. let groupCount = 0;
  21891. const radius = ( top === true ) ? radiusTop : radiusBottom;
  21892. const sign = ( top === true ) ? 1 : -1;
  21893. // first we generate the center vertex data of the cap.
  21894. // because the geometry needs one set of uvs per face,
  21895. // we must generate a center vertex per face/segment
  21896. for ( let x = 1; x <= radialSegments; x ++ ) {
  21897. // vertex
  21898. vertices.push( 0, halfHeight * sign, 0 );
  21899. // normal
  21900. normals.push( 0, sign, 0 );
  21901. // uv
  21902. uvs.push( 0.5, 0.5 );
  21903. // increase index
  21904. index ++;
  21905. }
  21906. // save the index of the last center vertex
  21907. const centerIndexEnd = index;
  21908. // now we generate the surrounding vertices, normals and uvs
  21909. for ( let x = 0; x <= radialSegments; x ++ ) {
  21910. const u = x / radialSegments;
  21911. const theta = u * thetaLength + thetaStart;
  21912. const cosTheta = Math.cos( theta );
  21913. const sinTheta = Math.sin( theta );
  21914. // vertex
  21915. vertex.x = radius * sinTheta;
  21916. vertex.y = halfHeight * sign;
  21917. vertex.z = radius * cosTheta;
  21918. vertices.push( vertex.x, vertex.y, vertex.z );
  21919. // normal
  21920. normals.push( 0, sign, 0 );
  21921. // uv
  21922. uv.x = ( cosTheta * 0.5 ) + 0.5;
  21923. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  21924. uvs.push( uv.x, uv.y );
  21925. // increase index
  21926. index ++;
  21927. }
  21928. // generate indices
  21929. for ( let x = 0; x < radialSegments; x ++ ) {
  21930. const c = centerIndexStart + x;
  21931. const i = centerIndexEnd + x;
  21932. if ( top === true ) {
  21933. // face top
  21934. indices.push( i, i + 1, c );
  21935. } else {
  21936. // face bottom
  21937. indices.push( i + 1, i, c );
  21938. }
  21939. groupCount += 3;
  21940. }
  21941. // add a group to the geometry. this will ensure multi material support
  21942. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  21943. // calculate new start value for groups
  21944. groupStart += groupCount;
  21945. }
  21946. }
  21947. copy( source ) {
  21948. super.copy( source );
  21949. this.parameters = Object.assign( {}, source.parameters );
  21950. return this;
  21951. }
  21952. /**
  21953. * Factory method for creating an instance of this class from the given
  21954. * JSON object.
  21955. *
  21956. * @param {Object} data - A JSON object representing the serialized geometry.
  21957. * @return {CylinderGeometry} A new instance.
  21958. */
  21959. static fromJSON( data ) {
  21960. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  21961. }
  21962. }
  21963. /**
  21964. * A geometry class for representing a cone.
  21965. *
  21966. * ```js
  21967. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  21968. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21969. * const cone = new THREE.Mesh(geometry, material );
  21970. * scene.add( cone );
  21971. * ```
  21972. *
  21973. * @augments CylinderGeometry
  21974. * @demo scenes/geometry-browser.html#ConeGeometry
  21975. */
  21976. class ConeGeometry extends CylinderGeometry {
  21977. /**
  21978. * Constructs a new cone geometry.
  21979. *
  21980. * @param {number} [radius=1] - Radius of the cone base.
  21981. * @param {number} [height=1] - Height of the cone.
  21982. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  21983. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  21984. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  21985. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  21986. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  21987. * The default value results in a complete cone.
  21988. */
  21989. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21990. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  21991. this.type = 'ConeGeometry';
  21992. /**
  21993. * Holds the constructor parameters that have been
  21994. * used to generate the geometry. Any modification
  21995. * after instantiation does not change the geometry.
  21996. *
  21997. * @type {Object}
  21998. */
  21999. this.parameters = {
  22000. radius: radius,
  22001. height: height,
  22002. radialSegments: radialSegments,
  22003. heightSegments: heightSegments,
  22004. openEnded: openEnded,
  22005. thetaStart: thetaStart,
  22006. thetaLength: thetaLength
  22007. };
  22008. }
  22009. /**
  22010. * Factory method for creating an instance of this class from the given
  22011. * JSON object.
  22012. *
  22013. * @param {Object} data - A JSON object representing the serialized geometry.
  22014. * @return {ConeGeometry} A new instance.
  22015. */
  22016. static fromJSON( data ) {
  22017. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22018. }
  22019. }
  22020. /**
  22021. * A polyhedron is a solid in three dimensions with flat faces. This class
  22022. * will take an array of vertices, project them onto a sphere, and then
  22023. * divide them up to the desired level of detail.
  22024. *
  22025. * @augments BufferGeometry
  22026. */
  22027. class PolyhedronGeometry extends BufferGeometry {
  22028. /**
  22029. * Constructs a new polyhedron geometry.
  22030. *
  22031. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22032. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22033. * @param {number} [radius=1] - The radius of the shape.
  22034. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22035. */
  22036. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22037. super();
  22038. this.type = 'PolyhedronGeometry';
  22039. /**
  22040. * Holds the constructor parameters that have been
  22041. * used to generate the geometry. Any modification
  22042. * after instantiation does not change the geometry.
  22043. *
  22044. * @type {Object}
  22045. */
  22046. this.parameters = {
  22047. vertices: vertices,
  22048. indices: indices,
  22049. radius: radius,
  22050. detail: detail
  22051. };
  22052. // default buffer data
  22053. const vertexBuffer = [];
  22054. const uvBuffer = [];
  22055. // the subdivision creates the vertex buffer data
  22056. subdivide( detail );
  22057. // all vertices should lie on a conceptual sphere with a given radius
  22058. applyRadius( radius );
  22059. // finally, create the uv data
  22060. generateUVs();
  22061. // build non-indexed geometry
  22062. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22063. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22064. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22065. if ( detail === 0 ) {
  22066. this.computeVertexNormals(); // flat normals
  22067. } else {
  22068. this.normalizeNormals(); // smooth normals
  22069. }
  22070. // helper functions
  22071. function subdivide( detail ) {
  22072. const a = new Vector3();
  22073. const b = new Vector3();
  22074. const c = new Vector3();
  22075. // iterate over all faces and apply a subdivision with the given detail value
  22076. for ( let i = 0; i < indices.length; i += 3 ) {
  22077. // get the vertices of the face
  22078. getVertexByIndex( indices[ i + 0 ], a );
  22079. getVertexByIndex( indices[ i + 1 ], b );
  22080. getVertexByIndex( indices[ i + 2 ], c );
  22081. // perform subdivision
  22082. subdivideFace( a, b, c, detail );
  22083. }
  22084. }
  22085. function subdivideFace( a, b, c, detail ) {
  22086. const cols = detail + 1;
  22087. // we use this multidimensional array as a data structure for creating the subdivision
  22088. const v = [];
  22089. // construct all of the vertices for this subdivision
  22090. for ( let i = 0; i <= cols; i ++ ) {
  22091. v[ i ] = [];
  22092. const aj = a.clone().lerp( c, i / cols );
  22093. const bj = b.clone().lerp( c, i / cols );
  22094. const rows = cols - i;
  22095. for ( let j = 0; j <= rows; j ++ ) {
  22096. if ( j === 0 && i === cols ) {
  22097. v[ i ][ j ] = aj;
  22098. } else {
  22099. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22100. }
  22101. }
  22102. }
  22103. // construct all of the faces
  22104. for ( let i = 0; i < cols; i ++ ) {
  22105. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22106. const k = Math.floor( j / 2 );
  22107. if ( j % 2 === 0 ) {
  22108. pushVertex( v[ i ][ k + 1 ] );
  22109. pushVertex( v[ i + 1 ][ k ] );
  22110. pushVertex( v[ i ][ k ] );
  22111. } else {
  22112. pushVertex( v[ i ][ k + 1 ] );
  22113. pushVertex( v[ i + 1 ][ k + 1 ] );
  22114. pushVertex( v[ i + 1 ][ k ] );
  22115. }
  22116. }
  22117. }
  22118. }
  22119. function applyRadius( radius ) {
  22120. const vertex = new Vector3();
  22121. // iterate over the entire buffer and apply the radius to each vertex
  22122. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22123. vertex.x = vertexBuffer[ i + 0 ];
  22124. vertex.y = vertexBuffer[ i + 1 ];
  22125. vertex.z = vertexBuffer[ i + 2 ];
  22126. vertex.normalize().multiplyScalar( radius );
  22127. vertexBuffer[ i + 0 ] = vertex.x;
  22128. vertexBuffer[ i + 1 ] = vertex.y;
  22129. vertexBuffer[ i + 2 ] = vertex.z;
  22130. }
  22131. }
  22132. function generateUVs() {
  22133. const vertex = new Vector3();
  22134. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22135. vertex.x = vertexBuffer[ i + 0 ];
  22136. vertex.y = vertexBuffer[ i + 1 ];
  22137. vertex.z = vertexBuffer[ i + 2 ];
  22138. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22139. const v = inclination( vertex ) / Math.PI + 0.5;
  22140. uvBuffer.push( u, 1 - v );
  22141. }
  22142. correctUVs();
  22143. correctSeam();
  22144. }
  22145. function correctSeam() {
  22146. // handle case when face straddles the seam, see #3269
  22147. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22148. // uv data of a single face
  22149. const x0 = uvBuffer[ i + 0 ];
  22150. const x1 = uvBuffer[ i + 2 ];
  22151. const x2 = uvBuffer[ i + 4 ];
  22152. const max = Math.max( x0, x1, x2 );
  22153. const min = Math.min( x0, x1, x2 );
  22154. // 0.9 is somewhat arbitrary
  22155. if ( max > 0.9 && min < 0.1 ) {
  22156. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22157. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22158. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22159. }
  22160. }
  22161. }
  22162. function pushVertex( vertex ) {
  22163. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22164. }
  22165. function getVertexByIndex( index, vertex ) {
  22166. const stride = index * 3;
  22167. vertex.x = vertices[ stride + 0 ];
  22168. vertex.y = vertices[ stride + 1 ];
  22169. vertex.z = vertices[ stride + 2 ];
  22170. }
  22171. function correctUVs() {
  22172. const a = new Vector3();
  22173. const b = new Vector3();
  22174. const c = new Vector3();
  22175. const centroid = new Vector3();
  22176. const uvA = new Vector2();
  22177. const uvB = new Vector2();
  22178. const uvC = new Vector2();
  22179. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22180. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22181. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22182. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22183. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22184. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22185. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22186. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22187. const azi = azimuth( centroid );
  22188. correctUV( uvA, j + 0, a, azi );
  22189. correctUV( uvB, j + 2, b, azi );
  22190. correctUV( uvC, j + 4, c, azi );
  22191. }
  22192. }
  22193. function correctUV( uv, stride, vector, azimuth ) {
  22194. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22195. uvBuffer[ stride ] = uv.x - 1;
  22196. }
  22197. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22198. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22199. }
  22200. }
  22201. // Angle around the Y axis, counter-clockwise when looking from above.
  22202. function azimuth( vector ) {
  22203. return Math.atan2( vector.z, - vector.x );
  22204. }
  22205. // Angle above the XZ plane.
  22206. function inclination( vector ) {
  22207. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22208. }
  22209. }
  22210. copy( source ) {
  22211. super.copy( source );
  22212. this.parameters = Object.assign( {}, source.parameters );
  22213. return this;
  22214. }
  22215. /**
  22216. * Factory method for creating an instance of this class from the given
  22217. * JSON object.
  22218. *
  22219. * @param {Object} data - A JSON object representing the serialized geometry.
  22220. * @return {PolyhedronGeometry} A new instance.
  22221. */
  22222. static fromJSON( data ) {
  22223. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  22224. }
  22225. }
  22226. /**
  22227. * A geometry class for representing a dodecahedron.
  22228. *
  22229. * ```js
  22230. * const geometry = new THREE.DodecahedronGeometry();
  22231. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22232. * const dodecahedron = new THREE.Mesh( geometry, material );
  22233. * scene.add( dodecahedron );
  22234. * ```
  22235. *
  22236. * @augments PolyhedronGeometry
  22237. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  22238. */
  22239. class DodecahedronGeometry extends PolyhedronGeometry {
  22240. /**
  22241. * Constructs a new dodecahedron geometry.
  22242. *
  22243. * @param {number} [radius=1] - Radius of the dodecahedron.
  22244. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22245. */
  22246. constructor( radius = 1, detail = 0 ) {
  22247. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22248. const r = 1 / t;
  22249. const vertices = [
  22250. // (±1, ±1, ±1)
  22251. -1, -1, -1, -1, -1, 1,
  22252. -1, 1, -1, -1, 1, 1,
  22253. 1, -1, -1, 1, -1, 1,
  22254. 1, 1, -1, 1, 1, 1,
  22255. // (0, ±1/φ, ±φ)
  22256. 0, - r, - t, 0, - r, t,
  22257. 0, r, - t, 0, r, t,
  22258. // (±1/φ, ±φ, 0)
  22259. - r, - t, 0, - r, t, 0,
  22260. r, - t, 0, r, t, 0,
  22261. // (±φ, 0, ±1/φ)
  22262. - t, 0, - r, t, 0, - r,
  22263. - t, 0, r, t, 0, r
  22264. ];
  22265. const indices = [
  22266. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22267. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22268. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22269. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22270. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22271. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22272. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22273. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22274. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22275. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22276. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22277. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22278. ];
  22279. super( vertices, indices, radius, detail );
  22280. this.type = 'DodecahedronGeometry';
  22281. /**
  22282. * Holds the constructor parameters that have been
  22283. * used to generate the geometry. Any modification
  22284. * after instantiation does not change the geometry.
  22285. *
  22286. * @type {Object}
  22287. */
  22288. this.parameters = {
  22289. radius: radius,
  22290. detail: detail
  22291. };
  22292. }
  22293. /**
  22294. * Factory method for creating an instance of this class from the given
  22295. * JSON object.
  22296. *
  22297. * @param {Object} data - A JSON object representing the serialized geometry.
  22298. * @return {DodecahedronGeometry} A new instance.
  22299. */
  22300. static fromJSON( data ) {
  22301. return new DodecahedronGeometry( data.radius, data.detail );
  22302. }
  22303. }
  22304. const _v0 = /*@__PURE__*/ new Vector3();
  22305. const _v1$1 = /*@__PURE__*/ new Vector3();
  22306. const _normal = /*@__PURE__*/ new Vector3();
  22307. const _triangle = /*@__PURE__*/ new Triangle();
  22308. /**
  22309. * Can be used as a helper object to view the edges of a geometry.
  22310. *
  22311. * ```js
  22312. * const geometry = new THREE.BoxGeometry();
  22313. * const edges = new THREE.EdgesGeometry( geometry );
  22314. * const line = new THREE.LineSegments( edges );
  22315. * scene.add( line );
  22316. * ```
  22317. *
  22318. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22319. *
  22320. * @augments BufferGeometry
  22321. */
  22322. class EdgesGeometry extends BufferGeometry {
  22323. /**
  22324. * Constructs a new edges geometry.
  22325. *
  22326. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22327. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22328. * between the face normals of the adjoining faces exceeds this value.
  22329. */
  22330. constructor( geometry = null, thresholdAngle = 1 ) {
  22331. super();
  22332. this.type = 'EdgesGeometry';
  22333. /**
  22334. * Holds the constructor parameters that have been
  22335. * used to generate the geometry. Any modification
  22336. * after instantiation does not change the geometry.
  22337. *
  22338. * @type {Object}
  22339. */
  22340. this.parameters = {
  22341. geometry: geometry,
  22342. thresholdAngle: thresholdAngle
  22343. };
  22344. if ( geometry !== null ) {
  22345. const precisionPoints = 4;
  22346. const precision = Math.pow( 10, precisionPoints );
  22347. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22348. const indexAttr = geometry.getIndex();
  22349. const positionAttr = geometry.getAttribute( 'position' );
  22350. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22351. const indexArr = [ 0, 0, 0 ];
  22352. const vertKeys = [ 'a', 'b', 'c' ];
  22353. const hashes = new Array( 3 );
  22354. const edgeData = {};
  22355. const vertices = [];
  22356. for ( let i = 0; i < indexCount; i += 3 ) {
  22357. if ( indexAttr ) {
  22358. indexArr[ 0 ] = indexAttr.getX( i );
  22359. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22360. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22361. } else {
  22362. indexArr[ 0 ] = i;
  22363. indexArr[ 1 ] = i + 1;
  22364. indexArr[ 2 ] = i + 2;
  22365. }
  22366. const { a, b, c } = _triangle;
  22367. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22368. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22369. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22370. _triangle.getNormal( _normal );
  22371. // create hashes for the edge from the vertices
  22372. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22373. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22374. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22375. // skip degenerate triangles
  22376. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22377. continue;
  22378. }
  22379. // iterate over every edge
  22380. for ( let j = 0; j < 3; j ++ ) {
  22381. // get the first and next vertex making up the edge
  22382. const jNext = ( j + 1 ) % 3;
  22383. const vecHash0 = hashes[ j ];
  22384. const vecHash1 = hashes[ jNext ];
  22385. const v0 = _triangle[ vertKeys[ j ] ];
  22386. const v1 = _triangle[ vertKeys[ jNext ] ];
  22387. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22388. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22389. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22390. // if we found a sibling edge add it into the vertex array if
  22391. // it meets the angle threshold and delete the edge from the map.
  22392. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22393. vertices.push( v0.x, v0.y, v0.z );
  22394. vertices.push( v1.x, v1.y, v1.z );
  22395. }
  22396. edgeData[ reverseHash ] = null;
  22397. } else if ( ! ( hash in edgeData ) ) {
  22398. // if we've already got an edge here then skip adding a new one
  22399. edgeData[ hash ] = {
  22400. index0: indexArr[ j ],
  22401. index1: indexArr[ jNext ],
  22402. normal: _normal.clone(),
  22403. };
  22404. }
  22405. }
  22406. }
  22407. // iterate over all remaining, unmatched edges and add them to the vertex array
  22408. for ( const key in edgeData ) {
  22409. if ( edgeData[ key ] ) {
  22410. const { index0, index1 } = edgeData[ key ];
  22411. _v0.fromBufferAttribute( positionAttr, index0 );
  22412. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22413. vertices.push( _v0.x, _v0.y, _v0.z );
  22414. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22415. }
  22416. }
  22417. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22418. }
  22419. }
  22420. copy( source ) {
  22421. super.copy( source );
  22422. this.parameters = Object.assign( {}, source.parameters );
  22423. return this;
  22424. }
  22425. }
  22426. /**
  22427. * An abstract base class for creating an analytic curve object that contains methods
  22428. * for interpolation.
  22429. *
  22430. * @abstract
  22431. */
  22432. class Curve {
  22433. /**
  22434. * Constructs a new curve.
  22435. */
  22436. constructor() {
  22437. /**
  22438. * The type property is used for detecting the object type
  22439. * in context of serialization/deserialization.
  22440. *
  22441. * @type {string}
  22442. * @readonly
  22443. */
  22444. this.type = 'Curve';
  22445. /**
  22446. * This value determines the amount of divisions when calculating the
  22447. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  22448. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  22449. * recommended to increase the value of this property if the curve is very large.
  22450. *
  22451. * @type {number}
  22452. * @default 200
  22453. */
  22454. this.arcLengthDivisions = 200;
  22455. /**
  22456. * Must be set to `true` if the curve parameters have changed.
  22457. *
  22458. * @type {boolean}
  22459. * @default false
  22460. */
  22461. this.needsUpdate = false;
  22462. /**
  22463. * An internal cache that holds precomputed curve length values.
  22464. *
  22465. * @private
  22466. * @type {?Array<number>}
  22467. * @default null
  22468. */
  22469. this.cacheArcLengths = null;
  22470. }
  22471. /**
  22472. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22473. * for the given interpolation factor.
  22474. *
  22475. * @abstract
  22476. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22477. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22478. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22479. */
  22480. getPoint( /* t, optionalTarget */ ) {
  22481. warn( 'Curve: .getPoint() not implemented.' );
  22482. }
  22483. /**
  22484. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22485. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  22486. * of the curve which equidistant samples.
  22487. *
  22488. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22489. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22490. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22491. */
  22492. getPointAt( u, optionalTarget ) {
  22493. const t = this.getUtoTmapping( u );
  22494. return this.getPoint( t, optionalTarget );
  22495. }
  22496. /**
  22497. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  22498. * the curve shape.
  22499. *
  22500. * @param {number} [divisions=5] - The number of divisions.
  22501. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22502. */
  22503. getPoints( divisions = 5 ) {
  22504. const points = [];
  22505. for ( let d = 0; d <= divisions; d ++ ) {
  22506. points.push( this.getPoint( d / divisions ) );
  22507. }
  22508. return points;
  22509. }
  22510. // Get sequence of points using getPointAt( u )
  22511. /**
  22512. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  22513. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  22514. * curve.
  22515. *
  22516. * @param {number} [divisions=5] - The number of divisions.
  22517. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22518. */
  22519. getSpacedPoints( divisions = 5 ) {
  22520. const points = [];
  22521. for ( let d = 0; d <= divisions; d ++ ) {
  22522. points.push( this.getPointAt( d / divisions ) );
  22523. }
  22524. return points;
  22525. }
  22526. /**
  22527. * Returns the total arc length of the curve.
  22528. *
  22529. * @return {number} The length of the curve.
  22530. */
  22531. getLength() {
  22532. const lengths = this.getLengths();
  22533. return lengths[ lengths.length - 1 ];
  22534. }
  22535. /**
  22536. * Returns an array of cumulative segment lengths of the curve.
  22537. *
  22538. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  22539. * @return {Array<number>} An array holding the cumulative segment lengths.
  22540. */
  22541. getLengths( divisions = this.arcLengthDivisions ) {
  22542. if ( this.cacheArcLengths &&
  22543. ( this.cacheArcLengths.length === divisions + 1 ) &&
  22544. ! this.needsUpdate ) {
  22545. return this.cacheArcLengths;
  22546. }
  22547. this.needsUpdate = false;
  22548. const cache = [];
  22549. let current, last = this.getPoint( 0 );
  22550. let sum = 0;
  22551. cache.push( 0 );
  22552. for ( let p = 1; p <= divisions; p ++ ) {
  22553. current = this.getPoint( p / divisions );
  22554. sum += current.distanceTo( last );
  22555. cache.push( sum );
  22556. last = current;
  22557. }
  22558. this.cacheArcLengths = cache;
  22559. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22560. }
  22561. /**
  22562. * Update the cumulative segment distance cache. The method must be called
  22563. * every time curve parameters are changed. If an updated curve is part of a
  22564. * composed curve like {@link CurvePath}, this method must be called on the
  22565. * composed curve, too.
  22566. */
  22567. updateArcLengths() {
  22568. this.needsUpdate = true;
  22569. this.getLengths();
  22570. }
  22571. /**
  22572. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  22573. * interpolation factor in the same range that can be ued to sample equidistant points
  22574. * from a curve.
  22575. *
  22576. * @param {number} u - The interpolation factor.
  22577. * @param {?number} distance - An optional distance on the curve.
  22578. * @return {number} The updated interpolation factor.
  22579. */
  22580. getUtoTmapping( u, distance = null ) {
  22581. const arcLengths = this.getLengths();
  22582. let i = 0;
  22583. const il = arcLengths.length;
  22584. let targetArcLength; // The targeted u distance value to get
  22585. if ( distance ) {
  22586. targetArcLength = distance;
  22587. } else {
  22588. targetArcLength = u * arcLengths[ il - 1 ];
  22589. }
  22590. // binary search for the index with largest value smaller than target u distance
  22591. let low = 0, high = il - 1, comparison;
  22592. while ( low <= high ) {
  22593. 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
  22594. comparison = arcLengths[ i ] - targetArcLength;
  22595. if ( comparison < 0 ) {
  22596. low = i + 1;
  22597. } else if ( comparison > 0 ) {
  22598. high = i - 1;
  22599. } else {
  22600. high = i;
  22601. break;
  22602. // DONE
  22603. }
  22604. }
  22605. i = high;
  22606. if ( arcLengths[ i ] === targetArcLength ) {
  22607. return i / ( il - 1 );
  22608. }
  22609. // we could get finer grain at lengths, or use simple interpolation between two points
  22610. const lengthBefore = arcLengths[ i ];
  22611. const lengthAfter = arcLengths[ i + 1 ];
  22612. const segmentLength = lengthAfter - lengthBefore;
  22613. // determine where we are between the 'before' and 'after' points
  22614. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  22615. // add that fractional amount to t
  22616. const t = ( i + segmentFraction ) / ( il - 1 );
  22617. return t;
  22618. }
  22619. /**
  22620. * Returns a unit vector tangent for the given interpolation factor.
  22621. * If the derived curve does not implement its tangent derivation,
  22622. * two points a small delta apart will be used to find its gradient
  22623. * which seems to give a reasonable approximation.
  22624. *
  22625. * @param {number} t - The interpolation factor.
  22626. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22627. * @return {(Vector2|Vector3)} The tangent vector.
  22628. */
  22629. getTangent( t, optionalTarget ) {
  22630. const delta = 0.0001;
  22631. let t1 = t - delta;
  22632. let t2 = t + delta;
  22633. // Capping in case of danger
  22634. if ( t1 < 0 ) t1 = 0;
  22635. if ( t2 > 1 ) t2 = 1;
  22636. const pt1 = this.getPoint( t1 );
  22637. const pt2 = this.getPoint( t2 );
  22638. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  22639. tangent.copy( pt2 ).sub( pt1 ).normalize();
  22640. return tangent;
  22641. }
  22642. /**
  22643. * Same as {@link Curve#getTangent} but with equidistant samples.
  22644. *
  22645. * @param {number} u - The interpolation factor.
  22646. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22647. * @return {(Vector2|Vector3)} The tangent vector.
  22648. * @see {@link Curve#getPointAt}
  22649. */
  22650. getTangentAt( u, optionalTarget ) {
  22651. const t = this.getUtoTmapping( u );
  22652. return this.getTangent( t, optionalTarget );
  22653. }
  22654. /**
  22655. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  22656. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  22657. *
  22658. * @param {number} segments - The number of segments.
  22659. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  22660. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  22661. */
  22662. computeFrenetFrames( segments, closed = false ) {
  22663. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22664. const normal = new Vector3();
  22665. const tangents = [];
  22666. const normals = [];
  22667. const binormals = [];
  22668. const vec = new Vector3();
  22669. const mat = new Matrix4();
  22670. // compute the tangent vectors for each segment on the curve
  22671. for ( let i = 0; i <= segments; i ++ ) {
  22672. const u = i / segments;
  22673. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  22674. }
  22675. // select an initial normal vector perpendicular to the first tangent vector,
  22676. // and in the direction of the minimum tangent xyz component
  22677. normals[ 0 ] = new Vector3();
  22678. binormals[ 0 ] = new Vector3();
  22679. let min = Number.MAX_VALUE;
  22680. const tx = Math.abs( tangents[ 0 ].x );
  22681. const ty = Math.abs( tangents[ 0 ].y );
  22682. const tz = Math.abs( tangents[ 0 ].z );
  22683. if ( tx <= min ) {
  22684. min = tx;
  22685. normal.set( 1, 0, 0 );
  22686. }
  22687. if ( ty <= min ) {
  22688. min = ty;
  22689. normal.set( 0, 1, 0 );
  22690. }
  22691. if ( tz <= min ) {
  22692. normal.set( 0, 0, 1 );
  22693. }
  22694. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  22695. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  22696. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  22697. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22698. for ( let i = 1; i <= segments; i ++ ) {
  22699. normals[ i ] = normals[ i - 1 ].clone();
  22700. binormals[ i ] = binormals[ i - 1 ].clone();
  22701. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  22702. if ( vec.length() > Number.EPSILON ) {
  22703. vec.normalize();
  22704. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  22705. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  22706. }
  22707. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22708. }
  22709. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22710. if ( closed === true ) {
  22711. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  22712. theta /= segments;
  22713. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  22714. theta = - theta;
  22715. }
  22716. for ( let i = 1; i <= segments; i ++ ) {
  22717. // twist a little...
  22718. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  22719. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22720. }
  22721. }
  22722. return {
  22723. tangents: tangents,
  22724. normals: normals,
  22725. binormals: binormals
  22726. };
  22727. }
  22728. /**
  22729. * Returns a new curve with copied values from this instance.
  22730. *
  22731. * @return {Curve} A clone of this instance.
  22732. */
  22733. clone() {
  22734. return new this.constructor().copy( this );
  22735. }
  22736. /**
  22737. * Copies the values of the given curve to this instance.
  22738. *
  22739. * @param {Curve} source - The curve to copy.
  22740. * @return {Curve} A reference to this curve.
  22741. */
  22742. copy( source ) {
  22743. this.arcLengthDivisions = source.arcLengthDivisions;
  22744. return this;
  22745. }
  22746. /**
  22747. * Serializes the curve into JSON.
  22748. *
  22749. * @return {Object} A JSON object representing the serialized curve.
  22750. * @see {@link ObjectLoader#parse}
  22751. */
  22752. toJSON() {
  22753. const data = {
  22754. metadata: {
  22755. version: 4.7,
  22756. type: 'Curve',
  22757. generator: 'Curve.toJSON'
  22758. }
  22759. };
  22760. data.arcLengthDivisions = this.arcLengthDivisions;
  22761. data.type = this.type;
  22762. return data;
  22763. }
  22764. /**
  22765. * Deserializes the curve from the given JSON.
  22766. *
  22767. * @param {Object} json - The JSON holding the serialized curve.
  22768. * @return {Curve} A reference to this curve.
  22769. */
  22770. fromJSON( json ) {
  22771. this.arcLengthDivisions = json.arcLengthDivisions;
  22772. return this;
  22773. }
  22774. }
  22775. /**
  22776. * A curve representing an ellipse.
  22777. *
  22778. * ```js
  22779. * const curve = new THREE.EllipseCurve(
  22780. * 0, 0,
  22781. * 10, 10,
  22782. * 0, 2 * Math.PI,
  22783. * false,
  22784. * 0
  22785. * );
  22786. *
  22787. * const points = curve.getPoints( 50 );
  22788. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  22789. *
  22790. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  22791. *
  22792. * // Create the final object to add to the scene
  22793. * const ellipse = new THREE.Line( geometry, material );
  22794. * ```
  22795. *
  22796. * @augments Curve
  22797. */
  22798. class EllipseCurve extends Curve {
  22799. /**
  22800. * Constructs a new ellipse curve.
  22801. *
  22802. * @param {number} [aX=0] - The X center of the ellipse.
  22803. * @param {number} [aY=0] - The Y center of the ellipse.
  22804. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  22805. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  22806. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  22807. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  22808. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  22809. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  22810. */
  22811. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  22812. super();
  22813. /**
  22814. * This flag can be used for type testing.
  22815. *
  22816. * @type {boolean}
  22817. * @readonly
  22818. * @default true
  22819. */
  22820. this.isEllipseCurve = true;
  22821. this.type = 'EllipseCurve';
  22822. /**
  22823. * The X center of the ellipse.
  22824. *
  22825. * @type {number}
  22826. * @default 0
  22827. */
  22828. this.aX = aX;
  22829. /**
  22830. * The Y center of the ellipse.
  22831. *
  22832. * @type {number}
  22833. * @default 0
  22834. */
  22835. this.aY = aY;
  22836. /**
  22837. * The radius of the ellipse in the x direction.
  22838. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  22839. *
  22840. * @type {number}
  22841. * @default 1
  22842. */
  22843. this.xRadius = xRadius;
  22844. /**
  22845. * The radius of the ellipse in the y direction.
  22846. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  22847. *
  22848. * @type {number}
  22849. * @default 1
  22850. */
  22851. this.yRadius = yRadius;
  22852. /**
  22853. * The start angle of the curve in radians starting from the positive X axis.
  22854. *
  22855. * @type {number}
  22856. * @default 0
  22857. */
  22858. this.aStartAngle = aStartAngle;
  22859. /**
  22860. * The end angle of the curve in radians starting from the positive X axis.
  22861. *
  22862. * @type {number}
  22863. * @default Math.PI*2
  22864. */
  22865. this.aEndAngle = aEndAngle;
  22866. /**
  22867. * Whether the ellipse is drawn clockwise or not.
  22868. *
  22869. * @type {boolean}
  22870. * @default false
  22871. */
  22872. this.aClockwise = aClockwise;
  22873. /**
  22874. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  22875. *
  22876. * @type {number}
  22877. * @default 0
  22878. */
  22879. this.aRotation = aRotation;
  22880. }
  22881. /**
  22882. * Returns a point on the curve.
  22883. *
  22884. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22885. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  22886. * @return {Vector2} The position on the curve.
  22887. */
  22888. getPoint( t, optionalTarget = new Vector2() ) {
  22889. const point = optionalTarget;
  22890. const twoPi = Math.PI * 2;
  22891. let deltaAngle = this.aEndAngle - this.aStartAngle;
  22892. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  22893. // ensures that deltaAngle is 0 .. 2 PI
  22894. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  22895. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  22896. if ( deltaAngle < Number.EPSILON ) {
  22897. if ( samePoints ) {
  22898. deltaAngle = 0;
  22899. } else {
  22900. deltaAngle = twoPi;
  22901. }
  22902. }
  22903. if ( this.aClockwise === true && ! samePoints ) {
  22904. if ( deltaAngle === twoPi ) {
  22905. deltaAngle = - twoPi;
  22906. } else {
  22907. deltaAngle = deltaAngle - twoPi;
  22908. }
  22909. }
  22910. const angle = this.aStartAngle + t * deltaAngle;
  22911. let x = this.aX + this.xRadius * Math.cos( angle );
  22912. let y = this.aY + this.yRadius * Math.sin( angle );
  22913. if ( this.aRotation !== 0 ) {
  22914. const cos = Math.cos( this.aRotation );
  22915. const sin = Math.sin( this.aRotation );
  22916. const tx = x - this.aX;
  22917. const ty = y - this.aY;
  22918. // Rotate the point about the center of the ellipse.
  22919. x = tx * cos - ty * sin + this.aX;
  22920. y = tx * sin + ty * cos + this.aY;
  22921. }
  22922. return point.set( x, y );
  22923. }
  22924. copy( source ) {
  22925. super.copy( source );
  22926. this.aX = source.aX;
  22927. this.aY = source.aY;
  22928. this.xRadius = source.xRadius;
  22929. this.yRadius = source.yRadius;
  22930. this.aStartAngle = source.aStartAngle;
  22931. this.aEndAngle = source.aEndAngle;
  22932. this.aClockwise = source.aClockwise;
  22933. this.aRotation = source.aRotation;
  22934. return this;
  22935. }
  22936. toJSON() {
  22937. const data = super.toJSON();
  22938. data.aX = this.aX;
  22939. data.aY = this.aY;
  22940. data.xRadius = this.xRadius;
  22941. data.yRadius = this.yRadius;
  22942. data.aStartAngle = this.aStartAngle;
  22943. data.aEndAngle = this.aEndAngle;
  22944. data.aClockwise = this.aClockwise;
  22945. data.aRotation = this.aRotation;
  22946. return data;
  22947. }
  22948. fromJSON( json ) {
  22949. super.fromJSON( json );
  22950. this.aX = json.aX;
  22951. this.aY = json.aY;
  22952. this.xRadius = json.xRadius;
  22953. this.yRadius = json.yRadius;
  22954. this.aStartAngle = json.aStartAngle;
  22955. this.aEndAngle = json.aEndAngle;
  22956. this.aClockwise = json.aClockwise;
  22957. this.aRotation = json.aRotation;
  22958. return this;
  22959. }
  22960. }
  22961. /**
  22962. * A curve representing an arc.
  22963. *
  22964. * @augments EllipseCurve
  22965. */
  22966. class ArcCurve extends EllipseCurve {
  22967. /**
  22968. * Constructs a new arc curve.
  22969. *
  22970. * @param {number} [aX=0] - The X center of the ellipse.
  22971. * @param {number} [aY=0] - The Y center of the ellipse.
  22972. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  22973. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  22974. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  22975. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  22976. */
  22977. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  22978. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  22979. /**
  22980. * This flag can be used for type testing.
  22981. *
  22982. * @type {boolean}
  22983. * @readonly
  22984. * @default true
  22985. */
  22986. this.isArcCurve = true;
  22987. this.type = 'ArcCurve';
  22988. }
  22989. }
  22990. function CubicPoly() {
  22991. /**
  22992. * Centripetal CatmullRom Curve - which is useful for avoiding
  22993. * cusps and self-intersections in non-uniform catmull rom curves.
  22994. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  22995. *
  22996. * curve.type accepts centripetal(default), chordal and catmullrom
  22997. * curve.tension is used for catmullrom which defaults to 0.5
  22998. */
  22999. /*
  23000. Based on an optimized c++ solution in
  23001. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23002. - http://ideone.com/NoEbVM
  23003. This CubicPoly class could be used for reusing some variables and calculations,
  23004. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23005. which can be placed in CurveUtils.
  23006. */
  23007. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23008. /*
  23009. * Compute coefficients for a cubic polynomial
  23010. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23011. * such that
  23012. * p(0) = x0, p(1) = x1
  23013. * and
  23014. * p'(0) = t0, p'(1) = t1.
  23015. */
  23016. function init( x0, x1, t0, t1 ) {
  23017. c0 = x0;
  23018. c1 = t0;
  23019. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23020. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23021. }
  23022. return {
  23023. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23024. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23025. },
  23026. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23027. // compute tangents when parameterized in [t1,t2]
  23028. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23029. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23030. // rescale tangents for parametrization in [0,1]
  23031. t1 *= dt1;
  23032. t2 *= dt1;
  23033. init( x1, x2, t1, t2 );
  23034. },
  23035. calc: function ( t ) {
  23036. const t2 = t * t;
  23037. const t3 = t2 * t;
  23038. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23039. }
  23040. };
  23041. }
  23042. //
  23043. const tmp = /*@__PURE__*/ new Vector3();
  23044. const px = /*@__PURE__*/ new CubicPoly();
  23045. const py = /*@__PURE__*/ new CubicPoly();
  23046. const pz = /*@__PURE__*/ new CubicPoly();
  23047. /**
  23048. * A curve representing a Catmull-Rom spline.
  23049. *
  23050. * ```js
  23051. * //Create a closed wavey loop
  23052. * const curve = new THREE.CatmullRomCurve3( [
  23053. * new THREE.Vector3( -10, 0, 10 ),
  23054. * new THREE.Vector3( -5, 5, 5 ),
  23055. * new THREE.Vector3( 0, 0, 0 ),
  23056. * new THREE.Vector3( 5, -5, 5 ),
  23057. * new THREE.Vector3( 10, 0, 10 )
  23058. * ] );
  23059. *
  23060. * const points = curve.getPoints( 50 );
  23061. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23062. *
  23063. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23064. *
  23065. * // Create the final object to add to the scene
  23066. * const curveObject = new THREE.Line( geometry, material );
  23067. * ```
  23068. *
  23069. * @augments Curve
  23070. */
  23071. class CatmullRomCurve3 extends Curve {
  23072. /**
  23073. * Constructs a new Catmull-Rom curve.
  23074. *
  23075. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23076. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23077. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23078. * @param {number} [tension=0.5] - Tension of the curve.
  23079. */
  23080. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23081. super();
  23082. /**
  23083. * This flag can be used for type testing.
  23084. *
  23085. * @type {boolean}
  23086. * @readonly
  23087. * @default true
  23088. */
  23089. this.isCatmullRomCurve3 = true;
  23090. this.type = 'CatmullRomCurve3';
  23091. /**
  23092. * An array of 3D points defining the curve.
  23093. *
  23094. * @type {Array<Vector3>}
  23095. */
  23096. this.points = points;
  23097. /**
  23098. * Whether the curve is closed or not.
  23099. *
  23100. * @type {boolean}
  23101. * @default false
  23102. */
  23103. this.closed = closed;
  23104. /**
  23105. * The curve type.
  23106. *
  23107. * @type {('centripetal'|'chordal'|'catmullrom')}
  23108. * @default 'centripetal'
  23109. */
  23110. this.curveType = curveType;
  23111. /**
  23112. * Tension of the curve.
  23113. *
  23114. * @type {number}
  23115. * @default 0.5
  23116. */
  23117. this.tension = tension;
  23118. }
  23119. /**
  23120. * Returns a point on the curve.
  23121. *
  23122. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23123. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23124. * @return {Vector3} The position on the curve.
  23125. */
  23126. getPoint( t, optionalTarget = new Vector3() ) {
  23127. const point = optionalTarget;
  23128. const points = this.points;
  23129. const l = points.length;
  23130. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23131. let intPoint = Math.floor( p );
  23132. let weight = p - intPoint;
  23133. if ( this.closed ) {
  23134. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23135. } else if ( weight === 0 && intPoint === l - 1 ) {
  23136. intPoint = l - 2;
  23137. weight = 1;
  23138. }
  23139. let p0, p3; // 4 points (p1 & p2 defined below)
  23140. if ( this.closed || intPoint > 0 ) {
  23141. p0 = points[ ( intPoint - 1 ) % l ];
  23142. } else {
  23143. // extrapolate first point
  23144. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23145. p0 = tmp;
  23146. }
  23147. const p1 = points[ intPoint % l ];
  23148. const p2 = points[ ( intPoint + 1 ) % l ];
  23149. if ( this.closed || intPoint + 2 < l ) {
  23150. p3 = points[ ( intPoint + 2 ) % l ];
  23151. } else {
  23152. // extrapolate last point
  23153. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23154. p3 = tmp;
  23155. }
  23156. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23157. // init Centripetal / Chordal Catmull-Rom
  23158. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23159. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23160. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23161. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23162. // safety check for repeated points
  23163. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23164. if ( dt0 < 1e-4 ) dt0 = dt1;
  23165. if ( dt2 < 1e-4 ) dt2 = dt1;
  23166. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23167. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23168. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23169. } else if ( this.curveType === 'catmullrom' ) {
  23170. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23171. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23172. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23173. }
  23174. point.set(
  23175. px.calc( weight ),
  23176. py.calc( weight ),
  23177. pz.calc( weight )
  23178. );
  23179. return point;
  23180. }
  23181. copy( source ) {
  23182. super.copy( source );
  23183. this.points = [];
  23184. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23185. const point = source.points[ i ];
  23186. this.points.push( point.clone() );
  23187. }
  23188. this.closed = source.closed;
  23189. this.curveType = source.curveType;
  23190. this.tension = source.tension;
  23191. return this;
  23192. }
  23193. toJSON() {
  23194. const data = super.toJSON();
  23195. data.points = [];
  23196. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23197. const point = this.points[ i ];
  23198. data.points.push( point.toArray() );
  23199. }
  23200. data.closed = this.closed;
  23201. data.curveType = this.curveType;
  23202. data.tension = this.tension;
  23203. return data;
  23204. }
  23205. fromJSON( json ) {
  23206. super.fromJSON( json );
  23207. this.points = [];
  23208. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23209. const point = json.points[ i ];
  23210. this.points.push( new Vector3().fromArray( point ) );
  23211. }
  23212. this.closed = json.closed;
  23213. this.curveType = json.curveType;
  23214. this.tension = json.tension;
  23215. return this;
  23216. }
  23217. }
  23218. /**
  23219. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  23220. *
  23221. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23222. *
  23223. * @module Interpolations
  23224. */
  23225. /**
  23226. * Computes a point on a Catmull-Rom spline.
  23227. *
  23228. * @param {number} t - The interpolation factor.
  23229. * @param {number} p0 - The first control point.
  23230. * @param {number} p1 - The second control point.
  23231. * @param {number} p2 - The third control point.
  23232. * @param {number} p3 - The fourth control point.
  23233. * @return {number} The calculated point on a Catmull-Rom spline.
  23234. */
  23235. function CatmullRom( t, p0, p1, p2, p3 ) {
  23236. const v0 = ( p2 - p0 ) * 0.5;
  23237. const v1 = ( p3 - p1 ) * 0.5;
  23238. const t2 = t * t;
  23239. const t3 = t * t2;
  23240. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23241. }
  23242. //
  23243. function QuadraticBezierP0( t, p ) {
  23244. const k = 1 - t;
  23245. return k * k * p;
  23246. }
  23247. function QuadraticBezierP1( t, p ) {
  23248. return 2 * ( 1 - t ) * t * p;
  23249. }
  23250. function QuadraticBezierP2( t, p ) {
  23251. return t * t * p;
  23252. }
  23253. /**
  23254. * Computes a point on a Quadratic Bezier curve.
  23255. *
  23256. * @param {number} t - The interpolation factor.
  23257. * @param {number} p0 - The first control point.
  23258. * @param {number} p1 - The second control point.
  23259. * @param {number} p2 - The third control point.
  23260. * @return {number} The calculated point on a Quadratic Bezier curve.
  23261. */
  23262. function QuadraticBezier( t, p0, p1, p2 ) {
  23263. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23264. QuadraticBezierP2( t, p2 );
  23265. }
  23266. //
  23267. function CubicBezierP0( t, p ) {
  23268. const k = 1 - t;
  23269. return k * k * k * p;
  23270. }
  23271. function CubicBezierP1( t, p ) {
  23272. const k = 1 - t;
  23273. return 3 * k * k * t * p;
  23274. }
  23275. function CubicBezierP2( t, p ) {
  23276. return 3 * ( 1 - t ) * t * t * p;
  23277. }
  23278. function CubicBezierP3( t, p ) {
  23279. return t * t * t * p;
  23280. }
  23281. /**
  23282. * Computes a point on a Cubic Bezier curve.
  23283. *
  23284. * @param {number} t - The interpolation factor.
  23285. * @param {number} p0 - The first control point.
  23286. * @param {number} p1 - The second control point.
  23287. * @param {number} p2 - The third control point.
  23288. * @param {number} p3 - The fourth control point.
  23289. * @return {number} The calculated point on a Cubic Bezier curve.
  23290. */
  23291. function CubicBezier( t, p0, p1, p2, p3 ) {
  23292. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23293. CubicBezierP3( t, p3 );
  23294. }
  23295. /**
  23296. * A curve representing a 2D Cubic Bezier curve.
  23297. *
  23298. * ```js
  23299. * const curve = new THREE.CubicBezierCurve(
  23300. * new THREE.Vector2( - 0, 0 ),
  23301. * new THREE.Vector2( - 5, 15 ),
  23302. * new THREE.Vector2( 20, 15 ),
  23303. * new THREE.Vector2( 10, 0 )
  23304. * );
  23305. *
  23306. * const points = curve.getPoints( 50 );
  23307. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23308. *
  23309. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23310. *
  23311. * // Create the final object to add to the scene
  23312. * const curveObject = new THREE.Line( geometry, material );
  23313. * ```
  23314. *
  23315. * @augments Curve
  23316. */
  23317. class CubicBezierCurve extends Curve {
  23318. /**
  23319. * Constructs a new Cubic Bezier curve.
  23320. *
  23321. * @param {Vector2} [v0] - The start point.
  23322. * @param {Vector2} [v1] - The first control point.
  23323. * @param {Vector2} [v2] - The second control point.
  23324. * @param {Vector2} [v3] - The end point.
  23325. */
  23326. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23327. super();
  23328. /**
  23329. * This flag can be used for type testing.
  23330. *
  23331. * @type {boolean}
  23332. * @readonly
  23333. * @default true
  23334. */
  23335. this.isCubicBezierCurve = true;
  23336. this.type = 'CubicBezierCurve';
  23337. /**
  23338. * The start point.
  23339. *
  23340. * @type {Vector2}
  23341. */
  23342. this.v0 = v0;
  23343. /**
  23344. * The first control point.
  23345. *
  23346. * @type {Vector2}
  23347. */
  23348. this.v1 = v1;
  23349. /**
  23350. * The second control point.
  23351. *
  23352. * @type {Vector2}
  23353. */
  23354. this.v2 = v2;
  23355. /**
  23356. * The end point.
  23357. *
  23358. * @type {Vector2}
  23359. */
  23360. this.v3 = v3;
  23361. }
  23362. /**
  23363. * Returns a point on the curve.
  23364. *
  23365. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23366. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23367. * @return {Vector2} The position on the curve.
  23368. */
  23369. getPoint( t, optionalTarget = new Vector2() ) {
  23370. const point = optionalTarget;
  23371. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23372. point.set(
  23373. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23374. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23375. );
  23376. return point;
  23377. }
  23378. copy( source ) {
  23379. super.copy( source );
  23380. this.v0.copy( source.v0 );
  23381. this.v1.copy( source.v1 );
  23382. this.v2.copy( source.v2 );
  23383. this.v3.copy( source.v3 );
  23384. return this;
  23385. }
  23386. toJSON() {
  23387. const data = super.toJSON();
  23388. data.v0 = this.v0.toArray();
  23389. data.v1 = this.v1.toArray();
  23390. data.v2 = this.v2.toArray();
  23391. data.v3 = this.v3.toArray();
  23392. return data;
  23393. }
  23394. fromJSON( json ) {
  23395. super.fromJSON( json );
  23396. this.v0.fromArray( json.v0 );
  23397. this.v1.fromArray( json.v1 );
  23398. this.v2.fromArray( json.v2 );
  23399. this.v3.fromArray( json.v3 );
  23400. return this;
  23401. }
  23402. }
  23403. /**
  23404. * A curve representing a 3D Cubic Bezier curve.
  23405. *
  23406. * @augments Curve
  23407. */
  23408. class CubicBezierCurve3 extends Curve {
  23409. /**
  23410. * Constructs a new Cubic Bezier curve.
  23411. *
  23412. * @param {Vector3} [v0] - The start point.
  23413. * @param {Vector3} [v1] - The first control point.
  23414. * @param {Vector3} [v2] - The second control point.
  23415. * @param {Vector3} [v3] - The end point.
  23416. */
  23417. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23418. super();
  23419. /**
  23420. * This flag can be used for type testing.
  23421. *
  23422. * @type {boolean}
  23423. * @readonly
  23424. * @default true
  23425. */
  23426. this.isCubicBezierCurve3 = true;
  23427. this.type = 'CubicBezierCurve3';
  23428. /**
  23429. * The start point.
  23430. *
  23431. * @type {Vector3}
  23432. */
  23433. this.v0 = v0;
  23434. /**
  23435. * The first control point.
  23436. *
  23437. * @type {Vector3}
  23438. */
  23439. this.v1 = v1;
  23440. /**
  23441. * The second control point.
  23442. *
  23443. * @type {Vector3}
  23444. */
  23445. this.v2 = v2;
  23446. /**
  23447. * The end point.
  23448. *
  23449. * @type {Vector3}
  23450. */
  23451. this.v3 = v3;
  23452. }
  23453. /**
  23454. * Returns a point on the curve.
  23455. *
  23456. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23457. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23458. * @return {Vector3} The position on the curve.
  23459. */
  23460. getPoint( t, optionalTarget = new Vector3() ) {
  23461. const point = optionalTarget;
  23462. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23463. point.set(
  23464. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23465. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23466. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23467. );
  23468. return point;
  23469. }
  23470. copy( source ) {
  23471. super.copy( source );
  23472. this.v0.copy( source.v0 );
  23473. this.v1.copy( source.v1 );
  23474. this.v2.copy( source.v2 );
  23475. this.v3.copy( source.v3 );
  23476. return this;
  23477. }
  23478. toJSON() {
  23479. const data = super.toJSON();
  23480. data.v0 = this.v0.toArray();
  23481. data.v1 = this.v1.toArray();
  23482. data.v2 = this.v2.toArray();
  23483. data.v3 = this.v3.toArray();
  23484. return data;
  23485. }
  23486. fromJSON( json ) {
  23487. super.fromJSON( json );
  23488. this.v0.fromArray( json.v0 );
  23489. this.v1.fromArray( json.v1 );
  23490. this.v2.fromArray( json.v2 );
  23491. this.v3.fromArray( json.v3 );
  23492. return this;
  23493. }
  23494. }
  23495. /**
  23496. * A curve representing a 2D line segment.
  23497. *
  23498. * @augments Curve
  23499. */
  23500. class LineCurve extends Curve {
  23501. /**
  23502. * Constructs a new line curve.
  23503. *
  23504. * @param {Vector2} [v1] - The start point.
  23505. * @param {Vector2} [v2] - The end point.
  23506. */
  23507. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  23508. super();
  23509. /**
  23510. * This flag can be used for type testing.
  23511. *
  23512. * @type {boolean}
  23513. * @readonly
  23514. * @default true
  23515. */
  23516. this.isLineCurve = true;
  23517. this.type = 'LineCurve';
  23518. /**
  23519. * The start point.
  23520. *
  23521. * @type {Vector2}
  23522. */
  23523. this.v1 = v1;
  23524. /**
  23525. * The end point.
  23526. *
  23527. * @type {Vector2}
  23528. */
  23529. this.v2 = v2;
  23530. }
  23531. /**
  23532. * Returns a point on the line.
  23533. *
  23534. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23535. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23536. * @return {Vector2} The position on the line.
  23537. */
  23538. getPoint( t, optionalTarget = new Vector2() ) {
  23539. const point = optionalTarget;
  23540. if ( t === 1 ) {
  23541. point.copy( this.v2 );
  23542. } else {
  23543. point.copy( this.v2 ).sub( this.v1 );
  23544. point.multiplyScalar( t ).add( this.v1 );
  23545. }
  23546. return point;
  23547. }
  23548. // Line curve is linear, so we can overwrite default getPointAt
  23549. getPointAt( u, optionalTarget ) {
  23550. return this.getPoint( u, optionalTarget );
  23551. }
  23552. getTangent( t, optionalTarget = new Vector2() ) {
  23553. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23554. }
  23555. getTangentAt( u, optionalTarget ) {
  23556. return this.getTangent( u, optionalTarget );
  23557. }
  23558. copy( source ) {
  23559. super.copy( source );
  23560. this.v1.copy( source.v1 );
  23561. this.v2.copy( source.v2 );
  23562. return this;
  23563. }
  23564. toJSON() {
  23565. const data = super.toJSON();
  23566. data.v1 = this.v1.toArray();
  23567. data.v2 = this.v2.toArray();
  23568. return data;
  23569. }
  23570. fromJSON( json ) {
  23571. super.fromJSON( json );
  23572. this.v1.fromArray( json.v1 );
  23573. this.v2.fromArray( json.v2 );
  23574. return this;
  23575. }
  23576. }
  23577. /**
  23578. * A curve representing a 3D line segment.
  23579. *
  23580. * @augments Curve
  23581. */
  23582. class LineCurve3 extends Curve {
  23583. /**
  23584. * Constructs a new line curve.
  23585. *
  23586. * @param {Vector3} [v1] - The start point.
  23587. * @param {Vector3} [v2] - The end point.
  23588. */
  23589. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  23590. super();
  23591. /**
  23592. * This flag can be used for type testing.
  23593. *
  23594. * @type {boolean}
  23595. * @readonly
  23596. * @default true
  23597. */
  23598. this.isLineCurve3 = true;
  23599. this.type = 'LineCurve3';
  23600. /**
  23601. * The start point.
  23602. *
  23603. * @type {Vector3}
  23604. */
  23605. this.v1 = v1;
  23606. /**
  23607. * The end point.
  23608. *
  23609. * @type {Vector2}
  23610. */
  23611. this.v2 = v2;
  23612. }
  23613. /**
  23614. * Returns a point on the line.
  23615. *
  23616. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23617. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23618. * @return {Vector3} The position on the line.
  23619. */
  23620. getPoint( t, optionalTarget = new Vector3() ) {
  23621. const point = optionalTarget;
  23622. if ( t === 1 ) {
  23623. point.copy( this.v2 );
  23624. } else {
  23625. point.copy( this.v2 ).sub( this.v1 );
  23626. point.multiplyScalar( t ).add( this.v1 );
  23627. }
  23628. return point;
  23629. }
  23630. // Line curve is linear, so we can overwrite default getPointAt
  23631. getPointAt( u, optionalTarget ) {
  23632. return this.getPoint( u, optionalTarget );
  23633. }
  23634. getTangent( t, optionalTarget = new Vector3() ) {
  23635. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23636. }
  23637. getTangentAt( u, optionalTarget ) {
  23638. return this.getTangent( u, optionalTarget );
  23639. }
  23640. copy( source ) {
  23641. super.copy( source );
  23642. this.v1.copy( source.v1 );
  23643. this.v2.copy( source.v2 );
  23644. return this;
  23645. }
  23646. toJSON() {
  23647. const data = super.toJSON();
  23648. data.v1 = this.v1.toArray();
  23649. data.v2 = this.v2.toArray();
  23650. return data;
  23651. }
  23652. fromJSON( json ) {
  23653. super.fromJSON( json );
  23654. this.v1.fromArray( json.v1 );
  23655. this.v2.fromArray( json.v2 );
  23656. return this;
  23657. }
  23658. }
  23659. /**
  23660. * A curve representing a 2D Quadratic Bezier curve.
  23661. *
  23662. * ```js
  23663. * const curve = new THREE.QuadraticBezierCurve(
  23664. * new THREE.Vector2( - 10, 0 ),
  23665. * new THREE.Vector2( 20, 15 ),
  23666. * new THREE.Vector2( 10, 0 )
  23667. * )
  23668. *
  23669. * const points = curve.getPoints( 50 );
  23670. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23671. *
  23672. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23673. *
  23674. * // Create the final object to add to the scene
  23675. * const curveObject = new THREE.Line( geometry, material );
  23676. * ```
  23677. *
  23678. * @augments Curve
  23679. */
  23680. class QuadraticBezierCurve extends Curve {
  23681. /**
  23682. * Constructs a new Quadratic Bezier curve.
  23683. *
  23684. * @param {Vector2} [v0] - The start point.
  23685. * @param {Vector2} [v1] - The control point.
  23686. * @param {Vector2} [v2] - The end point.
  23687. */
  23688. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  23689. super();
  23690. /**
  23691. * This flag can be used for type testing.
  23692. *
  23693. * @type {boolean}
  23694. * @readonly
  23695. * @default true
  23696. */
  23697. this.isQuadraticBezierCurve = true;
  23698. this.type = 'QuadraticBezierCurve';
  23699. /**
  23700. * The start point.
  23701. *
  23702. * @type {Vector2}
  23703. */
  23704. this.v0 = v0;
  23705. /**
  23706. * The control point.
  23707. *
  23708. * @type {Vector2}
  23709. */
  23710. this.v1 = v1;
  23711. /**
  23712. * The end point.
  23713. *
  23714. * @type {Vector2}
  23715. */
  23716. this.v2 = v2;
  23717. }
  23718. /**
  23719. * Returns a point on the curve.
  23720. *
  23721. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23722. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23723. * @return {Vector2} The position on the curve.
  23724. */
  23725. getPoint( t, optionalTarget = new Vector2() ) {
  23726. const point = optionalTarget;
  23727. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23728. point.set(
  23729. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23730. QuadraticBezier( t, v0.y, v1.y, v2.y )
  23731. );
  23732. return point;
  23733. }
  23734. copy( source ) {
  23735. super.copy( source );
  23736. this.v0.copy( source.v0 );
  23737. this.v1.copy( source.v1 );
  23738. this.v2.copy( source.v2 );
  23739. return this;
  23740. }
  23741. toJSON() {
  23742. const data = super.toJSON();
  23743. data.v0 = this.v0.toArray();
  23744. data.v1 = this.v1.toArray();
  23745. data.v2 = this.v2.toArray();
  23746. return data;
  23747. }
  23748. fromJSON( json ) {
  23749. super.fromJSON( json );
  23750. this.v0.fromArray( json.v0 );
  23751. this.v1.fromArray( json.v1 );
  23752. this.v2.fromArray( json.v2 );
  23753. return this;
  23754. }
  23755. }
  23756. /**
  23757. * A curve representing a 3D Quadratic Bezier curve.
  23758. *
  23759. * @augments Curve
  23760. */
  23761. class QuadraticBezierCurve3 extends Curve {
  23762. /**
  23763. * Constructs a new Quadratic Bezier curve.
  23764. *
  23765. * @param {Vector3} [v0] - The start point.
  23766. * @param {Vector3} [v1] - The control point.
  23767. * @param {Vector3} [v2] - The end point.
  23768. */
  23769. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  23770. super();
  23771. /**
  23772. * This flag can be used for type testing.
  23773. *
  23774. * @type {boolean}
  23775. * @readonly
  23776. * @default true
  23777. */
  23778. this.isQuadraticBezierCurve3 = true;
  23779. this.type = 'QuadraticBezierCurve3';
  23780. /**
  23781. * The start point.
  23782. *
  23783. * @type {Vector3}
  23784. */
  23785. this.v0 = v0;
  23786. /**
  23787. * The control point.
  23788. *
  23789. * @type {Vector3}
  23790. */
  23791. this.v1 = v1;
  23792. /**
  23793. * The end point.
  23794. *
  23795. * @type {Vector3}
  23796. */
  23797. this.v2 = v2;
  23798. }
  23799. /**
  23800. * Returns a point on the curve.
  23801. *
  23802. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23803. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23804. * @return {Vector3} The position on the curve.
  23805. */
  23806. getPoint( t, optionalTarget = new Vector3() ) {
  23807. const point = optionalTarget;
  23808. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23809. point.set(
  23810. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23811. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  23812. QuadraticBezier( t, v0.z, v1.z, v2.z )
  23813. );
  23814. return point;
  23815. }
  23816. copy( source ) {
  23817. super.copy( source );
  23818. this.v0.copy( source.v0 );
  23819. this.v1.copy( source.v1 );
  23820. this.v2.copy( source.v2 );
  23821. return this;
  23822. }
  23823. toJSON() {
  23824. const data = super.toJSON();
  23825. data.v0 = this.v0.toArray();
  23826. data.v1 = this.v1.toArray();
  23827. data.v2 = this.v2.toArray();
  23828. return data;
  23829. }
  23830. fromJSON( json ) {
  23831. super.fromJSON( json );
  23832. this.v0.fromArray( json.v0 );
  23833. this.v1.fromArray( json.v1 );
  23834. this.v2.fromArray( json.v2 );
  23835. return this;
  23836. }
  23837. }
  23838. /**
  23839. * A curve representing a 2D spline curve.
  23840. *
  23841. * ```js
  23842. * // Create a sine-like wave
  23843. * const curve = new THREE.SplineCurve( [
  23844. * new THREE.Vector2( -10, 0 ),
  23845. * new THREE.Vector2( -5, 5 ),
  23846. * new THREE.Vector2( 0, 0 ),
  23847. * new THREE.Vector2( 5, -5 ),
  23848. * new THREE.Vector2( 10, 0 )
  23849. * ] );
  23850. *
  23851. * const points = curve.getPoints( 50 );
  23852. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23853. *
  23854. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23855. *
  23856. * // Create the final object to add to the scene
  23857. * const splineObject = new THREE.Line( geometry, material );
  23858. * ```
  23859. *
  23860. * @augments Curve
  23861. */
  23862. class SplineCurve extends Curve {
  23863. /**
  23864. * Constructs a new 2D spline curve.
  23865. *
  23866. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  23867. */
  23868. constructor( points = [] ) {
  23869. super();
  23870. /**
  23871. * This flag can be used for type testing.
  23872. *
  23873. * @type {boolean}
  23874. * @readonly
  23875. * @default true
  23876. */
  23877. this.isSplineCurve = true;
  23878. this.type = 'SplineCurve';
  23879. /**
  23880. * An array of 2D points defining the curve.
  23881. *
  23882. * @type {Array<Vector2>}
  23883. */
  23884. this.points = points;
  23885. }
  23886. /**
  23887. * Returns a point on the curve.
  23888. *
  23889. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23890. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23891. * @return {Vector2} The position on the curve.
  23892. */
  23893. getPoint( t, optionalTarget = new Vector2() ) {
  23894. const point = optionalTarget;
  23895. const points = this.points;
  23896. const p = ( points.length - 1 ) * t;
  23897. const intPoint = Math.floor( p );
  23898. const weight = p - intPoint;
  23899. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  23900. const p1 = points[ intPoint ];
  23901. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  23902. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  23903. point.set(
  23904. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  23905. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  23906. );
  23907. return point;
  23908. }
  23909. copy( source ) {
  23910. super.copy( source );
  23911. this.points = [];
  23912. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23913. const point = source.points[ i ];
  23914. this.points.push( point.clone() );
  23915. }
  23916. return this;
  23917. }
  23918. toJSON() {
  23919. const data = super.toJSON();
  23920. data.points = [];
  23921. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23922. const point = this.points[ i ];
  23923. data.points.push( point.toArray() );
  23924. }
  23925. return data;
  23926. }
  23927. fromJSON( json ) {
  23928. super.fromJSON( json );
  23929. this.points = [];
  23930. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23931. const point = json.points[ i ];
  23932. this.points.push( new Vector2().fromArray( point ) );
  23933. }
  23934. return this;
  23935. }
  23936. }
  23937. var Curves = /*#__PURE__*/Object.freeze({
  23938. __proto__: null,
  23939. ArcCurve: ArcCurve,
  23940. CatmullRomCurve3: CatmullRomCurve3,
  23941. CubicBezierCurve: CubicBezierCurve,
  23942. CubicBezierCurve3: CubicBezierCurve3,
  23943. EllipseCurve: EllipseCurve,
  23944. LineCurve: LineCurve,
  23945. LineCurve3: LineCurve3,
  23946. QuadraticBezierCurve: QuadraticBezierCurve,
  23947. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23948. SplineCurve: SplineCurve
  23949. });
  23950. /**
  23951. * A base class extending {@link Curve}. `CurvePath` is simply an
  23952. * array of connected curves, but retains the API of a curve.
  23953. *
  23954. * @augments Curve
  23955. */
  23956. class CurvePath extends Curve {
  23957. /**
  23958. * Constructs a new curve path.
  23959. */
  23960. constructor() {
  23961. super();
  23962. this.type = 'CurvePath';
  23963. /**
  23964. * An array of curves defining the
  23965. * path.
  23966. *
  23967. * @type {Array<Curve>}
  23968. */
  23969. this.curves = [];
  23970. /**
  23971. * Whether the path should automatically be closed
  23972. * by a line curve.
  23973. *
  23974. * @type {boolean}
  23975. * @default false
  23976. */
  23977. this.autoClose = false;
  23978. }
  23979. /**
  23980. * Adds a curve to this curve path.
  23981. *
  23982. * @param {Curve} curve - The curve to add.
  23983. */
  23984. add( curve ) {
  23985. this.curves.push( curve );
  23986. }
  23987. /**
  23988. * Adds a line curve to close the path.
  23989. *
  23990. * @return {CurvePath} A reference to this curve path.
  23991. */
  23992. closePath() {
  23993. // Add a line curve if start and end of lines are not connected
  23994. const startPoint = this.curves[ 0 ].getPoint( 0 );
  23995. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  23996. if ( ! startPoint.equals( endPoint ) ) {
  23997. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  23998. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  23999. }
  24000. return this;
  24001. }
  24002. /**
  24003. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24004. * for the given interpolation factor.
  24005. *
  24006. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24007. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24008. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24009. */
  24010. getPoint( t, optionalTarget ) {
  24011. // To get accurate point with reference to
  24012. // entire path distance at time t,
  24013. // following has to be done:
  24014. // 1. Length of each sub path have to be known
  24015. // 2. Locate and identify type of curve
  24016. // 3. Get t for the curve
  24017. // 4. Return curve.getPointAt(t')
  24018. const d = t * this.getLength();
  24019. const curveLengths = this.getCurveLengths();
  24020. let i = 0;
  24021. // To think about boundaries points.
  24022. while ( i < curveLengths.length ) {
  24023. if ( curveLengths[ i ] >= d ) {
  24024. const diff = curveLengths[ i ] - d;
  24025. const curve = this.curves[ i ];
  24026. const segmentLength = curve.getLength();
  24027. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24028. return curve.getPointAt( u, optionalTarget );
  24029. }
  24030. i ++;
  24031. }
  24032. return null;
  24033. // loop where sum != 0, sum > d , sum+1 <d
  24034. }
  24035. getLength() {
  24036. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24037. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24038. // getPoint() depends on getLength
  24039. const lens = this.getCurveLengths();
  24040. return lens[ lens.length - 1 ];
  24041. }
  24042. updateArcLengths() {
  24043. // cacheLengths must be recalculated.
  24044. this.needsUpdate = true;
  24045. this.cacheLengths = null;
  24046. this.getCurveLengths();
  24047. }
  24048. /**
  24049. * Returns list of cumulative curve lengths of the defined curves.
  24050. *
  24051. * @return {Array<number>} The curve lengths.
  24052. */
  24053. getCurveLengths() {
  24054. // Compute lengths and cache them
  24055. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24056. // We use cache values if curves and cache array are same length
  24057. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24058. return this.cacheLengths;
  24059. }
  24060. // Get length of sub-curve
  24061. // Push sums into cached array
  24062. const lengths = [];
  24063. let sums = 0;
  24064. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24065. sums += this.curves[ i ].getLength();
  24066. lengths.push( sums );
  24067. }
  24068. this.cacheLengths = lengths;
  24069. return lengths;
  24070. }
  24071. getSpacedPoints( divisions = 40 ) {
  24072. const points = [];
  24073. for ( let i = 0; i <= divisions; i ++ ) {
  24074. points.push( this.getPoint( i / divisions ) );
  24075. }
  24076. if ( this.autoClose ) {
  24077. points.push( points[ 0 ] );
  24078. }
  24079. return points;
  24080. }
  24081. getPoints( divisions = 12 ) {
  24082. const points = [];
  24083. let last;
  24084. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24085. const curve = curves[ i ];
  24086. const resolution = curve.isEllipseCurve ? divisions * 2
  24087. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24088. : curve.isSplineCurve ? divisions * curve.points.length
  24089. : divisions;
  24090. const pts = curve.getPoints( resolution );
  24091. for ( let j = 0; j < pts.length; j ++ ) {
  24092. const point = pts[ j ];
  24093. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24094. points.push( point );
  24095. last = point;
  24096. }
  24097. }
  24098. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24099. points.push( points[ 0 ] );
  24100. }
  24101. return points;
  24102. }
  24103. copy( source ) {
  24104. super.copy( source );
  24105. this.curves = [];
  24106. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24107. const curve = source.curves[ i ];
  24108. this.curves.push( curve.clone() );
  24109. }
  24110. this.autoClose = source.autoClose;
  24111. return this;
  24112. }
  24113. toJSON() {
  24114. const data = super.toJSON();
  24115. data.autoClose = this.autoClose;
  24116. data.curves = [];
  24117. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24118. const curve = this.curves[ i ];
  24119. data.curves.push( curve.toJSON() );
  24120. }
  24121. return data;
  24122. }
  24123. fromJSON( json ) {
  24124. super.fromJSON( json );
  24125. this.autoClose = json.autoClose;
  24126. this.curves = [];
  24127. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24128. const curve = json.curves[ i ];
  24129. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24130. }
  24131. return this;
  24132. }
  24133. }
  24134. /**
  24135. * A 2D path representation. The class provides methods for creating paths
  24136. * and contours of 2D shapes similar to the 2D Canvas API.
  24137. *
  24138. * ```js
  24139. * const path = new THREE.Path();
  24140. *
  24141. * path.lineTo( 0, 0.8 );
  24142. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24143. * path.lineTo( 1, 1 );
  24144. *
  24145. * const points = path.getPoints();
  24146. *
  24147. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24148. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24149. *
  24150. * const line = new THREE.Line( geometry, material );
  24151. * scene.add( line );
  24152. * ```
  24153. *
  24154. * @augments CurvePath
  24155. */
  24156. class Path extends CurvePath {
  24157. /**
  24158. * Constructs a new path.
  24159. *
  24160. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24161. */
  24162. constructor( points ) {
  24163. super();
  24164. this.type = 'Path';
  24165. /**
  24166. * The current offset of the path. Any new curve added will start here.
  24167. *
  24168. * @type {Vector2}
  24169. */
  24170. this.currentPoint = new Vector2();
  24171. if ( points ) {
  24172. this.setFromPoints( points );
  24173. }
  24174. }
  24175. /**
  24176. * Creates a path from the given list of points. The points are added
  24177. * to the path as instances of {@link LineCurve}.
  24178. *
  24179. * @param {Array<Vector2>} points - An array of 2D points.
  24180. * @return {Path} A reference to this path.
  24181. */
  24182. setFromPoints( points ) {
  24183. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24184. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24185. this.lineTo( points[ i ].x, points[ i ].y );
  24186. }
  24187. return this;
  24188. }
  24189. /**
  24190. * Moves {@link Path#currentPoint} to the given point.
  24191. *
  24192. * @param {number} x - The x coordinate.
  24193. * @param {number} y - The y coordinate.
  24194. * @return {Path} A reference to this path.
  24195. */
  24196. moveTo( x, y ) {
  24197. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24198. return this;
  24199. }
  24200. /**
  24201. * Adds an instance of {@link LineCurve} to the path by connecting
  24202. * the current point with the given one.
  24203. *
  24204. * @param {number} x - The x coordinate of the end point.
  24205. * @param {number} y - The y coordinate of the end point.
  24206. * @return {Path} A reference to this path.
  24207. */
  24208. lineTo( x, y ) {
  24209. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24210. this.curves.push( curve );
  24211. this.currentPoint.set( x, y );
  24212. return this;
  24213. }
  24214. /**
  24215. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24216. * the current point with the given one.
  24217. *
  24218. * @param {number} aCPx - The x coordinate of the control point.
  24219. * @param {number} aCPy - The y coordinate of the control point.
  24220. * @param {number} aX - The x coordinate of the end point.
  24221. * @param {number} aY - The y coordinate of the end point.
  24222. * @return {Path} A reference to this path.
  24223. */
  24224. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24225. const curve = new QuadraticBezierCurve(
  24226. this.currentPoint.clone(),
  24227. new Vector2( aCPx, aCPy ),
  24228. new Vector2( aX, aY )
  24229. );
  24230. this.curves.push( curve );
  24231. this.currentPoint.set( aX, aY );
  24232. return this;
  24233. }
  24234. /**
  24235. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24236. * the current point with the given one.
  24237. *
  24238. * @param {number} aCP1x - The x coordinate of the first control point.
  24239. * @param {number} aCP1y - The y coordinate of the first control point.
  24240. * @param {number} aCP2x - The x coordinate of the second control point.
  24241. * @param {number} aCP2y - The y coordinate of the second control point.
  24242. * @param {number} aX - The x coordinate of the end point.
  24243. * @param {number} aY - The y coordinate of the end point.
  24244. * @return {Path} A reference to this path.
  24245. */
  24246. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24247. const curve = new CubicBezierCurve(
  24248. this.currentPoint.clone(),
  24249. new Vector2( aCP1x, aCP1y ),
  24250. new Vector2( aCP2x, aCP2y ),
  24251. new Vector2( aX, aY )
  24252. );
  24253. this.curves.push( curve );
  24254. this.currentPoint.set( aX, aY );
  24255. return this;
  24256. }
  24257. /**
  24258. * Adds an instance of {@link SplineCurve} to the path by connecting
  24259. * the current point with the given list of points.
  24260. *
  24261. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24262. * @return {Path} A reference to this path.
  24263. */
  24264. splineThru( pts ) {
  24265. const npts = [ this.currentPoint.clone() ].concat( pts );
  24266. const curve = new SplineCurve( npts );
  24267. this.curves.push( curve );
  24268. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24269. return this;
  24270. }
  24271. /**
  24272. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24273. * to the current point.
  24274. *
  24275. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24276. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24277. * @param {number} [aRadius=1] - The radius of the arc.
  24278. * @param {number} [aStartAngle=0] - The start angle in radians.
  24279. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24280. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24281. * @return {Path} A reference to this path.
  24282. */
  24283. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24284. const x0 = this.currentPoint.x;
  24285. const y0 = this.currentPoint.y;
  24286. this.absarc( aX + x0, aY + y0, aRadius,
  24287. aStartAngle, aEndAngle, aClockwise );
  24288. return this;
  24289. }
  24290. /**
  24291. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24292. *
  24293. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24294. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24295. * @param {number} [aRadius=1] - The radius of the arc.
  24296. * @param {number} [aStartAngle=0] - The start angle in radians.
  24297. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24298. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24299. * @return {Path} A reference to this path.
  24300. */
  24301. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24302. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24303. return this;
  24304. }
  24305. /**
  24306. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24307. * to the current point
  24308. *
  24309. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24310. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24311. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24312. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24313. * @param {number} [aStartAngle=0] - The start angle in radians.
  24314. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24315. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24316. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24317. * @return {Path} A reference to this path.
  24318. */
  24319. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24320. const x0 = this.currentPoint.x;
  24321. const y0 = this.currentPoint.y;
  24322. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24323. return this;
  24324. }
  24325. /**
  24326. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24327. *
  24328. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24329. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24330. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24331. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24332. * @param {number} [aStartAngle=0] - The start angle in radians.
  24333. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24334. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24335. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24336. * @return {Path} A reference to this path.
  24337. */
  24338. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24339. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24340. if ( this.curves.length > 0 ) {
  24341. // if a previous curve is present, attempt to join
  24342. const firstPoint = curve.getPoint( 0 );
  24343. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24344. this.lineTo( firstPoint.x, firstPoint.y );
  24345. }
  24346. }
  24347. this.curves.push( curve );
  24348. const lastPoint = curve.getPoint( 1 );
  24349. this.currentPoint.copy( lastPoint );
  24350. return this;
  24351. }
  24352. copy( source ) {
  24353. super.copy( source );
  24354. this.currentPoint.copy( source.currentPoint );
  24355. return this;
  24356. }
  24357. toJSON() {
  24358. const data = super.toJSON();
  24359. data.currentPoint = this.currentPoint.toArray();
  24360. return data;
  24361. }
  24362. fromJSON( json ) {
  24363. super.fromJSON( json );
  24364. this.currentPoint.fromArray( json.currentPoint );
  24365. return this;
  24366. }
  24367. }
  24368. /**
  24369. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24370. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24371. * points, or to get triangulated faces.
  24372. *
  24373. * ```js
  24374. * const heartShape = new THREE.Shape();
  24375. *
  24376. * heartShape.moveTo( 25, 25 );
  24377. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24378. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24379. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24380. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24381. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24382. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24383. *
  24384. * const extrudeSettings = {
  24385. * depth: 8,
  24386. * bevelEnabled: true,
  24387. * bevelSegments: 2,
  24388. * steps: 2,
  24389. * bevelSize: 1,
  24390. * bevelThickness: 1
  24391. * };
  24392. *
  24393. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24394. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24395. * ```
  24396. *
  24397. * @augments Path
  24398. */
  24399. class Shape extends Path {
  24400. /**
  24401. * Constructs a new shape.
  24402. *
  24403. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24404. */
  24405. constructor( points ) {
  24406. super( points );
  24407. /**
  24408. * The UUID of the shape.
  24409. *
  24410. * @type {string}
  24411. * @readonly
  24412. */
  24413. this.uuid = generateUUID();
  24414. this.type = 'Shape';
  24415. /**
  24416. * Defines the holes in the shape. Hole definitions must use the
  24417. * opposite winding order (CW/CCW) than the outer shape.
  24418. *
  24419. * @type {Array<Path>}
  24420. * @readonly
  24421. */
  24422. this.holes = [];
  24423. }
  24424. /**
  24425. * Returns an array representing each contour of the holes
  24426. * as a list of 2D points.
  24427. *
  24428. * @param {number} divisions - The fineness of the result.
  24429. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  24430. */
  24431. getPointsHoles( divisions ) {
  24432. const holesPts = [];
  24433. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24434. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24435. }
  24436. return holesPts;
  24437. }
  24438. // get points of shape and holes (keypoints based on segments parameter)
  24439. /**
  24440. * Returns an object that holds contour data for the shape and its holes as
  24441. * arrays of 2D points.
  24442. *
  24443. * @param {number} divisions - The fineness of the result.
  24444. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  24445. */
  24446. extractPoints( divisions ) {
  24447. return {
  24448. shape: this.getPoints( divisions ),
  24449. holes: this.getPointsHoles( divisions )
  24450. };
  24451. }
  24452. copy( source ) {
  24453. super.copy( source );
  24454. this.holes = [];
  24455. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24456. const hole = source.holes[ i ];
  24457. this.holes.push( hole.clone() );
  24458. }
  24459. return this;
  24460. }
  24461. toJSON() {
  24462. const data = super.toJSON();
  24463. data.uuid = this.uuid;
  24464. data.holes = [];
  24465. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24466. const hole = this.holes[ i ];
  24467. data.holes.push( hole.toJSON() );
  24468. }
  24469. return data;
  24470. }
  24471. fromJSON( json ) {
  24472. super.fromJSON( json );
  24473. this.uuid = json.uuid;
  24474. this.holes = [];
  24475. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24476. const hole = json.holes[ i ];
  24477. this.holes.push( new Path().fromJSON( hole ) );
  24478. }
  24479. return this;
  24480. }
  24481. }
  24482. /* eslint-disable */
  24483. // copy of mapbox/earcut version 3.0.2
  24484. // https://github.com/mapbox/earcut/tree/v3.0.2
  24485. function earcut(data, holeIndices, dim = 2) {
  24486. const hasHoles = holeIndices && holeIndices.length;
  24487. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  24488. let outerNode = linkedList(data, 0, outerLen, dim, true);
  24489. const triangles = [];
  24490. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  24491. let minX, minY, invSize;
  24492. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  24493. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  24494. if (data.length > 80 * dim) {
  24495. minX = data[0];
  24496. minY = data[1];
  24497. let maxX = minX;
  24498. let maxY = minY;
  24499. for (let i = dim; i < outerLen; i += dim) {
  24500. const x = data[i];
  24501. const y = data[i + 1];
  24502. if (x < minX) minX = x;
  24503. if (y < minY) minY = y;
  24504. if (x > maxX) maxX = x;
  24505. if (y > maxY) maxY = y;
  24506. }
  24507. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  24508. invSize = Math.max(maxX - minX, maxY - minY);
  24509. invSize = invSize !== 0 ? 32767 / invSize : 0;
  24510. }
  24511. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  24512. return triangles;
  24513. }
  24514. // create a circular doubly linked list from polygon points in the specified winding order
  24515. function linkedList(data, start, end, dim, clockwise) {
  24516. let last;
  24517. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  24518. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24519. } else {
  24520. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24521. }
  24522. if (last && equals(last, last.next)) {
  24523. removeNode(last);
  24524. last = last.next;
  24525. }
  24526. return last;
  24527. }
  24528. // eliminate colinear or duplicate points
  24529. function filterPoints(start, end) {
  24530. if (!start) return start;
  24531. if (!end) end = start;
  24532. let p = start,
  24533. again;
  24534. do {
  24535. again = false;
  24536. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  24537. removeNode(p);
  24538. p = end = p.prev;
  24539. if (p === p.next) break;
  24540. again = true;
  24541. } else {
  24542. p = p.next;
  24543. }
  24544. } while (again || p !== end);
  24545. return end;
  24546. }
  24547. // main ear slicing loop which triangulates a polygon (given as a linked list)
  24548. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  24549. if (!ear) return;
  24550. // interlink polygon nodes in z-order
  24551. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  24552. let stop = ear;
  24553. // iterate through ears, slicing them one by one
  24554. while (ear.prev !== ear.next) {
  24555. const prev = ear.prev;
  24556. const next = ear.next;
  24557. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  24558. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  24559. removeNode(ear);
  24560. // skipping the next vertex leads to less sliver triangles
  24561. ear = next.next;
  24562. stop = next.next;
  24563. continue;
  24564. }
  24565. ear = next;
  24566. // if we looped through the whole remaining polygon and can't find any more ears
  24567. if (ear === stop) {
  24568. // try filtering points and slicing again
  24569. if (!pass) {
  24570. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  24571. // if this didn't work, try curing all small self-intersections locally
  24572. } else if (pass === 1) {
  24573. ear = cureLocalIntersections(filterPoints(ear), triangles);
  24574. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  24575. // as a last resort, try splitting the remaining polygon into two
  24576. } else if (pass === 2) {
  24577. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  24578. }
  24579. break;
  24580. }
  24581. }
  24582. }
  24583. // check whether a polygon node forms a valid ear with adjacent nodes
  24584. function isEar(ear) {
  24585. const a = ear.prev,
  24586. b = ear,
  24587. c = ear.next;
  24588. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24589. // now make sure we don't have other points inside the potential ear
  24590. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24591. // triangle bbox
  24592. const x0 = Math.min(ax, bx, cx),
  24593. y0 = Math.min(ay, by, cy),
  24594. x1 = Math.max(ax, bx, cx),
  24595. y1 = Math.max(ay, by, cy);
  24596. let p = c.next;
  24597. while (p !== a) {
  24598. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  24599. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  24600. area(p.prev, p, p.next) >= 0) return false;
  24601. p = p.next;
  24602. }
  24603. return true;
  24604. }
  24605. function isEarHashed(ear, minX, minY, invSize) {
  24606. const a = ear.prev,
  24607. b = ear,
  24608. c = ear.next;
  24609. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24610. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24611. // triangle bbox
  24612. const x0 = Math.min(ax, bx, cx),
  24613. y0 = Math.min(ay, by, cy),
  24614. x1 = Math.max(ax, bx, cx),
  24615. y1 = Math.max(ay, by, cy);
  24616. // z-order range for the current triangle bbox;
  24617. const minZ = zOrder(x0, y0, minX, minY, invSize),
  24618. maxZ = zOrder(x1, y1, minX, minY, invSize);
  24619. let p = ear.prevZ,
  24620. n = ear.nextZ;
  24621. // look for points inside the triangle in both directions
  24622. while (p && p.z >= minZ && n && n.z <= maxZ) {
  24623. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24624. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24625. p = p.prevZ;
  24626. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24627. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24628. n = n.nextZ;
  24629. }
  24630. // look for remaining points in decreasing z-order
  24631. while (p && p.z >= minZ) {
  24632. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24633. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24634. p = p.prevZ;
  24635. }
  24636. // look for remaining points in increasing z-order
  24637. while (n && n.z <= maxZ) {
  24638. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24639. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24640. n = n.nextZ;
  24641. }
  24642. return true;
  24643. }
  24644. // go through all polygon nodes and cure small local self-intersections
  24645. function cureLocalIntersections(start, triangles) {
  24646. let p = start;
  24647. do {
  24648. const a = p.prev,
  24649. b = p.next.next;
  24650. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  24651. triangles.push(a.i, p.i, b.i);
  24652. // remove two nodes involved
  24653. removeNode(p);
  24654. removeNode(p.next);
  24655. p = start = b;
  24656. }
  24657. p = p.next;
  24658. } while (p !== start);
  24659. return filterPoints(p);
  24660. }
  24661. // try splitting polygon into two and triangulate them independently
  24662. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  24663. // look for a valid diagonal that divides the polygon into two
  24664. let a = start;
  24665. do {
  24666. let b = a.next.next;
  24667. while (b !== a.prev) {
  24668. if (a.i !== b.i && isValidDiagonal(a, b)) {
  24669. // split the polygon in two by the diagonal
  24670. let c = splitPolygon(a, b);
  24671. // filter colinear points around the cuts
  24672. a = filterPoints(a, a.next);
  24673. c = filterPoints(c, c.next);
  24674. // run earcut on each half
  24675. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  24676. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  24677. return;
  24678. }
  24679. b = b.next;
  24680. }
  24681. a = a.next;
  24682. } while (a !== start);
  24683. }
  24684. // link every hole into the outer loop, producing a single-ring polygon without holes
  24685. function eliminateHoles(data, holeIndices, outerNode, dim) {
  24686. const queue = [];
  24687. for (let i = 0, len = holeIndices.length; i < len; i++) {
  24688. const start = holeIndices[i] * dim;
  24689. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  24690. const list = linkedList(data, start, end, dim, false);
  24691. if (list === list.next) list.steiner = true;
  24692. queue.push(getLeftmost(list));
  24693. }
  24694. queue.sort(compareXYSlope);
  24695. // process holes from left to right
  24696. for (let i = 0; i < queue.length; i++) {
  24697. outerNode = eliminateHole(queue[i], outerNode);
  24698. }
  24699. return outerNode;
  24700. }
  24701. function compareXYSlope(a, b) {
  24702. let result = a.x - b.x;
  24703. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  24704. // the bridge to the outer shell is always the point that they meet at.
  24705. if (result === 0) {
  24706. result = a.y - b.y;
  24707. if (result === 0) {
  24708. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  24709. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  24710. result = aSlope - bSlope;
  24711. }
  24712. }
  24713. return result;
  24714. }
  24715. // find a bridge between vertices that connects hole with an outer ring and link it
  24716. function eliminateHole(hole, outerNode) {
  24717. const bridge = findHoleBridge(hole, outerNode);
  24718. if (!bridge) {
  24719. return outerNode;
  24720. }
  24721. const bridgeReverse = splitPolygon(bridge, hole);
  24722. // filter collinear points around the cuts
  24723. filterPoints(bridgeReverse, bridgeReverse.next);
  24724. return filterPoints(bridge, bridge.next);
  24725. }
  24726. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  24727. function findHoleBridge(hole, outerNode) {
  24728. let p = outerNode;
  24729. const hx = hole.x;
  24730. const hy = hole.y;
  24731. let qx = -Infinity;
  24732. let m;
  24733. // find a segment intersected by a ray from the hole's leftmost point to the left;
  24734. // segment's endpoint with lesser x will be potential connection point
  24735. // unless they intersect at a vertex, then choose the vertex
  24736. if (equals(hole, p)) return p;
  24737. do {
  24738. if (equals(hole, p.next)) return p.next;
  24739. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  24740. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  24741. if (x <= hx && x > qx) {
  24742. qx = x;
  24743. m = p.x < p.next.x ? p : p.next;
  24744. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  24745. }
  24746. }
  24747. p = p.next;
  24748. } while (p !== outerNode);
  24749. if (!m) return null;
  24750. // look for points inside the triangle of hole point, segment intersection and endpoint;
  24751. // if there are no points found, we have a valid connection;
  24752. // otherwise choose the point of the minimum angle with the ray as connection point
  24753. const stop = m;
  24754. const mx = m.x;
  24755. const my = m.y;
  24756. let tanMin = Infinity;
  24757. p = m;
  24758. do {
  24759. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  24760. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  24761. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  24762. if (locallyInside(p, hole) &&
  24763. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  24764. m = p;
  24765. tanMin = tan;
  24766. }
  24767. }
  24768. p = p.next;
  24769. } while (p !== stop);
  24770. return m;
  24771. }
  24772. // whether sector in vertex m contains sector in vertex p in the same coordinates
  24773. function sectorContainsSector(m, p) {
  24774. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  24775. }
  24776. // interlink polygon nodes in z-order
  24777. function indexCurve(start, minX, minY, invSize) {
  24778. let p = start;
  24779. do {
  24780. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  24781. p.prevZ = p.prev;
  24782. p.nextZ = p.next;
  24783. p = p.next;
  24784. } while (p !== start);
  24785. p.prevZ.nextZ = null;
  24786. p.prevZ = null;
  24787. sortLinked(p);
  24788. }
  24789. // Simon Tatham's linked list merge sort algorithm
  24790. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  24791. function sortLinked(list) {
  24792. let numMerges;
  24793. let inSize = 1;
  24794. do {
  24795. let p = list;
  24796. let e;
  24797. list = null;
  24798. let tail = null;
  24799. numMerges = 0;
  24800. while (p) {
  24801. numMerges++;
  24802. let q = p;
  24803. let pSize = 0;
  24804. for (let i = 0; i < inSize; i++) {
  24805. pSize++;
  24806. q = q.nextZ;
  24807. if (!q) break;
  24808. }
  24809. let qSize = inSize;
  24810. while (pSize > 0 || (qSize > 0 && q)) {
  24811. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  24812. e = p;
  24813. p = p.nextZ;
  24814. pSize--;
  24815. } else {
  24816. e = q;
  24817. q = q.nextZ;
  24818. qSize--;
  24819. }
  24820. if (tail) tail.nextZ = e;
  24821. else list = e;
  24822. e.prevZ = tail;
  24823. tail = e;
  24824. }
  24825. p = q;
  24826. }
  24827. tail.nextZ = null;
  24828. inSize *= 2;
  24829. } while (numMerges > 1);
  24830. return list;
  24831. }
  24832. // z-order of a point given coords and inverse of the longer side of data bbox
  24833. function zOrder(x, y, minX, minY, invSize) {
  24834. // coords are transformed into non-negative 15-bit integer range
  24835. x = (x - minX) * invSize | 0;
  24836. y = (y - minY) * invSize | 0;
  24837. x = (x | (x << 8)) & 0x00FF00FF;
  24838. x = (x | (x << 4)) & 0x0F0F0F0F;
  24839. x = (x | (x << 2)) & 0x33333333;
  24840. x = (x | (x << 1)) & 0x55555555;
  24841. y = (y | (y << 8)) & 0x00FF00FF;
  24842. y = (y | (y << 4)) & 0x0F0F0F0F;
  24843. y = (y | (y << 2)) & 0x33333333;
  24844. y = (y | (y << 1)) & 0x55555555;
  24845. return x | (y << 1);
  24846. }
  24847. // find the leftmost node of a polygon ring
  24848. function getLeftmost(start) {
  24849. let p = start,
  24850. leftmost = start;
  24851. do {
  24852. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  24853. p = p.next;
  24854. } while (p !== start);
  24855. return leftmost;
  24856. }
  24857. // check if a point lies within a convex triangle
  24858. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  24859. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  24860. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  24861. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  24862. }
  24863. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  24864. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  24865. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  24866. }
  24867. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  24868. function isValidDiagonal(a, b) {
  24869. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  24870. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  24871. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  24872. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  24873. }
  24874. // signed area of a triangle
  24875. function area(p, q, r) {
  24876. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  24877. }
  24878. // check if two points are equal
  24879. function equals(p1, p2) {
  24880. return p1.x === p2.x && p1.y === p2.y;
  24881. }
  24882. // check if two segments intersect
  24883. function intersects(p1, q1, p2, q2) {
  24884. const o1 = sign(area(p1, q1, p2));
  24885. const o2 = sign(area(p1, q1, q2));
  24886. const o3 = sign(area(p2, q2, p1));
  24887. const o4 = sign(area(p2, q2, q1));
  24888. if (o1 !== o2 && o3 !== o4) return true; // general case
  24889. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  24890. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  24891. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  24892. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  24893. return false;
  24894. }
  24895. // for collinear points p, q, r, check if point q lies on segment pr
  24896. function onSegment(p, q, r) {
  24897. 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);
  24898. }
  24899. function sign(num) {
  24900. return num > 0 ? 1 : num < 0 ? -1 : 0;
  24901. }
  24902. // check if a polygon diagonal intersects any polygon segments
  24903. function intersectsPolygon(a, b) {
  24904. let p = a;
  24905. do {
  24906. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  24907. intersects(p, p.next, a, b)) return true;
  24908. p = p.next;
  24909. } while (p !== a);
  24910. return false;
  24911. }
  24912. // check if a polygon diagonal is locally inside the polygon
  24913. function locallyInside(a, b) {
  24914. return area(a.prev, a, a.next) < 0 ?
  24915. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  24916. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  24917. }
  24918. // check if the middle point of a polygon diagonal is inside the polygon
  24919. function middleInside(a, b) {
  24920. let p = a;
  24921. let inside = false;
  24922. const px = (a.x + b.x) / 2;
  24923. const py = (a.y + b.y) / 2;
  24924. do {
  24925. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  24926. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  24927. inside = !inside;
  24928. p = p.next;
  24929. } while (p !== a);
  24930. return inside;
  24931. }
  24932. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  24933. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  24934. function splitPolygon(a, b) {
  24935. const a2 = createNode(a.i, a.x, a.y),
  24936. b2 = createNode(b.i, b.x, b.y),
  24937. an = a.next,
  24938. bp = b.prev;
  24939. a.next = b;
  24940. b.prev = a;
  24941. a2.next = an;
  24942. an.prev = a2;
  24943. b2.next = a2;
  24944. a2.prev = b2;
  24945. bp.next = b2;
  24946. b2.prev = bp;
  24947. return b2;
  24948. }
  24949. // create a node and optionally link it with previous one (in a circular doubly linked list)
  24950. function insertNode(i, x, y, last) {
  24951. const p = createNode(i, x, y);
  24952. if (!last) {
  24953. p.prev = p;
  24954. p.next = p;
  24955. } else {
  24956. p.next = last.next;
  24957. p.prev = last;
  24958. last.next.prev = p;
  24959. last.next = p;
  24960. }
  24961. return p;
  24962. }
  24963. function removeNode(p) {
  24964. p.next.prev = p.prev;
  24965. p.prev.next = p.next;
  24966. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  24967. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  24968. }
  24969. function createNode(i, x, y) {
  24970. return {
  24971. i, // vertex index in coordinates array
  24972. x, y, // vertex coordinates
  24973. prev: null, // previous and next vertex nodes in a polygon ring
  24974. next: null,
  24975. z: 0, // z-order curve value
  24976. prevZ: null, // previous and next nodes in z-order
  24977. nextZ: null,
  24978. steiner: false // indicates whether this is a steiner point
  24979. };
  24980. }
  24981. function signedArea(data, start, end, dim) {
  24982. let sum = 0;
  24983. for (let i = start, j = end - dim; i < end; i += dim) {
  24984. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  24985. j = i;
  24986. }
  24987. return sum;
  24988. }
  24989. /**
  24990. * An implementation of the earcut polygon triangulation algorithm.
  24991. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  24992. *
  24993. * @see https://github.com/mapbox/earcut
  24994. */
  24995. class Earcut {
  24996. /**
  24997. * Triangulates the given shape definition by returning an array of triangles.
  24998. *
  24999. * @param {Array<number>} data - An array with 2D points.
  25000. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25001. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25002. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25003. * representing vertex indices.
  25004. */
  25005. static triangulate( data, holeIndices, dim = 2 ) {
  25006. return earcut( data, holeIndices, dim );
  25007. }
  25008. }
  25009. /**
  25010. * A class containing utility functions for shapes.
  25011. *
  25012. * @hideconstructor
  25013. */
  25014. class ShapeUtils {
  25015. /**
  25016. * Calculate area of a ( 2D ) contour polygon.
  25017. *
  25018. * @param {Array<Vector2>} contour - An array of 2D points.
  25019. * @return {number} The area.
  25020. */
  25021. static area( contour ) {
  25022. const n = contour.length;
  25023. let a = 0.0;
  25024. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25025. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25026. }
  25027. return a * 0.5;
  25028. }
  25029. /**
  25030. * Returns `true` if the given contour uses a clockwise winding order.
  25031. *
  25032. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25033. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25034. */
  25035. static isClockWise( pts ) {
  25036. return ShapeUtils.area( pts ) < 0;
  25037. }
  25038. /**
  25039. * Triangulates the given shape definition.
  25040. *
  25041. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25042. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25043. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25044. */
  25045. static triangulateShape( contour, holes ) {
  25046. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25047. const holeIndices = []; // array of hole indices
  25048. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25049. removeDupEndPts( contour );
  25050. addContour( vertices, contour );
  25051. //
  25052. let holeIndex = contour.length;
  25053. holes.forEach( removeDupEndPts );
  25054. for ( let i = 0; i < holes.length; i ++ ) {
  25055. holeIndices.push( holeIndex );
  25056. holeIndex += holes[ i ].length;
  25057. addContour( vertices, holes[ i ] );
  25058. }
  25059. //
  25060. const triangles = Earcut.triangulate( vertices, holeIndices );
  25061. //
  25062. for ( let i = 0; i < triangles.length; i += 3 ) {
  25063. faces.push( triangles.slice( i, i + 3 ) );
  25064. }
  25065. return faces;
  25066. }
  25067. }
  25068. function removeDupEndPts( points ) {
  25069. const l = points.length;
  25070. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25071. points.pop();
  25072. }
  25073. }
  25074. function addContour( vertices, contour ) {
  25075. for ( let i = 0; i < contour.length; i ++ ) {
  25076. vertices.push( contour[ i ].x );
  25077. vertices.push( contour[ i ].y );
  25078. }
  25079. }
  25080. /**
  25081. * Creates extruded geometry from a path shape.
  25082. *
  25083. * ```js
  25084. * const length = 12, width = 8;
  25085. *
  25086. * const shape = new THREE.Shape();
  25087. * shape.moveTo( 0,0 );
  25088. * shape.lineTo( 0, width );
  25089. * shape.lineTo( length, width );
  25090. * shape.lineTo( length, 0 );
  25091. * shape.lineTo( 0, 0 );
  25092. *
  25093. * const geometry = new THREE.ExtrudeGeometry( shape );
  25094. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25095. * const mesh = new THREE.Mesh( geometry, material ) ;
  25096. * scene.add( mesh );
  25097. * ```
  25098. *
  25099. * @augments BufferGeometry
  25100. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  25101. */
  25102. class ExtrudeGeometry extends BufferGeometry {
  25103. /**
  25104. * Constructs a new extrude geometry.
  25105. *
  25106. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25107. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25108. */
  25109. 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 = {} ) {
  25110. super();
  25111. this.type = 'ExtrudeGeometry';
  25112. /**
  25113. * Holds the constructor parameters that have been
  25114. * used to generate the geometry. Any modification
  25115. * after instantiation does not change the geometry.
  25116. *
  25117. * @type {Object}
  25118. */
  25119. this.parameters = {
  25120. shapes: shapes,
  25121. options: options
  25122. };
  25123. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25124. const scope = this;
  25125. const verticesArray = [];
  25126. const uvArray = [];
  25127. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25128. const shape = shapes[ i ];
  25129. addShape( shape );
  25130. }
  25131. // build geometry
  25132. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25133. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25134. this.computeVertexNormals();
  25135. // functions
  25136. function addShape( shape ) {
  25137. const placeholder = [];
  25138. // options
  25139. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25140. const steps = options.steps !== undefined ? options.steps : 1;
  25141. const depth = options.depth !== undefined ? options.depth : 1;
  25142. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25143. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25144. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25145. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25146. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25147. const extrudePath = options.extrudePath;
  25148. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25149. //
  25150. let extrudePts, extrudeByPath = false;
  25151. let splineTube, binormal, normal, position2;
  25152. if ( extrudePath ) {
  25153. extrudePts = extrudePath.getSpacedPoints( steps );
  25154. extrudeByPath = true;
  25155. bevelEnabled = false; // bevels not supported for path extrusion
  25156. // SETUP TNB variables
  25157. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  25158. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  25159. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25160. binormal = new Vector3();
  25161. normal = new Vector3();
  25162. position2 = new Vector3();
  25163. }
  25164. // Safeguards if bevels are not enabled
  25165. if ( ! bevelEnabled ) {
  25166. bevelSegments = 0;
  25167. bevelThickness = 0;
  25168. bevelSize = 0;
  25169. bevelOffset = 0;
  25170. }
  25171. // Variables initialization
  25172. const shapePoints = shape.extractPoints( curveSegments );
  25173. let vertices = shapePoints.shape;
  25174. const holes = shapePoints.holes;
  25175. const reverse = ! ShapeUtils.isClockWise( vertices );
  25176. if ( reverse ) {
  25177. vertices = vertices.reverse();
  25178. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25179. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25180. const ahole = holes[ h ];
  25181. if ( ShapeUtils.isClockWise( ahole ) ) {
  25182. holes[ h ] = ahole.reverse();
  25183. }
  25184. }
  25185. }
  25186. /**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.
  25187. * @param {Array<Vector2>} points
  25188. */
  25189. function mergeOverlappingPoints( points ) {
  25190. const THRESHOLD = 1e-10;
  25191. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25192. let prevPos = points[ 0 ];
  25193. for ( let i = 1; i <= points.length; i ++ ) {
  25194. const currentIndex = i % points.length;
  25195. const currentPos = points[ currentIndex ];
  25196. const dx = currentPos.x - prevPos.x;
  25197. const dy = currentPos.y - prevPos.y;
  25198. const distSq = dx * dx + dy * dy;
  25199. const scalingFactorSqrt = Math.max(
  25200. Math.abs( currentPos.x ),
  25201. Math.abs( currentPos.y ),
  25202. Math.abs( prevPos.x ),
  25203. Math.abs( prevPos.y )
  25204. );
  25205. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25206. if ( distSq <= thresholdSqScaled ) {
  25207. points.splice( currentIndex, 1 );
  25208. i --;
  25209. continue;
  25210. }
  25211. prevPos = currentPos;
  25212. }
  25213. }
  25214. mergeOverlappingPoints( vertices );
  25215. holes.forEach( mergeOverlappingPoints );
  25216. const numHoles = holes.length;
  25217. /* Vertices */
  25218. const contour = vertices; // vertices has all points but contour has only points of circumference
  25219. for ( let h = 0; h < numHoles; h ++ ) {
  25220. const ahole = holes[ h ];
  25221. vertices = vertices.concat( ahole );
  25222. }
  25223. function scalePt2( pt, vec, size ) {
  25224. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  25225. return pt.clone().addScaledVector( vec, size );
  25226. }
  25227. const vlen = vertices.length;
  25228. // Find directions for point movement
  25229. function getBevelVec( inPt, inPrev, inNext ) {
  25230. // computes for inPt the corresponding point inPt' on a new contour
  25231. // shifted by 1 unit (length of normalized vector) to the left
  25232. // if we walk along contour clockwise, this new contour is outside the old one
  25233. //
  25234. // inPt' is the intersection of the two lines parallel to the two
  25235. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25236. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25237. // good reading for geometry algorithms (here: line-line intersection)
  25238. // http://geomalgorithms.com/a05-_intersect-1.html
  25239. const v_prev_x = inPt.x - inPrev.x,
  25240. v_prev_y = inPt.y - inPrev.y;
  25241. const v_next_x = inNext.x - inPt.x,
  25242. v_next_y = inNext.y - inPt.y;
  25243. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25244. // check for collinear edges
  25245. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25246. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25247. // not collinear
  25248. // length of vectors for normalizing
  25249. const v_prev_len = Math.sqrt( v_prev_lensq );
  25250. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25251. // shift adjacent points by unit vectors to the left
  25252. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25253. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25254. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25255. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25256. // scaling factor for v_prev to intersection point
  25257. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25258. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25259. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25260. // vector from inPt to intersection point
  25261. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25262. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25263. // Don't normalize!, otherwise sharp corners become ugly
  25264. // but prevent crazy spikes
  25265. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25266. if ( v_trans_lensq <= 2 ) {
  25267. return new Vector2( v_trans_x, v_trans_y );
  25268. } else {
  25269. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25270. }
  25271. } else {
  25272. // handle special case of collinear edges
  25273. let direction_eq = false; // assumes: opposite
  25274. if ( v_prev_x > Number.EPSILON ) {
  25275. if ( v_next_x > Number.EPSILON ) {
  25276. direction_eq = true;
  25277. }
  25278. } else {
  25279. if ( v_prev_x < - Number.EPSILON ) {
  25280. if ( v_next_x < - Number.EPSILON ) {
  25281. direction_eq = true;
  25282. }
  25283. } else {
  25284. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25285. direction_eq = true;
  25286. }
  25287. }
  25288. }
  25289. if ( direction_eq ) {
  25290. // log("Warning: lines are a straight sequence");
  25291. v_trans_x = - v_prev_y;
  25292. v_trans_y = v_prev_x;
  25293. shrink_by = Math.sqrt( v_prev_lensq );
  25294. } else {
  25295. // log("Warning: lines are a straight spike");
  25296. v_trans_x = v_prev_x;
  25297. v_trans_y = v_prev_y;
  25298. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25299. }
  25300. }
  25301. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25302. }
  25303. const contourMovements = [];
  25304. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25305. if ( j === il ) j = 0;
  25306. if ( k === il ) k = 0;
  25307. // (j)---(i)---(k)
  25308. // log('i,j,k', i, j , k)
  25309. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25310. }
  25311. const holesMovements = [];
  25312. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25313. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25314. const ahole = holes[ h ];
  25315. oneHoleMovements = [];
  25316. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25317. if ( j === il ) j = 0;
  25318. if ( k === il ) k = 0;
  25319. // (j)---(i)---(k)
  25320. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25321. }
  25322. holesMovements.push( oneHoleMovements );
  25323. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25324. }
  25325. let faces;
  25326. if ( bevelSegments === 0 ) {
  25327. faces = ShapeUtils.triangulateShape( contour, holes );
  25328. } else {
  25329. const contractedContourVertices = [];
  25330. const expandedHoleVertices = [];
  25331. // Loop bevelSegments, 1 for the front, 1 for the back
  25332. for ( let b = 0; b < bevelSegments; b ++ ) {
  25333. //for ( b = bevelSegments; b > 0; b -- ) {
  25334. const t = b / bevelSegments;
  25335. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25336. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25337. // contract shape
  25338. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25339. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25340. v( vert.x, vert.y, - z );
  25341. if ( t === 0 ) contractedContourVertices.push( vert );
  25342. }
  25343. // expand holes
  25344. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25345. const ahole = holes[ h ];
  25346. oneHoleMovements = holesMovements[ h ];
  25347. const oneHoleVertices = [];
  25348. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25349. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25350. v( vert.x, vert.y, - z );
  25351. if ( t === 0 ) oneHoleVertices.push( vert );
  25352. }
  25353. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25354. }
  25355. }
  25356. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25357. }
  25358. const flen = faces.length;
  25359. const bs = bevelSize + bevelOffset;
  25360. // Back facing vertices
  25361. for ( let i = 0; i < vlen; i ++ ) {
  25362. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25363. if ( ! extrudeByPath ) {
  25364. v( vert.x, vert.y, 0 );
  25365. } else {
  25366. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25367. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25368. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25369. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25370. v( position2.x, position2.y, position2.z );
  25371. }
  25372. }
  25373. // Add stepped vertices...
  25374. // Including front facing vertices
  25375. for ( let s = 1; s <= steps; s ++ ) {
  25376. for ( let i = 0; i < vlen; i ++ ) {
  25377. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25378. if ( ! extrudeByPath ) {
  25379. v( vert.x, vert.y, depth / steps * s );
  25380. } else {
  25381. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25382. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25383. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25384. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25385. v( position2.x, position2.y, position2.z );
  25386. }
  25387. }
  25388. }
  25389. // Add bevel segments planes
  25390. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25391. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25392. const t = b / bevelSegments;
  25393. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25394. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25395. // contract shape
  25396. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25397. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25398. v( vert.x, vert.y, depth + z );
  25399. }
  25400. // expand holes
  25401. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25402. const ahole = holes[ h ];
  25403. oneHoleMovements = holesMovements[ h ];
  25404. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25405. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25406. if ( ! extrudeByPath ) {
  25407. v( vert.x, vert.y, depth + z );
  25408. } else {
  25409. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25410. }
  25411. }
  25412. }
  25413. }
  25414. /* Faces */
  25415. // Top and bottom faces
  25416. buildLidFaces();
  25417. // Sides faces
  25418. buildSideFaces();
  25419. ///// Internal functions
  25420. function buildLidFaces() {
  25421. const start = verticesArray.length / 3;
  25422. if ( bevelEnabled ) {
  25423. let layer = 0; // steps + 1
  25424. let offset = vlen * layer;
  25425. // Bottom faces
  25426. for ( let i = 0; i < flen; i ++ ) {
  25427. const face = faces[ i ];
  25428. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25429. }
  25430. layer = steps + bevelSegments * 2;
  25431. offset = vlen * layer;
  25432. // Top faces
  25433. for ( let i = 0; i < flen; i ++ ) {
  25434. const face = faces[ i ];
  25435. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  25436. }
  25437. } else {
  25438. // Bottom faces
  25439. for ( let i = 0; i < flen; i ++ ) {
  25440. const face = faces[ i ];
  25441. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  25442. }
  25443. // Top faces
  25444. for ( let i = 0; i < flen; i ++ ) {
  25445. const face = faces[ i ];
  25446. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  25447. }
  25448. }
  25449. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  25450. }
  25451. // Create faces for the z-sides of the shape
  25452. function buildSideFaces() {
  25453. const start = verticesArray.length / 3;
  25454. let layeroffset = 0;
  25455. sidewalls( contour, layeroffset );
  25456. layeroffset += contour.length;
  25457. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25458. const ahole = holes[ h ];
  25459. sidewalls( ahole, layeroffset );
  25460. //, true
  25461. layeroffset += ahole.length;
  25462. }
  25463. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  25464. }
  25465. function sidewalls( contour, layeroffset ) {
  25466. let i = contour.length;
  25467. while ( -- i >= 0 ) {
  25468. const j = i;
  25469. let k = i - 1;
  25470. if ( k < 0 ) k = contour.length - 1;
  25471. //log('b', i,j, i-1, k,vertices.length);
  25472. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  25473. const slen1 = vlen * s;
  25474. const slen2 = vlen * ( s + 1 );
  25475. const a = layeroffset + j + slen1,
  25476. b = layeroffset + k + slen1,
  25477. c = layeroffset + k + slen2,
  25478. d = layeroffset + j + slen2;
  25479. f4( a, b, c, d );
  25480. }
  25481. }
  25482. }
  25483. function v( x, y, z ) {
  25484. placeholder.push( x );
  25485. placeholder.push( y );
  25486. placeholder.push( z );
  25487. }
  25488. function f3( a, b, c ) {
  25489. addVertex( a );
  25490. addVertex( b );
  25491. addVertex( c );
  25492. const nextIndex = verticesArray.length / 3;
  25493. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25494. addUV( uvs[ 0 ] );
  25495. addUV( uvs[ 1 ] );
  25496. addUV( uvs[ 2 ] );
  25497. }
  25498. function f4( a, b, c, d ) {
  25499. addVertex( a );
  25500. addVertex( b );
  25501. addVertex( d );
  25502. addVertex( b );
  25503. addVertex( c );
  25504. addVertex( d );
  25505. const nextIndex = verticesArray.length / 3;
  25506. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25507. addUV( uvs[ 0 ] );
  25508. addUV( uvs[ 1 ] );
  25509. addUV( uvs[ 3 ] );
  25510. addUV( uvs[ 1 ] );
  25511. addUV( uvs[ 2 ] );
  25512. addUV( uvs[ 3 ] );
  25513. }
  25514. function addVertex( index ) {
  25515. verticesArray.push( placeholder[ index * 3 + 0 ] );
  25516. verticesArray.push( placeholder[ index * 3 + 1 ] );
  25517. verticesArray.push( placeholder[ index * 3 + 2 ] );
  25518. }
  25519. function addUV( vector2 ) {
  25520. uvArray.push( vector2.x );
  25521. uvArray.push( vector2.y );
  25522. }
  25523. }
  25524. }
  25525. copy( source ) {
  25526. super.copy( source );
  25527. this.parameters = Object.assign( {}, source.parameters );
  25528. return this;
  25529. }
  25530. toJSON() {
  25531. const data = super.toJSON();
  25532. const shapes = this.parameters.shapes;
  25533. const options = this.parameters.options;
  25534. return toJSON$1( shapes, options, data );
  25535. }
  25536. /**
  25537. * Factory method for creating an instance of this class from the given
  25538. * JSON object.
  25539. *
  25540. * @param {Object} data - A JSON object representing the serialized geometry.
  25541. * @param {Array<Shape>} shapes - An array of shapes.
  25542. * @return {ExtrudeGeometry} A new instance.
  25543. */
  25544. static fromJSON( data, shapes ) {
  25545. const geometryShapes = [];
  25546. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25547. const shape = shapes[ data.shapes[ j ] ];
  25548. geometryShapes.push( shape );
  25549. }
  25550. const extrudePath = data.options.extrudePath;
  25551. if ( extrudePath !== undefined ) {
  25552. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  25553. }
  25554. return new ExtrudeGeometry( geometryShapes, data.options );
  25555. }
  25556. }
  25557. const WorldUVGenerator = {
  25558. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  25559. const a_x = vertices[ indexA * 3 ];
  25560. const a_y = vertices[ indexA * 3 + 1 ];
  25561. const b_x = vertices[ indexB * 3 ];
  25562. const b_y = vertices[ indexB * 3 + 1 ];
  25563. const c_x = vertices[ indexC * 3 ];
  25564. const c_y = vertices[ indexC * 3 + 1 ];
  25565. return [
  25566. new Vector2( a_x, a_y ),
  25567. new Vector2( b_x, b_y ),
  25568. new Vector2( c_x, c_y )
  25569. ];
  25570. },
  25571. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  25572. const a_x = vertices[ indexA * 3 ];
  25573. const a_y = vertices[ indexA * 3 + 1 ];
  25574. const a_z = vertices[ indexA * 3 + 2 ];
  25575. const b_x = vertices[ indexB * 3 ];
  25576. const b_y = vertices[ indexB * 3 + 1 ];
  25577. const b_z = vertices[ indexB * 3 + 2 ];
  25578. const c_x = vertices[ indexC * 3 ];
  25579. const c_y = vertices[ indexC * 3 + 1 ];
  25580. const c_z = vertices[ indexC * 3 + 2 ];
  25581. const d_x = vertices[ indexD * 3 ];
  25582. const d_y = vertices[ indexD * 3 + 1 ];
  25583. const d_z = vertices[ indexD * 3 + 2 ];
  25584. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  25585. return [
  25586. new Vector2( a_x, 1 - a_z ),
  25587. new Vector2( b_x, 1 - b_z ),
  25588. new Vector2( c_x, 1 - c_z ),
  25589. new Vector2( d_x, 1 - d_z )
  25590. ];
  25591. } else {
  25592. return [
  25593. new Vector2( a_y, 1 - a_z ),
  25594. new Vector2( b_y, 1 - b_z ),
  25595. new Vector2( c_y, 1 - c_z ),
  25596. new Vector2( d_y, 1 - d_z )
  25597. ];
  25598. }
  25599. }
  25600. };
  25601. function toJSON$1( shapes, options, data ) {
  25602. data.shapes = [];
  25603. if ( Array.isArray( shapes ) ) {
  25604. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25605. const shape = shapes[ i ];
  25606. data.shapes.push( shape.uuid );
  25607. }
  25608. } else {
  25609. data.shapes.push( shapes.uuid );
  25610. }
  25611. data.options = Object.assign( {}, options );
  25612. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  25613. return data;
  25614. }
  25615. /**
  25616. * A geometry class for representing an icosahedron.
  25617. *
  25618. * ```js
  25619. * const geometry = new THREE.IcosahedronGeometry();
  25620. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25621. * const icosahedron = new THREE.Mesh( geometry, material );
  25622. * scene.add( icosahedron );
  25623. * ```
  25624. *
  25625. * @augments PolyhedronGeometry
  25626. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  25627. */
  25628. class IcosahedronGeometry extends PolyhedronGeometry {
  25629. /**
  25630. * Constructs a new icosahedron geometry.
  25631. *
  25632. * @param {number} [radius=1] - Radius of the icosahedron.
  25633. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  25634. */
  25635. constructor( radius = 1, detail = 0 ) {
  25636. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  25637. const vertices = [
  25638. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  25639. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  25640. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  25641. ];
  25642. const indices = [
  25643. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  25644. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  25645. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  25646. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  25647. ];
  25648. super( vertices, indices, radius, detail );
  25649. this.type = 'IcosahedronGeometry';
  25650. /**
  25651. * Holds the constructor parameters that have been
  25652. * used to generate the geometry. Any modification
  25653. * after instantiation does not change the geometry.
  25654. *
  25655. * @type {Object}
  25656. */
  25657. this.parameters = {
  25658. radius: radius,
  25659. detail: detail
  25660. };
  25661. }
  25662. /**
  25663. * Factory method for creating an instance of this class from the given
  25664. * JSON object.
  25665. *
  25666. * @param {Object} data - A JSON object representing the serialized geometry.
  25667. * @return {IcosahedronGeometry} A new instance.
  25668. */
  25669. static fromJSON( data ) {
  25670. return new IcosahedronGeometry( data.radius, data.detail );
  25671. }
  25672. }
  25673. /**
  25674. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  25675. *
  25676. * ```js
  25677. * const points = [];
  25678. * for ( let i = 0; i < 10; i ++ ) {
  25679. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  25680. * }
  25681. * const geometry = new THREE.LatheGeometry( points );
  25682. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25683. * const lathe = new THREE.Mesh( geometry, material );
  25684. * scene.add( lathe );
  25685. * ```
  25686. *
  25687. * @augments BufferGeometry
  25688. * @demo scenes/geometry-browser.html#LatheGeometry
  25689. */
  25690. class LatheGeometry extends BufferGeometry {
  25691. /**
  25692. * Constructs a new lathe geometry.
  25693. *
  25694. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  25695. * must be greater than zero.
  25696. * @param {number} [segments=12] - The number of circumference segments to generate.
  25697. * @param {number} [phiStart=0] - The starting angle in radians.
  25698. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  25699. * closed lathe, less than 2PI is a portion.
  25700. */
  25701. 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 ) {
  25702. super();
  25703. this.type = 'LatheGeometry';
  25704. /**
  25705. * Holds the constructor parameters that have been
  25706. * used to generate the geometry. Any modification
  25707. * after instantiation does not change the geometry.
  25708. *
  25709. * @type {Object}
  25710. */
  25711. this.parameters = {
  25712. points: points,
  25713. segments: segments,
  25714. phiStart: phiStart,
  25715. phiLength: phiLength
  25716. };
  25717. segments = Math.floor( segments );
  25718. // clamp phiLength so it's in range of [ 0, 2PI ]
  25719. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  25720. // buffers
  25721. const indices = [];
  25722. const vertices = [];
  25723. const uvs = [];
  25724. const initNormals = [];
  25725. const normals = [];
  25726. // helper variables
  25727. const inverseSegments = 1.0 / segments;
  25728. const vertex = new Vector3();
  25729. const uv = new Vector2();
  25730. const normal = new Vector3();
  25731. const curNormal = new Vector3();
  25732. const prevNormal = new Vector3();
  25733. let dx = 0;
  25734. let dy = 0;
  25735. // pre-compute normals for initial "meridian"
  25736. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  25737. switch ( j ) {
  25738. case 0: // special handling for 1st vertex on path
  25739. dx = points[ j + 1 ].x - points[ j ].x;
  25740. dy = points[ j + 1 ].y - points[ j ].y;
  25741. normal.x = dy * 1.0;
  25742. normal.y = - dx;
  25743. normal.z = dy * 0.0;
  25744. prevNormal.copy( normal );
  25745. normal.normalize();
  25746. initNormals.push( normal.x, normal.y, normal.z );
  25747. break;
  25748. case ( points.length - 1 ): // special handling for last Vertex on path
  25749. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  25750. break;
  25751. default: // default handling for all vertices in between
  25752. dx = points[ j + 1 ].x - points[ j ].x;
  25753. dy = points[ j + 1 ].y - points[ j ].y;
  25754. normal.x = dy * 1.0;
  25755. normal.y = - dx;
  25756. normal.z = dy * 0.0;
  25757. curNormal.copy( normal );
  25758. normal.x += prevNormal.x;
  25759. normal.y += prevNormal.y;
  25760. normal.z += prevNormal.z;
  25761. normal.normalize();
  25762. initNormals.push( normal.x, normal.y, normal.z );
  25763. prevNormal.copy( curNormal );
  25764. }
  25765. }
  25766. // generate vertices, uvs and normals
  25767. for ( let i = 0; i <= segments; i ++ ) {
  25768. const phi = phiStart + i * inverseSegments * phiLength;
  25769. const sin = Math.sin( phi );
  25770. const cos = Math.cos( phi );
  25771. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  25772. // vertex
  25773. vertex.x = points[ j ].x * sin;
  25774. vertex.y = points[ j ].y;
  25775. vertex.z = points[ j ].x * cos;
  25776. vertices.push( vertex.x, vertex.y, vertex.z );
  25777. // uv
  25778. uv.x = i / segments;
  25779. uv.y = j / ( points.length - 1 );
  25780. uvs.push( uv.x, uv.y );
  25781. // normal
  25782. const x = initNormals[ 3 * j + 0 ] * sin;
  25783. const y = initNormals[ 3 * j + 1 ];
  25784. const z = initNormals[ 3 * j + 0 ] * cos;
  25785. normals.push( x, y, z );
  25786. }
  25787. }
  25788. // indices
  25789. for ( let i = 0; i < segments; i ++ ) {
  25790. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  25791. const base = j + i * points.length;
  25792. const a = base;
  25793. const b = base + points.length;
  25794. const c = base + points.length + 1;
  25795. const d = base + 1;
  25796. // faces
  25797. indices.push( a, b, d );
  25798. indices.push( c, d, b );
  25799. }
  25800. }
  25801. // build geometry
  25802. this.setIndex( indices );
  25803. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25804. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25805. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25806. }
  25807. copy( source ) {
  25808. super.copy( source );
  25809. this.parameters = Object.assign( {}, source.parameters );
  25810. return this;
  25811. }
  25812. /**
  25813. * Factory method for creating an instance of this class from the given
  25814. * JSON object.
  25815. *
  25816. * @param {Object} data - A JSON object representing the serialized geometry.
  25817. * @return {LatheGeometry} A new instance.
  25818. */
  25819. static fromJSON( data ) {
  25820. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  25821. }
  25822. }
  25823. /**
  25824. * A geometry class for representing an octahedron.
  25825. *
  25826. * ```js
  25827. * const geometry = new THREE.OctahedronGeometry();
  25828. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25829. * const octahedron = new THREE.Mesh( geometry, material );
  25830. * scene.add( octahedron );
  25831. * ```
  25832. *
  25833. * @augments PolyhedronGeometry
  25834. * @demo scenes/geometry-browser.html#OctahedronGeometry
  25835. */
  25836. class OctahedronGeometry extends PolyhedronGeometry {
  25837. /**
  25838. * Constructs a new octahedron geometry.
  25839. *
  25840. * @param {number} [radius=1] - Radius of the octahedron.
  25841. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  25842. */
  25843. constructor( radius = 1, detail = 0 ) {
  25844. const vertices = [
  25845. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  25846. 0, -1, 0, 0, 0, 1, 0, 0, -1
  25847. ];
  25848. const indices = [
  25849. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  25850. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  25851. 1, 3, 4, 1, 4, 2
  25852. ];
  25853. super( vertices, indices, radius, detail );
  25854. this.type = 'OctahedronGeometry';
  25855. /**
  25856. * Holds the constructor parameters that have been
  25857. * used to generate the geometry. Any modification
  25858. * after instantiation does not change the geometry.
  25859. *
  25860. * @type {Object}
  25861. */
  25862. this.parameters = {
  25863. radius: radius,
  25864. detail: detail
  25865. };
  25866. }
  25867. /**
  25868. * Factory method for creating an instance of this class from the given
  25869. * JSON object.
  25870. *
  25871. * @param {Object} data - A JSON object representing the serialized geometry.
  25872. * @return {OctahedronGeometry} A new instance.
  25873. */
  25874. static fromJSON( data ) {
  25875. return new OctahedronGeometry( data.radius, data.detail );
  25876. }
  25877. }
  25878. /**
  25879. * A geometry class for representing a plane.
  25880. *
  25881. * ```js
  25882. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  25883. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  25884. * const plane = new THREE.Mesh( geometry, material );
  25885. * scene.add( plane );
  25886. * ```
  25887. *
  25888. * @augments BufferGeometry
  25889. * @demo scenes/geometry-browser.html#PlaneGeometry
  25890. */
  25891. class PlaneGeometry extends BufferGeometry {
  25892. /**
  25893. * Constructs a new plane geometry.
  25894. *
  25895. * @param {number} [width=1] - The width along the X axis.
  25896. * @param {number} [height=1] - The height along the Y axis
  25897. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  25898. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  25899. */
  25900. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  25901. super();
  25902. this.type = 'PlaneGeometry';
  25903. /**
  25904. * Holds the constructor parameters that have been
  25905. * used to generate the geometry. Any modification
  25906. * after instantiation does not change the geometry.
  25907. *
  25908. * @type {Object}
  25909. */
  25910. this.parameters = {
  25911. width: width,
  25912. height: height,
  25913. widthSegments: widthSegments,
  25914. heightSegments: heightSegments
  25915. };
  25916. const width_half = width / 2;
  25917. const height_half = height / 2;
  25918. const gridX = Math.floor( widthSegments );
  25919. const gridY = Math.floor( heightSegments );
  25920. const gridX1 = gridX + 1;
  25921. const gridY1 = gridY + 1;
  25922. const segment_width = width / gridX;
  25923. const segment_height = height / gridY;
  25924. //
  25925. const indices = [];
  25926. const vertices = [];
  25927. const normals = [];
  25928. const uvs = [];
  25929. for ( let iy = 0; iy < gridY1; iy ++ ) {
  25930. const y = iy * segment_height - height_half;
  25931. for ( let ix = 0; ix < gridX1; ix ++ ) {
  25932. const x = ix * segment_width - width_half;
  25933. vertices.push( x, - y, 0 );
  25934. normals.push( 0, 0, 1 );
  25935. uvs.push( ix / gridX );
  25936. uvs.push( 1 - ( iy / gridY ) );
  25937. }
  25938. }
  25939. for ( let iy = 0; iy < gridY; iy ++ ) {
  25940. for ( let ix = 0; ix < gridX; ix ++ ) {
  25941. const a = ix + gridX1 * iy;
  25942. const b = ix + gridX1 * ( iy + 1 );
  25943. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  25944. const d = ( ix + 1 ) + gridX1 * iy;
  25945. indices.push( a, b, d );
  25946. indices.push( b, c, d );
  25947. }
  25948. }
  25949. this.setIndex( indices );
  25950. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25951. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25952. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25953. }
  25954. copy( source ) {
  25955. super.copy( source );
  25956. this.parameters = Object.assign( {}, source.parameters );
  25957. return this;
  25958. }
  25959. /**
  25960. * Factory method for creating an instance of this class from the given
  25961. * JSON object.
  25962. *
  25963. * @param {Object} data - A JSON object representing the serialized geometry.
  25964. * @return {PlaneGeometry} A new instance.
  25965. */
  25966. static fromJSON( data ) {
  25967. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  25968. }
  25969. }
  25970. /**
  25971. * A class for generating a two-dimensional ring geometry.
  25972. *
  25973. * ```js
  25974. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  25975. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  25976. * const mesh = new THREE.Mesh( geometry, material );
  25977. * scene.add( mesh );
  25978. * ```
  25979. *
  25980. * @augments BufferGeometry
  25981. * @demo scenes/geometry-browser.html#RingGeometry
  25982. */
  25983. class RingGeometry extends BufferGeometry {
  25984. /**
  25985. * Constructs a new ring geometry.
  25986. *
  25987. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  25988. * @param {number} [outerRadius=1] - The outer radius of the ring.
  25989. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  25990. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  25991. * @param {number} [thetaStart=0] - Starting angle in radians.
  25992. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  25993. */
  25994. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  25995. super();
  25996. this.type = 'RingGeometry';
  25997. /**
  25998. * Holds the constructor parameters that have been
  25999. * used to generate the geometry. Any modification
  26000. * after instantiation does not change the geometry.
  26001. *
  26002. * @type {Object}
  26003. */
  26004. this.parameters = {
  26005. innerRadius: innerRadius,
  26006. outerRadius: outerRadius,
  26007. thetaSegments: thetaSegments,
  26008. phiSegments: phiSegments,
  26009. thetaStart: thetaStart,
  26010. thetaLength: thetaLength
  26011. };
  26012. thetaSegments = Math.max( 3, thetaSegments );
  26013. phiSegments = Math.max( 1, phiSegments );
  26014. // buffers
  26015. const indices = [];
  26016. const vertices = [];
  26017. const normals = [];
  26018. const uvs = [];
  26019. // some helper variables
  26020. let radius = innerRadius;
  26021. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26022. const vertex = new Vector3();
  26023. const uv = new Vector2();
  26024. // generate vertices, normals and uvs
  26025. for ( let j = 0; j <= phiSegments; j ++ ) {
  26026. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26027. // values are generate from the inside of the ring to the outside
  26028. const segment = thetaStart + i / thetaSegments * thetaLength;
  26029. // vertex
  26030. vertex.x = radius * Math.cos( segment );
  26031. vertex.y = radius * Math.sin( segment );
  26032. vertices.push( vertex.x, vertex.y, vertex.z );
  26033. // normal
  26034. normals.push( 0, 0, 1 );
  26035. // uv
  26036. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26037. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26038. uvs.push( uv.x, uv.y );
  26039. }
  26040. // increase the radius for next row of vertices
  26041. radius += radiusStep;
  26042. }
  26043. // indices
  26044. for ( let j = 0; j < phiSegments; j ++ ) {
  26045. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26046. for ( let i = 0; i < thetaSegments; i ++ ) {
  26047. const segment = i + thetaSegmentLevel;
  26048. const a = segment;
  26049. const b = segment + thetaSegments + 1;
  26050. const c = segment + thetaSegments + 2;
  26051. const d = segment + 1;
  26052. // faces
  26053. indices.push( a, b, d );
  26054. indices.push( b, c, d );
  26055. }
  26056. }
  26057. // build geometry
  26058. this.setIndex( indices );
  26059. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26060. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26061. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26062. }
  26063. copy( source ) {
  26064. super.copy( source );
  26065. this.parameters = Object.assign( {}, source.parameters );
  26066. return this;
  26067. }
  26068. /**
  26069. * Factory method for creating an instance of this class from the given
  26070. * JSON object.
  26071. *
  26072. * @param {Object} data - A JSON object representing the serialized geometry.
  26073. * @return {RingGeometry} A new instance.
  26074. */
  26075. static fromJSON( data ) {
  26076. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26077. }
  26078. }
  26079. /**
  26080. * Creates an one-sided polygonal geometry from one or more path shapes.
  26081. *
  26082. * ```js
  26083. * const arcShape = new THREE.Shape()
  26084. * .moveTo( 5, 1 )
  26085. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26086. *
  26087. * const geometry = new THREE.ShapeGeometry( arcShape );
  26088. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26089. * const mesh = new THREE.Mesh( geometry, material ) ;
  26090. * scene.add( mesh );
  26091. * ```
  26092. *
  26093. * @augments BufferGeometry
  26094. * @demo scenes/geometry-browser.html#ShapeGeometry
  26095. */
  26096. class ShapeGeometry extends BufferGeometry {
  26097. /**
  26098. * Constructs a new shape geometry.
  26099. *
  26100. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26101. * @param {number} [curveSegments=12] - Number of segments per shape.
  26102. */
  26103. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26104. super();
  26105. this.type = 'ShapeGeometry';
  26106. /**
  26107. * Holds the constructor parameters that have been
  26108. * used to generate the geometry. Any modification
  26109. * after instantiation does not change the geometry.
  26110. *
  26111. * @type {Object}
  26112. */
  26113. this.parameters = {
  26114. shapes: shapes,
  26115. curveSegments: curveSegments
  26116. };
  26117. // buffers
  26118. const indices = [];
  26119. const vertices = [];
  26120. const normals = [];
  26121. const uvs = [];
  26122. // helper variables
  26123. let groupStart = 0;
  26124. let groupCount = 0;
  26125. // allow single and array values for "shapes" parameter
  26126. if ( Array.isArray( shapes ) === false ) {
  26127. addShape( shapes );
  26128. } else {
  26129. for ( let i = 0; i < shapes.length; i ++ ) {
  26130. addShape( shapes[ i ] );
  26131. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26132. groupStart += groupCount;
  26133. groupCount = 0;
  26134. }
  26135. }
  26136. // build geometry
  26137. this.setIndex( indices );
  26138. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26139. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26140. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26141. // helper functions
  26142. function addShape( shape ) {
  26143. const indexOffset = vertices.length / 3;
  26144. const points = shape.extractPoints( curveSegments );
  26145. let shapeVertices = points.shape;
  26146. const shapeHoles = points.holes;
  26147. // check direction of vertices
  26148. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26149. shapeVertices = shapeVertices.reverse();
  26150. }
  26151. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26152. const shapeHole = shapeHoles[ i ];
  26153. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26154. shapeHoles[ i ] = shapeHole.reverse();
  26155. }
  26156. }
  26157. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26158. // join vertices of inner and outer paths to a single array
  26159. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26160. const shapeHole = shapeHoles[ i ];
  26161. shapeVertices = shapeVertices.concat( shapeHole );
  26162. }
  26163. // vertices, normals, uvs
  26164. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26165. const vertex = shapeVertices[ i ];
  26166. vertices.push( vertex.x, vertex.y, 0 );
  26167. normals.push( 0, 0, 1 );
  26168. uvs.push( vertex.x, vertex.y ); // world uvs
  26169. }
  26170. // indices
  26171. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26172. const face = faces[ i ];
  26173. const a = face[ 0 ] + indexOffset;
  26174. const b = face[ 1 ] + indexOffset;
  26175. const c = face[ 2 ] + indexOffset;
  26176. indices.push( a, b, c );
  26177. groupCount += 3;
  26178. }
  26179. }
  26180. }
  26181. copy( source ) {
  26182. super.copy( source );
  26183. this.parameters = Object.assign( {}, source.parameters );
  26184. return this;
  26185. }
  26186. toJSON() {
  26187. const data = super.toJSON();
  26188. const shapes = this.parameters.shapes;
  26189. return toJSON( shapes, data );
  26190. }
  26191. /**
  26192. * Factory method for creating an instance of this class from the given
  26193. * JSON object.
  26194. *
  26195. * @param {Object} data - A JSON object representing the serialized geometry.
  26196. * @param {Array<Shape>} shapes - An array of shapes.
  26197. * @return {ShapeGeometry} A new instance.
  26198. */
  26199. static fromJSON( data, shapes ) {
  26200. const geometryShapes = [];
  26201. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26202. const shape = shapes[ data.shapes[ j ] ];
  26203. geometryShapes.push( shape );
  26204. }
  26205. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26206. }
  26207. }
  26208. function toJSON( shapes, data ) {
  26209. data.shapes = [];
  26210. if ( Array.isArray( shapes ) ) {
  26211. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26212. const shape = shapes[ i ];
  26213. data.shapes.push( shape.uuid );
  26214. }
  26215. } else {
  26216. data.shapes.push( shapes.uuid );
  26217. }
  26218. return data;
  26219. }
  26220. /**
  26221. * A class for generating a sphere geometry.
  26222. *
  26223. * ```js
  26224. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26225. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26226. * const sphere = new THREE.Mesh( geometry, material );
  26227. * scene.add( sphere );
  26228. * ```
  26229. *
  26230. * @augments BufferGeometry
  26231. * @demo scenes/geometry-browser.html#SphereGeometry
  26232. */
  26233. class SphereGeometry extends BufferGeometry {
  26234. /**
  26235. * Constructs a new sphere geometry.
  26236. *
  26237. * @param {number} [radius=1] - The sphere radius.
  26238. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26239. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26240. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26241. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26242. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26243. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26244. */
  26245. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26246. super();
  26247. this.type = 'SphereGeometry';
  26248. /**
  26249. * Holds the constructor parameters that have been
  26250. * used to generate the geometry. Any modification
  26251. * after instantiation does not change the geometry.
  26252. *
  26253. * @type {Object}
  26254. */
  26255. this.parameters = {
  26256. radius: radius,
  26257. widthSegments: widthSegments,
  26258. heightSegments: heightSegments,
  26259. phiStart: phiStart,
  26260. phiLength: phiLength,
  26261. thetaStart: thetaStart,
  26262. thetaLength: thetaLength
  26263. };
  26264. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26265. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26266. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26267. let index = 0;
  26268. const grid = [];
  26269. const vertex = new Vector3();
  26270. const normal = new Vector3();
  26271. // buffers
  26272. const indices = [];
  26273. const vertices = [];
  26274. const normals = [];
  26275. const uvs = [];
  26276. // generate vertices, normals and uvs
  26277. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26278. const verticesRow = [];
  26279. const v = iy / heightSegments;
  26280. // special case for the poles
  26281. let uOffset = 0;
  26282. if ( iy === 0 && thetaStart === 0 ) {
  26283. uOffset = 0.5 / widthSegments;
  26284. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26285. uOffset = -0.5 / widthSegments;
  26286. }
  26287. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26288. const u = ix / widthSegments;
  26289. // vertex
  26290. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26291. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26292. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26293. vertices.push( vertex.x, vertex.y, vertex.z );
  26294. // normal
  26295. normal.copy( vertex ).normalize();
  26296. normals.push( normal.x, normal.y, normal.z );
  26297. // uv
  26298. uvs.push( u + uOffset, 1 - v );
  26299. verticesRow.push( index ++ );
  26300. }
  26301. grid.push( verticesRow );
  26302. }
  26303. // indices
  26304. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26305. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26306. const a = grid[ iy ][ ix + 1 ];
  26307. const b = grid[ iy ][ ix ];
  26308. const c = grid[ iy + 1 ][ ix ];
  26309. const d = grid[ iy + 1 ][ ix + 1 ];
  26310. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26311. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26312. }
  26313. }
  26314. // build geometry
  26315. this.setIndex( indices );
  26316. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26317. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26318. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26319. }
  26320. copy( source ) {
  26321. super.copy( source );
  26322. this.parameters = Object.assign( {}, source.parameters );
  26323. return this;
  26324. }
  26325. /**
  26326. * Factory method for creating an instance of this class from the given
  26327. * JSON object.
  26328. *
  26329. * @param {Object} data - A JSON object representing the serialized geometry.
  26330. * @return {SphereGeometry} A new instance.
  26331. */
  26332. static fromJSON( data ) {
  26333. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26334. }
  26335. }
  26336. /**
  26337. * A geometry class for representing an tetrahedron.
  26338. *
  26339. * ```js
  26340. * const geometry = new THREE.TetrahedronGeometry();
  26341. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26342. * const tetrahedron = new THREE.Mesh( geometry, material );
  26343. * scene.add( tetrahedron );
  26344. * ```
  26345. *
  26346. * @augments PolyhedronGeometry
  26347. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  26348. */
  26349. class TetrahedronGeometry extends PolyhedronGeometry {
  26350. /**
  26351. * Constructs a new tetrahedron geometry.
  26352. *
  26353. * @param {number} [radius=1] - Radius of the tetrahedron.
  26354. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26355. */
  26356. constructor( radius = 1, detail = 0 ) {
  26357. const vertices = [
  26358. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26359. ];
  26360. const indices = [
  26361. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26362. ];
  26363. super( vertices, indices, radius, detail );
  26364. this.type = 'TetrahedronGeometry';
  26365. /**
  26366. * Holds the constructor parameters that have been
  26367. * used to generate the geometry. Any modification
  26368. * after instantiation does not change the geometry.
  26369. *
  26370. * @type {Object}
  26371. */
  26372. this.parameters = {
  26373. radius: radius,
  26374. detail: detail
  26375. };
  26376. }
  26377. /**
  26378. * Factory method for creating an instance of this class from the given
  26379. * JSON object.
  26380. *
  26381. * @param {Object} data - A JSON object representing the serialized geometry.
  26382. * @return {TetrahedronGeometry} A new instance.
  26383. */
  26384. static fromJSON( data ) {
  26385. return new TetrahedronGeometry( data.radius, data.detail );
  26386. }
  26387. }
  26388. /**
  26389. * A geometry class for representing an torus.
  26390. *
  26391. * ```js
  26392. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26393. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26394. * const torus = new THREE.Mesh( geometry, material );
  26395. * scene.add( torus );
  26396. * ```
  26397. *
  26398. * @augments BufferGeometry
  26399. * @demo scenes/geometry-browser.html#TorusGeometry
  26400. */
  26401. class TorusGeometry extends BufferGeometry {
  26402. /**
  26403. * Constructs a new torus geometry.
  26404. *
  26405. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26406. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26407. * @param {number} [radialSegments=12] - The number of radial segments.
  26408. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26409. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26410. * @param {number} [thetaStart=0] - Start of the tubular sweep in radians.
  26411. * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians.
  26412. */
  26413. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26414. super();
  26415. this.type = 'TorusGeometry';
  26416. /**
  26417. * Holds the constructor parameters that have been
  26418. * used to generate the geometry. Any modification
  26419. * after instantiation does not change the geometry.
  26420. *
  26421. * @type {Object}
  26422. */
  26423. this.parameters = {
  26424. radius: radius,
  26425. tube: tube,
  26426. radialSegments: radialSegments,
  26427. tubularSegments: tubularSegments,
  26428. arc: arc,
  26429. thetaStart: thetaStart,
  26430. thetaLength: thetaLength,
  26431. };
  26432. radialSegments = Math.floor( radialSegments );
  26433. tubularSegments = Math.floor( tubularSegments );
  26434. // buffers
  26435. const indices = [];
  26436. const vertices = [];
  26437. const normals = [];
  26438. const uvs = [];
  26439. // helper variables
  26440. const center = new Vector3();
  26441. const vertex = new Vector3();
  26442. const normal = new Vector3();
  26443. // generate vertices, normals and uvs
  26444. for ( let j = 0; j <= radialSegments; j ++ ) {
  26445. const v = thetaStart + ( j / radialSegments ) * thetaLength;
  26446. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26447. const u = i / tubularSegments * arc;
  26448. // vertex
  26449. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  26450. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  26451. vertex.z = tube * Math.sin( v );
  26452. vertices.push( vertex.x, vertex.y, vertex.z );
  26453. // normal
  26454. center.x = radius * Math.cos( u );
  26455. center.y = radius * Math.sin( u );
  26456. normal.subVectors( vertex, center ).normalize();
  26457. normals.push( normal.x, normal.y, normal.z );
  26458. // uv
  26459. uvs.push( i / tubularSegments );
  26460. uvs.push( j / radialSegments );
  26461. }
  26462. }
  26463. // generate indices
  26464. for ( let j = 1; j <= radialSegments; j ++ ) {
  26465. for ( let i = 1; i <= tubularSegments; i ++ ) {
  26466. // indices
  26467. const a = ( tubularSegments + 1 ) * j + i - 1;
  26468. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  26469. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  26470. const d = ( tubularSegments + 1 ) * j + i;
  26471. // faces
  26472. indices.push( a, b, d );
  26473. indices.push( b, c, d );
  26474. }
  26475. }
  26476. // build geometry
  26477. this.setIndex( indices );
  26478. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26479. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26480. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26481. }
  26482. copy( source ) {
  26483. super.copy( source );
  26484. this.parameters = Object.assign( {}, source.parameters );
  26485. return this;
  26486. }
  26487. /**
  26488. * Factory method for creating an instance of this class from the given
  26489. * JSON object.
  26490. *
  26491. * @param {Object} data - A JSON object representing the serialized geometry.
  26492. * @return {TorusGeometry} A new instance.
  26493. */
  26494. static fromJSON( data ) {
  26495. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  26496. }
  26497. }
  26498. /**
  26499. * Creates a torus knot, the particular shape of which is defined by a pair
  26500. * of coprime integers, p and q. If p and q are not coprime, the result will
  26501. * be a torus link.
  26502. *
  26503. * ```js
  26504. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  26505. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26506. * const torusKnot = new THREE.Mesh( geometry, material );
  26507. * scene.add( torusKnot );
  26508. * ```
  26509. *
  26510. * @augments BufferGeometry
  26511. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  26512. */
  26513. class TorusKnotGeometry extends BufferGeometry {
  26514. /**
  26515. * Constructs a new torus knot geometry.
  26516. *
  26517. * @param {number} [radius=1] - Radius of the torus knot.
  26518. * @param {number} [tube=0.4] - Radius of the tube.
  26519. * @param {number} [tubularSegments=64] - The number of tubular segments.
  26520. * @param {number} [radialSegments=8] - The number of radial segments.
  26521. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  26522. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  26523. */
  26524. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  26525. super();
  26526. this.type = 'TorusKnotGeometry';
  26527. /**
  26528. * Holds the constructor parameters that have been
  26529. * used to generate the geometry. Any modification
  26530. * after instantiation does not change the geometry.
  26531. *
  26532. * @type {Object}
  26533. */
  26534. this.parameters = {
  26535. radius: radius,
  26536. tube: tube,
  26537. tubularSegments: tubularSegments,
  26538. radialSegments: radialSegments,
  26539. p: p,
  26540. q: q
  26541. };
  26542. tubularSegments = Math.floor( tubularSegments );
  26543. radialSegments = Math.floor( radialSegments );
  26544. // buffers
  26545. const indices = [];
  26546. const vertices = [];
  26547. const normals = [];
  26548. const uvs = [];
  26549. // helper variables
  26550. const vertex = new Vector3();
  26551. const normal = new Vector3();
  26552. const P1 = new Vector3();
  26553. const P2 = new Vector3();
  26554. const B = new Vector3();
  26555. const T = new Vector3();
  26556. const N = new Vector3();
  26557. // generate vertices, normals and uvs
  26558. for ( let i = 0; i <= tubularSegments; ++ i ) {
  26559. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  26560. const u = i / tubularSegments * p * Math.PI * 2;
  26561. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  26562. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  26563. calculatePositionOnCurve( u, p, q, radius, P1 );
  26564. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  26565. // calculate orthonormal basis
  26566. T.subVectors( P2, P1 );
  26567. N.addVectors( P2, P1 );
  26568. B.crossVectors( T, N );
  26569. N.crossVectors( B, T );
  26570. // normalize B, N. T can be ignored, we don't use it
  26571. B.normalize();
  26572. N.normalize();
  26573. for ( let j = 0; j <= radialSegments; ++ j ) {
  26574. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  26575. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  26576. const v = j / radialSegments * Math.PI * 2;
  26577. const cx = - tube * Math.cos( v );
  26578. const cy = tube * Math.sin( v );
  26579. // now calculate the final vertex position.
  26580. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  26581. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  26582. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  26583. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  26584. vertices.push( vertex.x, vertex.y, vertex.z );
  26585. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  26586. normal.subVectors( vertex, P1 ).normalize();
  26587. normals.push( normal.x, normal.y, normal.z );
  26588. // uv
  26589. uvs.push( i / tubularSegments );
  26590. uvs.push( j / radialSegments );
  26591. }
  26592. }
  26593. // generate indices
  26594. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26595. for ( let i = 1; i <= radialSegments; i ++ ) {
  26596. // indices
  26597. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26598. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26599. const c = ( radialSegments + 1 ) * j + i;
  26600. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26601. // faces
  26602. indices.push( a, b, d );
  26603. indices.push( b, c, d );
  26604. }
  26605. }
  26606. // build geometry
  26607. this.setIndex( indices );
  26608. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26609. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26610. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26611. // this function calculates the current position on the torus curve
  26612. function calculatePositionOnCurve( u, p, q, radius, position ) {
  26613. const cu = Math.cos( u );
  26614. const su = Math.sin( u );
  26615. const quOverP = q / p * u;
  26616. const cs = Math.cos( quOverP );
  26617. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  26618. position.y = radius * ( 2 + cs ) * su * 0.5;
  26619. position.z = radius * Math.sin( quOverP ) * 0.5;
  26620. }
  26621. }
  26622. copy( source ) {
  26623. super.copy( source );
  26624. this.parameters = Object.assign( {}, source.parameters );
  26625. return this;
  26626. }
  26627. /**
  26628. * Factory method for creating an instance of this class from the given
  26629. * JSON object.
  26630. *
  26631. * @param {Object} data - A JSON object representing the serialized geometry.
  26632. * @return {TorusKnotGeometry} A new instance.
  26633. */
  26634. static fromJSON( data ) {
  26635. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  26636. }
  26637. }
  26638. /**
  26639. * Creates a tube that extrudes along a 3D curve.
  26640. *
  26641. * ```js
  26642. * class CustomSinCurve extends THREE.Curve {
  26643. *
  26644. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  26645. *
  26646. * const tx = t * 3 - 1.5;
  26647. * const ty = Math.sin( 2 * Math.PI * t );
  26648. * const tz = 0;
  26649. *
  26650. * return optionalTarget.set( tx, ty, tz );
  26651. * }
  26652. *
  26653. * }
  26654. *
  26655. * const path = new CustomSinCurve( 10 );
  26656. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  26657. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  26658. * const mesh = new THREE.Mesh( geometry, material );
  26659. * scene.add( mesh );
  26660. * ```
  26661. *
  26662. * @augments BufferGeometry
  26663. * @demo scenes/geometry-browser.html#TubeGeometry
  26664. */
  26665. class TubeGeometry extends BufferGeometry {
  26666. /**
  26667. * Constructs a new tube geometry.
  26668. *
  26669. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  26670. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  26671. * @param {number} [radius=1] -The radius of the tube.
  26672. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  26673. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  26674. */
  26675. 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 ) {
  26676. super();
  26677. this.type = 'TubeGeometry';
  26678. /**
  26679. * Holds the constructor parameters that have been
  26680. * used to generate the geometry. Any modification
  26681. * after instantiation does not change the geometry.
  26682. *
  26683. * @type {Object}
  26684. */
  26685. this.parameters = {
  26686. path: path,
  26687. tubularSegments: tubularSegments,
  26688. radius: radius,
  26689. radialSegments: radialSegments,
  26690. closed: closed
  26691. };
  26692. const frames = path.computeFrenetFrames( tubularSegments, closed );
  26693. // expose internals
  26694. this.tangents = frames.tangents;
  26695. this.normals = frames.normals;
  26696. this.binormals = frames.binormals;
  26697. // helper variables
  26698. const vertex = new Vector3();
  26699. const normal = new Vector3();
  26700. const uv = new Vector2();
  26701. let P = new Vector3();
  26702. // buffer
  26703. const vertices = [];
  26704. const normals = [];
  26705. const uvs = [];
  26706. const indices = [];
  26707. // create buffer data
  26708. generateBufferData();
  26709. // build geometry
  26710. this.setIndex( indices );
  26711. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26712. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26713. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26714. // functions
  26715. function generateBufferData() {
  26716. for ( let i = 0; i < tubularSegments; i ++ ) {
  26717. generateSegment( i );
  26718. }
  26719. // if the geometry is not closed, generate the last row of vertices and normals
  26720. // at the regular position on the given path
  26721. //
  26722. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  26723. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  26724. // uvs are generated in a separate function.
  26725. // this makes it easy compute correct values for closed geometries
  26726. generateUVs();
  26727. // finally create faces
  26728. generateIndices();
  26729. }
  26730. function generateSegment( i ) {
  26731. // we use getPointAt to sample evenly distributed points from the given path
  26732. P = path.getPointAt( i / tubularSegments, P );
  26733. // retrieve corresponding normal and binormal
  26734. const N = frames.normals[ i ];
  26735. const B = frames.binormals[ i ];
  26736. // generate normals and vertices for the current segment
  26737. for ( let j = 0; j <= radialSegments; j ++ ) {
  26738. const v = j / radialSegments * Math.PI * 2;
  26739. const sin = Math.sin( v );
  26740. const cos = - Math.cos( v );
  26741. // normal
  26742. normal.x = ( cos * N.x + sin * B.x );
  26743. normal.y = ( cos * N.y + sin * B.y );
  26744. normal.z = ( cos * N.z + sin * B.z );
  26745. normal.normalize();
  26746. normals.push( normal.x, normal.y, normal.z );
  26747. // vertex
  26748. vertex.x = P.x + radius * normal.x;
  26749. vertex.y = P.y + radius * normal.y;
  26750. vertex.z = P.z + radius * normal.z;
  26751. vertices.push( vertex.x, vertex.y, vertex.z );
  26752. }
  26753. }
  26754. function generateIndices() {
  26755. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26756. for ( let i = 1; i <= radialSegments; i ++ ) {
  26757. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26758. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26759. const c = ( radialSegments + 1 ) * j + i;
  26760. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26761. // faces
  26762. indices.push( a, b, d );
  26763. indices.push( b, c, d );
  26764. }
  26765. }
  26766. }
  26767. function generateUVs() {
  26768. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26769. for ( let j = 0; j <= radialSegments; j ++ ) {
  26770. uv.x = i / tubularSegments;
  26771. uv.y = j / radialSegments;
  26772. uvs.push( uv.x, uv.y );
  26773. }
  26774. }
  26775. }
  26776. }
  26777. copy( source ) {
  26778. super.copy( source );
  26779. this.parameters = Object.assign( {}, source.parameters );
  26780. return this;
  26781. }
  26782. toJSON() {
  26783. const data = super.toJSON();
  26784. data.path = this.parameters.path.toJSON();
  26785. return data;
  26786. }
  26787. /**
  26788. * Factory method for creating an instance of this class from the given
  26789. * JSON object.
  26790. *
  26791. * @param {Object} data - A JSON object representing the serialized geometry.
  26792. * @return {TubeGeometry} A new instance.
  26793. */
  26794. static fromJSON( data ) {
  26795. // This only works for built-in curves (e.g. CatmullRomCurve3).
  26796. // User defined curves or instances of CurvePath will not be deserialized.
  26797. return new TubeGeometry(
  26798. new Curves[ data.path.type ]().fromJSON( data.path ),
  26799. data.tubularSegments,
  26800. data.radius,
  26801. data.radialSegments,
  26802. data.closed
  26803. );
  26804. }
  26805. }
  26806. /**
  26807. * Can be used as a helper object to visualize a geometry as a wireframe.
  26808. *
  26809. * ```js
  26810. * const geometry = new THREE.SphereGeometry();
  26811. *
  26812. * const wireframe = new THREE.WireframeGeometry( geometry );
  26813. *
  26814. * const line = new THREE.LineSegments( wireframe );
  26815. * line.material.depthWrite = false;
  26816. * line.material.opacity = 0.25;
  26817. * line.material.transparent = true;
  26818. *
  26819. * scene.add( line );
  26820. * ```
  26821. *
  26822. * Note: It is not yet possible to serialize/deserialize instances of this class.
  26823. *
  26824. * @augments BufferGeometry
  26825. */
  26826. class WireframeGeometry extends BufferGeometry {
  26827. /**
  26828. * Constructs a new wireframe geometry.
  26829. *
  26830. * @param {?BufferGeometry} [geometry=null] - The geometry.
  26831. */
  26832. constructor( geometry = null ) {
  26833. super();
  26834. this.type = 'WireframeGeometry';
  26835. /**
  26836. * Holds the constructor parameters that have been
  26837. * used to generate the geometry. Any modification
  26838. * after instantiation does not change the geometry.
  26839. *
  26840. * @type {Object}
  26841. */
  26842. this.parameters = {
  26843. geometry: geometry
  26844. };
  26845. if ( geometry !== null ) {
  26846. // buffer
  26847. const vertices = [];
  26848. const edges = new Set();
  26849. // helper variables
  26850. const start = new Vector3();
  26851. const end = new Vector3();
  26852. if ( geometry.index !== null ) {
  26853. // indexed BufferGeometry
  26854. const position = geometry.attributes.position;
  26855. const indices = geometry.index;
  26856. let groups = geometry.groups;
  26857. if ( groups.length === 0 ) {
  26858. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  26859. }
  26860. // create a data structure that contains all edges without duplicates
  26861. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  26862. const group = groups[ o ];
  26863. const groupStart = group.start;
  26864. const groupCount = group.count;
  26865. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  26866. for ( let j = 0; j < 3; j ++ ) {
  26867. const index1 = indices.getX( i + j );
  26868. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  26869. start.fromBufferAttribute( position, index1 );
  26870. end.fromBufferAttribute( position, index2 );
  26871. if ( isUniqueEdge( start, end, edges ) === true ) {
  26872. vertices.push( start.x, start.y, start.z );
  26873. vertices.push( end.x, end.y, end.z );
  26874. }
  26875. }
  26876. }
  26877. }
  26878. } else {
  26879. // non-indexed BufferGeometry
  26880. const position = geometry.attributes.position;
  26881. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  26882. for ( let j = 0; j < 3; j ++ ) {
  26883. // three edges per triangle, an edge is represented as (index1, index2)
  26884. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  26885. const index1 = 3 * i + j;
  26886. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  26887. start.fromBufferAttribute( position, index1 );
  26888. end.fromBufferAttribute( position, index2 );
  26889. if ( isUniqueEdge( start, end, edges ) === true ) {
  26890. vertices.push( start.x, start.y, start.z );
  26891. vertices.push( end.x, end.y, end.z );
  26892. }
  26893. }
  26894. }
  26895. }
  26896. // build geometry
  26897. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26898. }
  26899. }
  26900. copy( source ) {
  26901. super.copy( source );
  26902. this.parameters = Object.assign( {}, source.parameters );
  26903. return this;
  26904. }
  26905. }
  26906. function isUniqueEdge( start, end, edges ) {
  26907. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  26908. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  26909. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  26910. return false;
  26911. } else {
  26912. edges.add( hash1 );
  26913. edges.add( hash2 );
  26914. return true;
  26915. }
  26916. }
  26917. var Geometries = /*#__PURE__*/Object.freeze({
  26918. __proto__: null,
  26919. BoxGeometry: BoxGeometry,
  26920. CapsuleGeometry: CapsuleGeometry,
  26921. CircleGeometry: CircleGeometry,
  26922. ConeGeometry: ConeGeometry,
  26923. CylinderGeometry: CylinderGeometry,
  26924. DodecahedronGeometry: DodecahedronGeometry,
  26925. EdgesGeometry: EdgesGeometry,
  26926. ExtrudeGeometry: ExtrudeGeometry,
  26927. IcosahedronGeometry: IcosahedronGeometry,
  26928. LatheGeometry: LatheGeometry,
  26929. OctahedronGeometry: OctahedronGeometry,
  26930. PlaneGeometry: PlaneGeometry,
  26931. PolyhedronGeometry: PolyhedronGeometry,
  26932. RingGeometry: RingGeometry,
  26933. ShapeGeometry: ShapeGeometry,
  26934. SphereGeometry: SphereGeometry,
  26935. TetrahedronGeometry: TetrahedronGeometry,
  26936. TorusGeometry: TorusGeometry,
  26937. TorusKnotGeometry: TorusKnotGeometry,
  26938. TubeGeometry: TubeGeometry,
  26939. WireframeGeometry: WireframeGeometry
  26940. });
  26941. /**
  26942. * This material can receive shadows, but otherwise is completely transparent.
  26943. *
  26944. * ```js
  26945. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  26946. * geometry.rotateX( - Math.PI / 2 );
  26947. *
  26948. * const material = new THREE.ShadowMaterial();
  26949. * material.opacity = 0.2;
  26950. *
  26951. * const plane = new THREE.Mesh( geometry, material );
  26952. * plane.position.y = -200;
  26953. * plane.receiveShadow = true;
  26954. * scene.add( plane );
  26955. * ```
  26956. *
  26957. * @augments Material
  26958. */
  26959. class ShadowMaterial extends Material {
  26960. /**
  26961. * Constructs a new shadow material.
  26962. *
  26963. * @param {Object} [parameters] - An object with one or more properties
  26964. * defining the material's appearance. Any property of the material
  26965. * (including any property from inherited materials) can be passed
  26966. * in here. Color values can be passed any type of value accepted
  26967. * by {@link Color#set}.
  26968. */
  26969. constructor( parameters ) {
  26970. super();
  26971. /**
  26972. * This flag can be used for type testing.
  26973. *
  26974. * @type {boolean}
  26975. * @readonly
  26976. * @default true
  26977. */
  26978. this.isShadowMaterial = true;
  26979. this.type = 'ShadowMaterial';
  26980. /**
  26981. * Color of the material.
  26982. *
  26983. * @type {Color}
  26984. * @default (0,0,0)
  26985. */
  26986. this.color = new Color( 0x000000 );
  26987. /**
  26988. * Overwritten since shadow materials are transparent
  26989. * by default.
  26990. *
  26991. * @type {boolean}
  26992. * @default true
  26993. */
  26994. this.transparent = true;
  26995. /**
  26996. * Whether the material is affected by fog or not.
  26997. *
  26998. * @type {boolean}
  26999. * @default true
  27000. */
  27001. this.fog = true;
  27002. this.setValues( parameters );
  27003. }
  27004. copy( source ) {
  27005. super.copy( source );
  27006. this.color.copy( source.color );
  27007. this.fog = source.fog;
  27008. return this;
  27009. }
  27010. }
  27011. /**
  27012. * Provides utility functions for managing uniforms.
  27013. *
  27014. * @module UniformsUtils
  27015. */
  27016. /**
  27017. * Clones the given uniform definitions by performing a deep-copy. That means
  27018. * if the value of a uniform refers to an object like a Vector3 or Texture,
  27019. * the cloned uniform will refer to a new object reference.
  27020. *
  27021. * @param {Object} src - An object representing uniform definitions.
  27022. * @return {Object} The cloned uniforms.
  27023. */
  27024. function cloneUniforms( src ) {
  27025. const dst = {};
  27026. for ( const u in src ) {
  27027. dst[ u ] = {};
  27028. for ( const p in src[ u ] ) {
  27029. const property = src[ u ][ p ];
  27030. if ( property && ( property.isColor ||
  27031. property.isMatrix3 || property.isMatrix4 ||
  27032. property.isVector2 || property.isVector3 || property.isVector4 ||
  27033. property.isTexture || property.isQuaternion ) ) {
  27034. if ( property.isRenderTargetTexture ) {
  27035. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  27036. dst[ u ][ p ] = null;
  27037. } else {
  27038. dst[ u ][ p ] = property.clone();
  27039. }
  27040. } else if ( Array.isArray( property ) ) {
  27041. dst[ u ][ p ] = property.slice();
  27042. } else {
  27043. dst[ u ][ p ] = property;
  27044. }
  27045. }
  27046. }
  27047. return dst;
  27048. }
  27049. /**
  27050. * Merges the given uniform definitions into a single object. Since the
  27051. * method internally uses cloneUniforms(), it performs a deep-copy when
  27052. * producing the merged uniform definitions.
  27053. *
  27054. * @param {Array} uniforms - An array of objects containing uniform definitions.
  27055. * @return {Object} The merged uniforms.
  27056. */
  27057. function mergeUniforms( uniforms ) {
  27058. const merged = {};
  27059. for ( let u = 0; u < uniforms.length; u ++ ) {
  27060. const tmp = cloneUniforms( uniforms[ u ] );
  27061. for ( const p in tmp ) {
  27062. merged[ p ] = tmp[ p ];
  27063. }
  27064. }
  27065. return merged;
  27066. }
  27067. function cloneUniformsGroups( src ) {
  27068. const dst = [];
  27069. for ( let u = 0; u < src.length; u ++ ) {
  27070. dst.push( src[ u ].clone() );
  27071. }
  27072. return dst;
  27073. }
  27074. function getUnlitUniformColorSpace( renderer ) {
  27075. const currentRenderTarget = renderer.getRenderTarget();
  27076. if ( currentRenderTarget === null ) {
  27077. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  27078. return renderer.outputColorSpace;
  27079. }
  27080. // https://github.com/mrdoob/three.js/issues/27868
  27081. if ( currentRenderTarget.isXRRenderTarget === true ) {
  27082. return currentRenderTarget.texture.colorSpace;
  27083. }
  27084. return ColorManagement.workingColorSpace;
  27085. }
  27086. // Legacy
  27087. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  27088. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  27089. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  27090. /**
  27091. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  27092. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  27093. * effect not included with any of the built-in materials.
  27094. *
  27095. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  27096. *
  27097. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  27098. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  27099. * you don't want that, use {@link RawShaderMaterial} instead.
  27100. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  27101. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  27102. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  27103. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  27104. * - The loop variable has to be *i*.
  27105. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  27106. * value of *i* for the given iteration and can be used in preprocessor
  27107. * statements.
  27108. *
  27109. * ```js
  27110. * const material = new THREE.ShaderMaterial( {
  27111. * uniforms: {
  27112. * time: { value: 1.0 },
  27113. * resolution: { value: new THREE.Vector2() }
  27114. * },
  27115. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  27116. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  27117. * } );
  27118. * ```
  27119. *
  27120. * @augments Material
  27121. */
  27122. class ShaderMaterial extends Material {
  27123. /**
  27124. * Constructs a new shader material.
  27125. *
  27126. * @param {Object} [parameters] - An object with one or more properties
  27127. * defining the material's appearance. Any property of the material
  27128. * (including any property from inherited materials) can be passed
  27129. * in here. Color values can be passed any type of value accepted
  27130. * by {@link Color#set}.
  27131. */
  27132. constructor( parameters ) {
  27133. super();
  27134. /**
  27135. * This flag can be used for type testing.
  27136. *
  27137. * @type {boolean}
  27138. * @readonly
  27139. * @default true
  27140. */
  27141. this.isShaderMaterial = true;
  27142. this.type = 'ShaderMaterial';
  27143. /**
  27144. * Defines custom constants using `#define` directives within the GLSL code
  27145. * for both the vertex shader and the fragment shader; each key/value pair
  27146. * yields another directive.
  27147. * ```js
  27148. * defines: {
  27149. * FOO: 15,
  27150. * BAR: true
  27151. * }
  27152. * ```
  27153. * Yields the lines:
  27154. * ```
  27155. * #define FOO 15
  27156. * #define BAR true
  27157. * ```
  27158. *
  27159. * @type {Object}
  27160. */
  27161. this.defines = {};
  27162. /**
  27163. * An object of the form:
  27164. * ```js
  27165. * {
  27166. * "uniform1": { value: 1.0 },
  27167. * "uniform2": { value: 2 }
  27168. * }
  27169. * ```
  27170. * specifying the uniforms to be passed to the shader code; keys are uniform
  27171. * names, values are definitions of the form
  27172. * ```
  27173. * {
  27174. * value: 1.0
  27175. * }
  27176. * ```
  27177. * where `value` is the value of the uniform. Names must match the name of
  27178. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  27179. * on every frame, so updating the value of the uniform will immediately
  27180. * update the value available to the GLSL code.
  27181. *
  27182. * @type {Object}
  27183. */
  27184. this.uniforms = {};
  27185. /**
  27186. * An array holding uniforms groups for configuring UBOs.
  27187. *
  27188. * @type {Array<UniformsGroup>}
  27189. */
  27190. this.uniformsGroups = [];
  27191. /**
  27192. * Vertex shader GLSL code. This is the actual code for the shader.
  27193. *
  27194. * @type {string}
  27195. */
  27196. this.vertexShader = default_vertex;
  27197. /**
  27198. * Fragment shader GLSL code. This is the actual code for the shader.
  27199. *
  27200. * @type {string}
  27201. */
  27202. this.fragmentShader = default_fragment;
  27203. /**
  27204. * Controls line thickness or lines.
  27205. *
  27206. * WebGL and WebGPU ignore this setting and always render line primitives with a
  27207. * width of one pixel.
  27208. *
  27209. * @type {number}
  27210. * @default 1
  27211. */
  27212. this.linewidth = 1;
  27213. /**
  27214. * Renders the geometry as a wireframe.
  27215. *
  27216. * @type {boolean}
  27217. * @default false
  27218. */
  27219. this.wireframe = false;
  27220. /**
  27221. * Controls the thickness of the wireframe.
  27222. *
  27223. * WebGL and WebGPU ignore this property and always render
  27224. * 1 pixel wide lines.
  27225. *
  27226. * @type {number}
  27227. * @default 1
  27228. */
  27229. this.wireframeLinewidth = 1;
  27230. /**
  27231. * Defines whether the material color is affected by global fog settings; `true`
  27232. * to pass fog uniforms to the shader.
  27233. *
  27234. * Setting this property to `true` requires the definition of fog uniforms. It is
  27235. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  27236. * with predefined fog uniforms.
  27237. *
  27238. * ```js
  27239. * const material = new ShaderMaterial( {
  27240. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  27241. * vertexShader: vertexShader,
  27242. * fragmentShader: fragmentShader,
  27243. * fog: true
  27244. * } );
  27245. * ```
  27246. *
  27247. * @type {boolean}
  27248. * @default false
  27249. */
  27250. this.fog = false;
  27251. /**
  27252. * Defines whether this material uses lighting; `true` to pass uniform data
  27253. * related to lighting to this shader.
  27254. *
  27255. * @type {boolean}
  27256. * @default false
  27257. */
  27258. this.lights = false;
  27259. /**
  27260. * Defines whether this material supports clipping; `true` to let the renderer
  27261. * pass the clippingPlanes uniform.
  27262. *
  27263. * @type {boolean}
  27264. * @default false
  27265. */
  27266. this.clipping = false;
  27267. /**
  27268. * Overwritten and set to `true` by default.
  27269. *
  27270. * @type {boolean}
  27271. * @default true
  27272. */
  27273. this.forceSinglePass = true;
  27274. /**
  27275. * This object allows to enable certain WebGL 2 extensions.
  27276. *
  27277. * - clipCullDistance: set to `true` to use vertex shader clipping
  27278. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  27279. *
  27280. * @type {{clipCullDistance:false,multiDraw:false}}
  27281. */
  27282. this.extensions = {
  27283. clipCullDistance: false, // set to use vertex shader clipping
  27284. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  27285. };
  27286. /**
  27287. * When the rendered geometry doesn't include these attributes but the
  27288. * material does, these default values will be passed to the shaders. This
  27289. * avoids errors when buffer data is missing.
  27290. *
  27291. * - color: [ 1, 1, 1 ]
  27292. * - uv: [ 0, 0 ]
  27293. * - uv1: [ 0, 0 ]
  27294. *
  27295. * @type {Object}
  27296. */
  27297. this.defaultAttributeValues = {
  27298. 'color': [ 1, 1, 1 ],
  27299. 'uv': [ 0, 0 ],
  27300. 'uv1': [ 0, 0 ]
  27301. };
  27302. /**
  27303. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  27304. * to bind a generic vertex index to an attribute variable.
  27305. *
  27306. * @type {string|undefined}
  27307. * @default undefined
  27308. */
  27309. this.index0AttributeName = undefined;
  27310. /**
  27311. * Can be used to force a uniform update while changing uniforms in
  27312. * {@link Object3D#onBeforeRender}.
  27313. *
  27314. * @type {boolean}
  27315. * @default false
  27316. */
  27317. this.uniformsNeedUpdate = false;
  27318. /**
  27319. * Defines the GLSL version of custom shader code.
  27320. *
  27321. * @type {?(GLSL1|GLSL3)}
  27322. * @default null
  27323. */
  27324. this.glslVersion = null;
  27325. if ( parameters !== undefined ) {
  27326. this.setValues( parameters );
  27327. }
  27328. }
  27329. copy( source ) {
  27330. super.copy( source );
  27331. this.fragmentShader = source.fragmentShader;
  27332. this.vertexShader = source.vertexShader;
  27333. this.uniforms = cloneUniforms( source.uniforms );
  27334. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  27335. this.defines = Object.assign( {}, source.defines );
  27336. this.wireframe = source.wireframe;
  27337. this.wireframeLinewidth = source.wireframeLinewidth;
  27338. this.fog = source.fog;
  27339. this.lights = source.lights;
  27340. this.clipping = source.clipping;
  27341. this.extensions = Object.assign( {}, source.extensions );
  27342. this.glslVersion = source.glslVersion;
  27343. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  27344. this.index0AttributeName = source.index0AttributeName;
  27345. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  27346. return this;
  27347. }
  27348. toJSON( meta ) {
  27349. const data = super.toJSON( meta );
  27350. data.glslVersion = this.glslVersion;
  27351. data.uniforms = {};
  27352. for ( const name in this.uniforms ) {
  27353. const uniform = this.uniforms[ name ];
  27354. const value = uniform.value;
  27355. if ( value && value.isTexture ) {
  27356. data.uniforms[ name ] = {
  27357. type: 't',
  27358. value: value.toJSON( meta ).uuid
  27359. };
  27360. } else if ( value && value.isColor ) {
  27361. data.uniforms[ name ] = {
  27362. type: 'c',
  27363. value: value.getHex()
  27364. };
  27365. } else if ( value && value.isVector2 ) {
  27366. data.uniforms[ name ] = {
  27367. type: 'v2',
  27368. value: value.toArray()
  27369. };
  27370. } else if ( value && value.isVector3 ) {
  27371. data.uniforms[ name ] = {
  27372. type: 'v3',
  27373. value: value.toArray()
  27374. };
  27375. } else if ( value && value.isVector4 ) {
  27376. data.uniforms[ name ] = {
  27377. type: 'v4',
  27378. value: value.toArray()
  27379. };
  27380. } else if ( value && value.isMatrix3 ) {
  27381. data.uniforms[ name ] = {
  27382. type: 'm3',
  27383. value: value.toArray()
  27384. };
  27385. } else if ( value && value.isMatrix4 ) {
  27386. data.uniforms[ name ] = {
  27387. type: 'm4',
  27388. value: value.toArray()
  27389. };
  27390. } else {
  27391. data.uniforms[ name ] = {
  27392. value: value
  27393. };
  27394. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  27395. }
  27396. }
  27397. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  27398. data.vertexShader = this.vertexShader;
  27399. data.fragmentShader = this.fragmentShader;
  27400. data.lights = this.lights;
  27401. data.clipping = this.clipping;
  27402. const extensions = {};
  27403. for ( const key in this.extensions ) {
  27404. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  27405. }
  27406. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  27407. return data;
  27408. }
  27409. }
  27410. /**
  27411. * This class works just like {@link ShaderMaterial}, except that definitions
  27412. * of built-in uniforms and attributes are not automatically prepended to the
  27413. * GLSL shader code.
  27414. *
  27415. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27416. *
  27417. * @augments ShaderMaterial
  27418. */
  27419. class RawShaderMaterial extends ShaderMaterial {
  27420. /**
  27421. * Constructs a new raw shader material.
  27422. *
  27423. * @param {Object} [parameters] - An object with one or more properties
  27424. * defining the material's appearance. Any property of the material
  27425. * (including any property from inherited materials) can be passed
  27426. * in here. Color values can be passed any type of value accepted
  27427. * by {@link Color#set}.
  27428. */
  27429. constructor( parameters ) {
  27430. super( parameters );
  27431. /**
  27432. * This flag can be used for type testing.
  27433. *
  27434. * @type {boolean}
  27435. * @readonly
  27436. * @default true
  27437. */
  27438. this.isRawShaderMaterial = true;
  27439. this.type = 'RawShaderMaterial';
  27440. }
  27441. }
  27442. /**
  27443. * A standard physically based material, using Metallic-Roughness workflow.
  27444. *
  27445. * Physically based rendering (PBR) has recently become the standard in many
  27446. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  27447. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  27448. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  27449. *
  27450. * This approach differs from older approaches in that instead of using
  27451. * approximations for the way in which light interacts with a surface, a
  27452. * physically correct model is used. The idea is that, instead of tweaking
  27453. * materials to look good under specific lighting, a material can be created
  27454. * that will react 'correctly' under all lighting scenarios.
  27455. *
  27456. * In practice this gives a more accurate and realistic looking result than
  27457. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27458. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27459. * shading.
  27460. *
  27461. * Note that for best results you should always specify an environment map when using this material.
  27462. *
  27463. * For a non-technical introduction to the concept of PBR and how to set up a
  27464. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  27465. *
  27466. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  27467. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  27468. *
  27469. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27470. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  27471. * (pdf), by Brent Burley.
  27472. *
  27473. * @augments Material
  27474. * @demo scenes/material-browser.html#MeshStandardMaterial
  27475. */
  27476. class MeshStandardMaterial extends Material {
  27477. /**
  27478. * Constructs a new mesh standard material.
  27479. *
  27480. * @param {Object} [parameters] - An object with one or more properties
  27481. * defining the material's appearance. Any property of the material
  27482. * (including any property from inherited materials) can be passed
  27483. * in here. Color values can be passed any type of value accepted
  27484. * by {@link Color#set}.
  27485. */
  27486. constructor( parameters ) {
  27487. super();
  27488. /**
  27489. * This flag can be used for type testing.
  27490. *
  27491. * @type {boolean}
  27492. * @readonly
  27493. * @default true
  27494. */
  27495. this.isMeshStandardMaterial = true;
  27496. this.type = 'MeshStandardMaterial';
  27497. this.defines = { 'STANDARD': '' };
  27498. /**
  27499. * Color of the material.
  27500. *
  27501. * @type {Color}
  27502. * @default (1,1,1)
  27503. */
  27504. this.color = new Color( 0xffffff ); // diffuse
  27505. /**
  27506. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27507. * means fully diffuse. If `roughnessMap` is also provided,
  27508. * both values are multiplied.
  27509. *
  27510. * @type {number}
  27511. * @default 1
  27512. */
  27513. this.roughness = 1.0;
  27514. /**
  27515. * How much the material is like a metal. Non-metallic materials such as wood
  27516. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27517. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27518. * If `metalnessMap` is also provided, both values are multiplied.
  27519. *
  27520. * @type {number}
  27521. * @default 0
  27522. */
  27523. this.metalness = 0.0;
  27524. /**
  27525. * The color map. May optionally include an alpha channel, typically combined
  27526. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27527. * color is modulated by the diffuse `color`.
  27528. *
  27529. * @type {?Texture}
  27530. * @default null
  27531. */
  27532. this.map = null;
  27533. /**
  27534. * The light map. Requires a second set of UVs.
  27535. *
  27536. * @type {?Texture}
  27537. * @default null
  27538. */
  27539. this.lightMap = null;
  27540. /**
  27541. * Intensity of the baked light.
  27542. *
  27543. * @type {number}
  27544. * @default 1
  27545. */
  27546. this.lightMapIntensity = 1.0;
  27547. /**
  27548. * The red channel of this texture is used as the ambient occlusion map.
  27549. * Requires a second set of UVs.
  27550. *
  27551. * @type {?Texture}
  27552. * @default null
  27553. */
  27554. this.aoMap = null;
  27555. /**
  27556. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27557. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27558. * red channel is also `1`, ambient light is fully occluded on a surface.
  27559. *
  27560. * @type {number}
  27561. * @default 1
  27562. */
  27563. this.aoMapIntensity = 1.0;
  27564. /**
  27565. * Emissive (light) color of the material, essentially a solid color
  27566. * unaffected by other lighting.
  27567. *
  27568. * @type {Color}
  27569. * @default (0,0,0)
  27570. */
  27571. this.emissive = new Color( 0x000000 );
  27572. /**
  27573. * Intensity of the emissive light. Modulates the emissive color.
  27574. *
  27575. * @type {number}
  27576. * @default 1
  27577. */
  27578. this.emissiveIntensity = 1.0;
  27579. /**
  27580. * Set emissive (glow) map. The emissive map color is modulated by the
  27581. * emissive color and the emissive intensity. If you have an emissive map,
  27582. * be sure to set the emissive color to something other than black.
  27583. *
  27584. * @type {?Texture}
  27585. * @default null
  27586. */
  27587. this.emissiveMap = null;
  27588. /**
  27589. * The texture to create a bump map. The black and white values map to the
  27590. * perceived depth in relation to the lights. Bump doesn't actually affect
  27591. * the geometry of the object, only the lighting. If a normal map is defined
  27592. * this will be ignored.
  27593. *
  27594. * @type {?Texture}
  27595. * @default null
  27596. */
  27597. this.bumpMap = null;
  27598. /**
  27599. * How much the bump map affects the material. Typical range is `[0,1]`.
  27600. *
  27601. * @type {number}
  27602. * @default 1
  27603. */
  27604. this.bumpScale = 1;
  27605. /**
  27606. * The texture to create a normal map. The RGB values affect the surface
  27607. * normal for each pixel fragment and change the way the color is lit. Normal
  27608. * maps do not change the actual shape of the surface, only the lighting. In
  27609. * case the material has a normal map authored using the left handed
  27610. * convention, the `y` component of `normalScale` should be negated to compensate
  27611. * for the different handedness.
  27612. *
  27613. * @type {?Texture}
  27614. * @default null
  27615. */
  27616. this.normalMap = null;
  27617. /**
  27618. * The type of normal map.
  27619. *
  27620. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27621. * @default TangentSpaceNormalMap
  27622. */
  27623. this.normalMapType = TangentSpaceNormalMap;
  27624. /**
  27625. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27626. *
  27627. * @type {Vector2}
  27628. * @default (1,1)
  27629. */
  27630. this.normalScale = new Vector2( 1, 1 );
  27631. /**
  27632. * The displacement map affects the position of the mesh's vertices. Unlike
  27633. * other maps which only affect the light and shade of the material the
  27634. * displaced vertices can cast shadows, block other objects, and otherwise
  27635. * act as real geometry. The displacement texture is an image where the value
  27636. * of each pixel (white being the highest) is mapped against, and
  27637. * repositions, the vertices of the mesh.
  27638. *
  27639. * @type {?Texture}
  27640. * @default null
  27641. */
  27642. this.displacementMap = null;
  27643. /**
  27644. * How much the displacement map affects the mesh (where black is no
  27645. * displacement, and white is maximum displacement). Without a displacement
  27646. * map set, this value is not applied.
  27647. *
  27648. * @type {number}
  27649. * @default 0
  27650. */
  27651. this.displacementScale = 1;
  27652. /**
  27653. * The offset of the displacement map's values on the mesh's vertices.
  27654. * The bias is added to the scaled sample of the displacement map.
  27655. * Without a displacement map set, this value is not applied.
  27656. *
  27657. * @type {number}
  27658. * @default 0
  27659. */
  27660. this.displacementBias = 0;
  27661. /**
  27662. * The green channel of this texture is used to alter the roughness of the
  27663. * material.
  27664. *
  27665. * @type {?Texture}
  27666. * @default null
  27667. */
  27668. this.roughnessMap = null;
  27669. /**
  27670. * The blue channel of this texture is used to alter the metalness of the
  27671. * material.
  27672. *
  27673. * @type {?Texture}
  27674. * @default null
  27675. */
  27676. this.metalnessMap = null;
  27677. /**
  27678. * The alpha map is a grayscale texture that controls the opacity across the
  27679. * surface (black: fully transparent; white: fully opaque).
  27680. *
  27681. * Only the color of the texture is used, ignoring the alpha channel if one
  27682. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27683. * when sampling this texture due to the extra bit of precision provided for
  27684. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27685. * luminance/alpha textures will also still work as expected.
  27686. *
  27687. * @type {?Texture}
  27688. * @default null
  27689. */
  27690. this.alphaMap = null;
  27691. /**
  27692. * The environment map. To ensure a physically correct rendering, environment maps
  27693. * are internally pre-processed with {@link PMREMGenerator}.
  27694. *
  27695. * @type {?Texture}
  27696. * @default null
  27697. */
  27698. this.envMap = null;
  27699. /**
  27700. * The rotation of the environment map in radians.
  27701. *
  27702. * @type {Euler}
  27703. * @default (0,0,0)
  27704. */
  27705. this.envMapRotation = new Euler();
  27706. /**
  27707. * Scales the effect of the environment map by multiplying its color.
  27708. *
  27709. * @type {number}
  27710. * @default 1
  27711. */
  27712. this.envMapIntensity = 1.0;
  27713. /**
  27714. * Renders the geometry as a wireframe.
  27715. *
  27716. * @type {boolean}
  27717. * @default false
  27718. */
  27719. this.wireframe = false;
  27720. /**
  27721. * Controls the thickness of the wireframe.
  27722. *
  27723. * Can only be used with {@link SVGRenderer}.
  27724. *
  27725. * @type {number}
  27726. * @default 1
  27727. */
  27728. this.wireframeLinewidth = 1;
  27729. /**
  27730. * Defines appearance of wireframe ends.
  27731. *
  27732. * Can only be used with {@link SVGRenderer}.
  27733. *
  27734. * @type {('round'|'bevel'|'miter')}
  27735. * @default 'round'
  27736. */
  27737. this.wireframeLinecap = 'round';
  27738. /**
  27739. * Defines appearance of wireframe joints.
  27740. *
  27741. * Can only be used with {@link SVGRenderer}.
  27742. *
  27743. * @type {('round'|'bevel'|'miter')}
  27744. * @default 'round'
  27745. */
  27746. this.wireframeLinejoin = 'round';
  27747. /**
  27748. * Whether the material is rendered with flat shading or not.
  27749. *
  27750. * @type {boolean}
  27751. * @default false
  27752. */
  27753. this.flatShading = false;
  27754. /**
  27755. * Whether the material is affected by fog or not.
  27756. *
  27757. * @type {boolean}
  27758. * @default true
  27759. */
  27760. this.fog = true;
  27761. this.setValues( parameters );
  27762. }
  27763. copy( source ) {
  27764. super.copy( source );
  27765. this.defines = { 'STANDARD': '' };
  27766. this.color.copy( source.color );
  27767. this.roughness = source.roughness;
  27768. this.metalness = source.metalness;
  27769. this.map = source.map;
  27770. this.lightMap = source.lightMap;
  27771. this.lightMapIntensity = source.lightMapIntensity;
  27772. this.aoMap = source.aoMap;
  27773. this.aoMapIntensity = source.aoMapIntensity;
  27774. this.emissive.copy( source.emissive );
  27775. this.emissiveMap = source.emissiveMap;
  27776. this.emissiveIntensity = source.emissiveIntensity;
  27777. this.bumpMap = source.bumpMap;
  27778. this.bumpScale = source.bumpScale;
  27779. this.normalMap = source.normalMap;
  27780. this.normalMapType = source.normalMapType;
  27781. this.normalScale.copy( source.normalScale );
  27782. this.displacementMap = source.displacementMap;
  27783. this.displacementScale = source.displacementScale;
  27784. this.displacementBias = source.displacementBias;
  27785. this.roughnessMap = source.roughnessMap;
  27786. this.metalnessMap = source.metalnessMap;
  27787. this.alphaMap = source.alphaMap;
  27788. this.envMap = source.envMap;
  27789. this.envMapRotation.copy( source.envMapRotation );
  27790. this.envMapIntensity = source.envMapIntensity;
  27791. this.wireframe = source.wireframe;
  27792. this.wireframeLinewidth = source.wireframeLinewidth;
  27793. this.wireframeLinecap = source.wireframeLinecap;
  27794. this.wireframeLinejoin = source.wireframeLinejoin;
  27795. this.flatShading = source.flatShading;
  27796. this.fog = source.fog;
  27797. return this;
  27798. }
  27799. }
  27800. /**
  27801. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27802. * physically-based rendering properties:
  27803. *
  27804. * - Anisotropy: Ability to represent the anisotropic property of materials
  27805. * as observable with brushed metals.
  27806. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27807. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27808. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27809. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27810. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27811. * wings of many insects.
  27812. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27813. * transparent materials are less reflective. Physically-based transmission provides a more
  27814. * realistic option for thin, transparent surfaces like glass.
  27815. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27816. * - Sheen: Can be used for representing cloth and fabric materials.
  27817. *
  27818. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27819. * higher performance cost, per pixel, than other three.js materials. Most
  27820. * effects are disabled by default, and add cost as they are enabled. For
  27821. * best results, always specify an environment map when using this material.
  27822. *
  27823. * @augments MeshStandardMaterial
  27824. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  27825. */
  27826. class MeshPhysicalMaterial extends MeshStandardMaterial {
  27827. /**
  27828. * Constructs a new mesh physical material.
  27829. *
  27830. * @param {Object} [parameters] - An object with one or more properties
  27831. * defining the material's appearance. Any property of the material
  27832. * (including any property from inherited materials) can be passed
  27833. * in here. Color values can be passed any type of value accepted
  27834. * by {@link Color#set}.
  27835. */
  27836. constructor( parameters ) {
  27837. super();
  27838. /**
  27839. * This flag can be used for type testing.
  27840. *
  27841. * @type {boolean}
  27842. * @readonly
  27843. * @default true
  27844. */
  27845. this.isMeshPhysicalMaterial = true;
  27846. this.defines = {
  27847. 'STANDARD': '',
  27848. 'PHYSICAL': ''
  27849. };
  27850. this.type = 'MeshPhysicalMaterial';
  27851. /**
  27852. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  27853. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  27854. * property provides additional rotation to the vectors in the texture.
  27855. *
  27856. * @type {number}
  27857. * @default 1
  27858. */
  27859. this.anisotropyRotation = 0;
  27860. /**
  27861. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  27862. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  27863. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  27864. *
  27865. * @type {?Texture}
  27866. * @default null
  27867. */
  27868. this.anisotropyMap = null;
  27869. /**
  27870. * The red channel of this texture is multiplied against `clearcoat`,
  27871. * for per-pixel control over a coating's intensity.
  27872. *
  27873. * @type {?Texture}
  27874. * @default null
  27875. */
  27876. this.clearcoatMap = null;
  27877. /**
  27878. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  27879. *
  27880. * @type {number}
  27881. * @default 0
  27882. */
  27883. this.clearcoatRoughness = 0.0;
  27884. /**
  27885. * The green channel of this texture is multiplied against
  27886. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  27887. *
  27888. * @type {?Texture}
  27889. * @default null
  27890. */
  27891. this.clearcoatRoughnessMap = null;
  27892. /**
  27893. * How much `clearcoatNormalMap` affects the clear coat layer, from
  27894. * `(0,0)` to `(1,1)`.
  27895. *
  27896. * @type {Vector2}
  27897. * @default (1,1)
  27898. */
  27899. this.clearcoatNormalScale = new Vector2( 1, 1 );
  27900. /**
  27901. * Can be used to enable independent normals for the clear coat layer.
  27902. *
  27903. * @type {?Texture}
  27904. * @default null
  27905. */
  27906. this.clearcoatNormalMap = null;
  27907. /**
  27908. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  27909. *
  27910. * @type {number}
  27911. * @default 1.5
  27912. */
  27913. this.ior = 1.5;
  27914. /**
  27915. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  27916. * corresponds to an index-of-refraction of `1.5`.
  27917. *
  27918. * This models the reflectivity of non-metallic materials. It has no effect
  27919. * when `metalness` is `1.0`
  27920. *
  27921. * @name MeshPhysicalMaterial#reflectivity
  27922. * @type {number}
  27923. * @default 0.5
  27924. */
  27925. Object.defineProperty( this, 'reflectivity', {
  27926. get: function () {
  27927. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  27928. },
  27929. set: function ( reflectivity ) {
  27930. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  27931. }
  27932. } );
  27933. /**
  27934. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  27935. * control over iridescence.
  27936. *
  27937. * @type {?Texture}
  27938. * @default null
  27939. */
  27940. this.iridescenceMap = null;
  27941. /**
  27942. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  27943. * Between `1.0` to `2.333`.
  27944. *
  27945. * @type {number}
  27946. * @default 1.3
  27947. */
  27948. this.iridescenceIOR = 1.3;
  27949. /**
  27950. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  27951. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  27952. *
  27953. * @type {Array<number,number>}
  27954. * @default [100,400]
  27955. */
  27956. this.iridescenceThicknessRange = [ 100, 400 ];
  27957. /**
  27958. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  27959. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  27960. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  27961. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  27962. * - Values in-between will linearly interpolate between the elements of the array.
  27963. *
  27964. * @type {?Texture}
  27965. * @default null
  27966. */
  27967. this.iridescenceThicknessMap = null;
  27968. /**
  27969. * The sheen tint.
  27970. *
  27971. * @type {Color}
  27972. * @default (0,0,0)
  27973. */
  27974. this.sheenColor = new Color( 0x000000 );
  27975. /**
  27976. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  27977. * over sheen tint.
  27978. *
  27979. * @type {?Texture}
  27980. * @default null
  27981. */
  27982. this.sheenColorMap = null;
  27983. /**
  27984. * Roughness of the sheen layer, from `0.0` to `1.0`.
  27985. *
  27986. * @type {number}
  27987. * @default 1
  27988. */
  27989. this.sheenRoughness = 1.0;
  27990. /**
  27991. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  27992. * over sheen roughness.
  27993. *
  27994. * @type {?Texture}
  27995. * @default null
  27996. */
  27997. this.sheenRoughnessMap = null;
  27998. /**
  27999. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28000. * optical transparency.
  28001. *
  28002. * @type {?Texture}
  28003. * @default null
  28004. */
  28005. this.transmissionMap = null;
  28006. /**
  28007. * The thickness of the volume beneath the surface. The value is given in the
  28008. * coordinate space of the mesh. If the value is `0` the material is
  28009. * thin-walled. Otherwise the material is a volume boundary.
  28010. *
  28011. * @type {number}
  28012. * @default 0
  28013. */
  28014. this.thickness = 0;
  28015. /**
  28016. * A texture that defines the thickness, stored in the green channel. This will
  28017. * be multiplied by `thickness`.
  28018. *
  28019. * @type {?Texture}
  28020. * @default null
  28021. */
  28022. this.thicknessMap = null;
  28023. /**
  28024. * Density of the medium given as the average distance that light travels in
  28025. * the medium before interacting with a particle. The value is given in world
  28026. * space units, and must be greater than zero.
  28027. *
  28028. * @type {number}
  28029. * @default Infinity
  28030. */
  28031. this.attenuationDistance = Infinity;
  28032. /**
  28033. * The color that white light turns into due to absorption when reaching the
  28034. * attenuation distance.
  28035. *
  28036. * @type {Color}
  28037. * @default (1,1,1)
  28038. */
  28039. this.attenuationColor = new Color( 1, 1, 1 );
  28040. /**
  28041. * A float that scales the amount of specular reflection for non-metals only.
  28042. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28043. *
  28044. * @type {number}
  28045. * @default 1
  28046. */
  28047. this.specularIntensity = 1.0;
  28048. /**
  28049. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28050. * for per-pixel control over specular intensity.
  28051. *
  28052. * @type {?Texture}
  28053. * @default null
  28054. */
  28055. this.specularIntensityMap = null;
  28056. /**
  28057. * Tints the specular reflection at normal incidence for non-metals only.
  28058. *
  28059. * @type {Color}
  28060. * @default (1,1,1)
  28061. */
  28062. this.specularColor = new Color( 1, 1, 1 );
  28063. /**
  28064. * The RGB channels of this texture are multiplied against `specularColor`,
  28065. * for per-pixel control over specular color.
  28066. *
  28067. * @type {?Texture}
  28068. * @default null
  28069. */
  28070. this.specularColorMap = null;
  28071. this._anisotropy = 0;
  28072. this._clearcoat = 0;
  28073. this._dispersion = 0;
  28074. this._iridescence = 0;
  28075. this._sheen = 0.0;
  28076. this._transmission = 0;
  28077. this.setValues( parameters );
  28078. }
  28079. /**
  28080. * The anisotropy strength, from `0.0` to `1.0`.
  28081. *
  28082. * @type {number}
  28083. * @default 0
  28084. */
  28085. get anisotropy() {
  28086. return this._anisotropy;
  28087. }
  28088. set anisotropy( value ) {
  28089. if ( this._anisotropy > 0 !== value > 0 ) {
  28090. this.version ++;
  28091. }
  28092. this._anisotropy = value;
  28093. }
  28094. /**
  28095. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28096. * clear coat related properties to enable multilayer materials that have a
  28097. * thin translucent layer over the base layer.
  28098. *
  28099. * @type {number}
  28100. * @default 0
  28101. */
  28102. get clearcoat() {
  28103. return this._clearcoat;
  28104. }
  28105. set clearcoat( value ) {
  28106. if ( this._clearcoat > 0 !== value > 0 ) {
  28107. this.version ++;
  28108. }
  28109. this._clearcoat = value;
  28110. }
  28111. /**
  28112. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28113. * the surface and the viewer, from `0.0` to `1.0`.
  28114. *
  28115. * @type {number}
  28116. * @default 0
  28117. */
  28118. get iridescence() {
  28119. return this._iridescence;
  28120. }
  28121. set iridescence( value ) {
  28122. if ( this._iridescence > 0 !== value > 0 ) {
  28123. this.version ++;
  28124. }
  28125. this._iridescence = value;
  28126. }
  28127. /**
  28128. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28129. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28130. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28131. *
  28132. * @type {number}
  28133. * @default 0
  28134. */
  28135. get dispersion() {
  28136. return this._dispersion;
  28137. }
  28138. set dispersion( value ) {
  28139. if ( this._dispersion > 0 !== value > 0 ) {
  28140. this.version ++;
  28141. }
  28142. this._dispersion = value;
  28143. }
  28144. /**
  28145. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28146. *
  28147. * @type {number}
  28148. * @default 0
  28149. */
  28150. get sheen() {
  28151. return this._sheen;
  28152. }
  28153. set sheen( value ) {
  28154. if ( this._sheen > 0 !== value > 0 ) {
  28155. this.version ++;
  28156. }
  28157. this._sheen = value;
  28158. }
  28159. /**
  28160. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28161. *
  28162. * Thin, transparent or semitransparent, plastic or glass materials remain
  28163. * largely reflective even if they are fully transmissive. The transmission
  28164. * property can be used to model these materials.
  28165. *
  28166. * When transmission is non-zero, `opacity` should be set to `1`.
  28167. *
  28168. * @type {number}
  28169. * @default 0
  28170. */
  28171. get transmission() {
  28172. return this._transmission;
  28173. }
  28174. set transmission( value ) {
  28175. if ( this._transmission > 0 !== value > 0 ) {
  28176. this.version ++;
  28177. }
  28178. this._transmission = value;
  28179. }
  28180. copy( source ) {
  28181. super.copy( source );
  28182. this.defines = {
  28183. 'STANDARD': '',
  28184. 'PHYSICAL': ''
  28185. };
  28186. this.anisotropy = source.anisotropy;
  28187. this.anisotropyRotation = source.anisotropyRotation;
  28188. this.anisotropyMap = source.anisotropyMap;
  28189. this.clearcoat = source.clearcoat;
  28190. this.clearcoatMap = source.clearcoatMap;
  28191. this.clearcoatRoughness = source.clearcoatRoughness;
  28192. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28193. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28194. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28195. this.dispersion = source.dispersion;
  28196. this.ior = source.ior;
  28197. this.iridescence = source.iridescence;
  28198. this.iridescenceMap = source.iridescenceMap;
  28199. this.iridescenceIOR = source.iridescenceIOR;
  28200. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28201. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28202. this.sheen = source.sheen;
  28203. this.sheenColor.copy( source.sheenColor );
  28204. this.sheenColorMap = source.sheenColorMap;
  28205. this.sheenRoughness = source.sheenRoughness;
  28206. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28207. this.transmission = source.transmission;
  28208. this.transmissionMap = source.transmissionMap;
  28209. this.thickness = source.thickness;
  28210. this.thicknessMap = source.thicknessMap;
  28211. this.attenuationDistance = source.attenuationDistance;
  28212. this.attenuationColor.copy( source.attenuationColor );
  28213. this.specularIntensity = source.specularIntensity;
  28214. this.specularIntensityMap = source.specularIntensityMap;
  28215. this.specularColor.copy( source.specularColor );
  28216. this.specularColorMap = source.specularColorMap;
  28217. return this;
  28218. }
  28219. }
  28220. /**
  28221. * A material for shiny surfaces with specular highlights.
  28222. *
  28223. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28224. * model for calculating reflectance. Unlike the Lambertian model used in the
  28225. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28226. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28227. *
  28228. * Performance will generally be greater when using this material over the
  28229. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28230. * some graphical accuracy.
  28231. *
  28232. * @augments Material
  28233. * @demo scenes/material-browser.html#MeshPhongMaterial
  28234. */
  28235. class MeshPhongMaterial extends Material {
  28236. /**
  28237. * Constructs a new mesh phong material.
  28238. *
  28239. * @param {Object} [parameters] - An object with one or more properties
  28240. * defining the material's appearance. Any property of the material
  28241. * (including any property from inherited materials) can be passed
  28242. * in here. Color values can be passed any type of value accepted
  28243. * by {@link Color#set}.
  28244. */
  28245. constructor( parameters ) {
  28246. super();
  28247. /**
  28248. * This flag can be used for type testing.
  28249. *
  28250. * @type {boolean}
  28251. * @readonly
  28252. * @default true
  28253. */
  28254. this.isMeshPhongMaterial = true;
  28255. this.type = 'MeshPhongMaterial';
  28256. /**
  28257. * Color of the material.
  28258. *
  28259. * @type {Color}
  28260. * @default (1,1,1)
  28261. */
  28262. this.color = new Color( 0xffffff ); // diffuse
  28263. /**
  28264. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28265. *
  28266. * This defines how shiny the material is and the color of its shine.
  28267. *
  28268. * @type {Color}
  28269. */
  28270. this.specular = new Color( 0x111111 );
  28271. /**
  28272. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28273. *
  28274. * @type {number}
  28275. * @default 30
  28276. */
  28277. this.shininess = 30;
  28278. /**
  28279. * The color map. May optionally include an alpha channel, typically combined
  28280. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28281. * color is modulated by the diffuse `color`.
  28282. *
  28283. * @type {?Texture}
  28284. * @default null
  28285. */
  28286. this.map = null;
  28287. /**
  28288. * The light map. Requires a second set of UVs.
  28289. *
  28290. * @type {?Texture}
  28291. * @default null
  28292. */
  28293. this.lightMap = null;
  28294. /**
  28295. * Intensity of the baked light.
  28296. *
  28297. * @type {number}
  28298. * @default 1
  28299. */
  28300. this.lightMapIntensity = 1.0;
  28301. /**
  28302. * The red channel of this texture is used as the ambient occlusion map.
  28303. * Requires a second set of UVs.
  28304. *
  28305. * @type {?Texture}
  28306. * @default null
  28307. */
  28308. this.aoMap = null;
  28309. /**
  28310. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28311. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28312. * red channel is also `1`, ambient light is fully occluded on a surface.
  28313. *
  28314. * @type {number}
  28315. * @default 1
  28316. */
  28317. this.aoMapIntensity = 1.0;
  28318. /**
  28319. * Emissive (light) color of the material, essentially a solid color
  28320. * unaffected by other lighting.
  28321. *
  28322. * @type {Color}
  28323. * @default (0,0,0)
  28324. */
  28325. this.emissive = new Color( 0x000000 );
  28326. /**
  28327. * Intensity of the emissive light. Modulates the emissive color.
  28328. *
  28329. * @type {number}
  28330. * @default 1
  28331. */
  28332. this.emissiveIntensity = 1.0;
  28333. /**
  28334. * Set emissive (glow) map. The emissive map color is modulated by the
  28335. * emissive color and the emissive intensity. If you have an emissive map,
  28336. * be sure to set the emissive color to something other than black.
  28337. *
  28338. * @type {?Texture}
  28339. * @default null
  28340. */
  28341. this.emissiveMap = null;
  28342. /**
  28343. * The texture to create a bump map. The black and white values map to the
  28344. * perceived depth in relation to the lights. Bump doesn't actually affect
  28345. * the geometry of the object, only the lighting. If a normal map is defined
  28346. * this will be ignored.
  28347. *
  28348. * @type {?Texture}
  28349. * @default null
  28350. */
  28351. this.bumpMap = null;
  28352. /**
  28353. * How much the bump map affects the material. Typical range is `[0,1]`.
  28354. *
  28355. * @type {number}
  28356. * @default 1
  28357. */
  28358. this.bumpScale = 1;
  28359. /**
  28360. * The texture to create a normal map. The RGB values affect the surface
  28361. * normal for each pixel fragment and change the way the color is lit. Normal
  28362. * maps do not change the actual shape of the surface, only the lighting. In
  28363. * case the material has a normal map authored using the left handed
  28364. * convention, the `y` component of `normalScale` should be negated to compensate
  28365. * for the different handedness.
  28366. *
  28367. * @type {?Texture}
  28368. * @default null
  28369. */
  28370. this.normalMap = null;
  28371. /**
  28372. * The type of normal map.
  28373. *
  28374. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28375. * @default TangentSpaceNormalMap
  28376. */
  28377. this.normalMapType = TangentSpaceNormalMap;
  28378. /**
  28379. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28380. *
  28381. * @type {Vector2}
  28382. * @default (1,1)
  28383. */
  28384. this.normalScale = new Vector2( 1, 1 );
  28385. /**
  28386. * The displacement map affects the position of the mesh's vertices. Unlike
  28387. * other maps which only affect the light and shade of the material the
  28388. * displaced vertices can cast shadows, block other objects, and otherwise
  28389. * act as real geometry. The displacement texture is an image where the value
  28390. * of each pixel (white being the highest) is mapped against, and
  28391. * repositions, the vertices of the mesh.
  28392. *
  28393. * @type {?Texture}
  28394. * @default null
  28395. */
  28396. this.displacementMap = null;
  28397. /**
  28398. * How much the displacement map affects the mesh (where black is no
  28399. * displacement, and white is maximum displacement). Without a displacement
  28400. * map set, this value is not applied.
  28401. *
  28402. * @type {number}
  28403. * @default 0
  28404. */
  28405. this.displacementScale = 1;
  28406. /**
  28407. * The offset of the displacement map's values on the mesh's vertices.
  28408. * The bias is added to the scaled sample of the displacement map.
  28409. * Without a displacement map set, this value is not applied.
  28410. *
  28411. * @type {number}
  28412. * @default 0
  28413. */
  28414. this.displacementBias = 0;
  28415. /**
  28416. * The specular map value affects both how much the specular surface
  28417. * highlight contributes and how much of the environment map affects the
  28418. * surface.
  28419. *
  28420. * @type {?Texture}
  28421. * @default null
  28422. */
  28423. this.specularMap = null;
  28424. /**
  28425. * The alpha map is a grayscale texture that controls the opacity across the
  28426. * surface (black: fully transparent; white: fully opaque).
  28427. *
  28428. * Only the color of the texture is used, ignoring the alpha channel if one
  28429. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28430. * when sampling this texture due to the extra bit of precision provided for
  28431. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28432. * luminance/alpha textures will also still work as expected.
  28433. *
  28434. * @type {?Texture}
  28435. * @default null
  28436. */
  28437. this.alphaMap = null;
  28438. /**
  28439. * The environment map.
  28440. *
  28441. * @type {?Texture}
  28442. * @default null
  28443. */
  28444. this.envMap = null;
  28445. /**
  28446. * The rotation of the environment map in radians.
  28447. *
  28448. * @type {Euler}
  28449. * @default (0,0,0)
  28450. */
  28451. this.envMapRotation = new Euler();
  28452. /**
  28453. * How to combine the result of the surface's color with the environment map, if any.
  28454. *
  28455. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28456. * blend between the two colors.
  28457. *
  28458. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28459. * @default MultiplyOperation
  28460. */
  28461. this.combine = MultiplyOperation;
  28462. /**
  28463. * How much the environment map affects the surface.
  28464. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28465. *
  28466. * @type {number}
  28467. * @default 1
  28468. */
  28469. this.reflectivity = 1;
  28470. /**
  28471. * Scales the effect of the environment map by multiplying its color.
  28472. *
  28473. * @type {number}
  28474. * @default 1
  28475. */
  28476. this.envMapIntensity = 1.0;
  28477. /**
  28478. * The index of refraction (IOR) of air (approximately 1) divided by the
  28479. * index of refraction of the material. It is used with environment mapping
  28480. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28481. * The refraction ratio should not exceed `1`.
  28482. *
  28483. * @type {number}
  28484. * @default 0.98
  28485. */
  28486. this.refractionRatio = 0.98;
  28487. /**
  28488. * Renders the geometry as a wireframe.
  28489. *
  28490. * @type {boolean}
  28491. * @default false
  28492. */
  28493. this.wireframe = false;
  28494. /**
  28495. * Controls the thickness of the wireframe.
  28496. *
  28497. * Can only be used with {@link SVGRenderer}.
  28498. *
  28499. * @type {number}
  28500. * @default 1
  28501. */
  28502. this.wireframeLinewidth = 1;
  28503. /**
  28504. * Defines appearance of wireframe ends.
  28505. *
  28506. * Can only be used with {@link SVGRenderer}.
  28507. *
  28508. * @type {('round'|'bevel'|'miter')}
  28509. * @default 'round'
  28510. */
  28511. this.wireframeLinecap = 'round';
  28512. /**
  28513. * Defines appearance of wireframe joints.
  28514. *
  28515. * Can only be used with {@link SVGRenderer}.
  28516. *
  28517. * @type {('round'|'bevel'|'miter')}
  28518. * @default 'round'
  28519. */
  28520. this.wireframeLinejoin = 'round';
  28521. /**
  28522. * Whether the material is rendered with flat shading or not.
  28523. *
  28524. * @type {boolean}
  28525. * @default false
  28526. */
  28527. this.flatShading = false;
  28528. /**
  28529. * Whether the material is affected by fog or not.
  28530. *
  28531. * @type {boolean}
  28532. * @default true
  28533. */
  28534. this.fog = true;
  28535. this.setValues( parameters );
  28536. }
  28537. copy( source ) {
  28538. super.copy( source );
  28539. this.color.copy( source.color );
  28540. this.specular.copy( source.specular );
  28541. this.shininess = source.shininess;
  28542. this.map = source.map;
  28543. this.lightMap = source.lightMap;
  28544. this.lightMapIntensity = source.lightMapIntensity;
  28545. this.aoMap = source.aoMap;
  28546. this.aoMapIntensity = source.aoMapIntensity;
  28547. this.emissive.copy( source.emissive );
  28548. this.emissiveMap = source.emissiveMap;
  28549. this.emissiveIntensity = source.emissiveIntensity;
  28550. this.bumpMap = source.bumpMap;
  28551. this.bumpScale = source.bumpScale;
  28552. this.normalMap = source.normalMap;
  28553. this.normalMapType = source.normalMapType;
  28554. this.normalScale.copy( source.normalScale );
  28555. this.displacementMap = source.displacementMap;
  28556. this.displacementScale = source.displacementScale;
  28557. this.displacementBias = source.displacementBias;
  28558. this.specularMap = source.specularMap;
  28559. this.alphaMap = source.alphaMap;
  28560. this.envMap = source.envMap;
  28561. this.envMapRotation.copy( source.envMapRotation );
  28562. this.combine = source.combine;
  28563. this.reflectivity = source.reflectivity;
  28564. this.envMapIntensity = source.envMapIntensity;
  28565. this.refractionRatio = source.refractionRatio;
  28566. this.wireframe = source.wireframe;
  28567. this.wireframeLinewidth = source.wireframeLinewidth;
  28568. this.wireframeLinecap = source.wireframeLinecap;
  28569. this.wireframeLinejoin = source.wireframeLinejoin;
  28570. this.flatShading = source.flatShading;
  28571. this.fog = source.fog;
  28572. return this;
  28573. }
  28574. }
  28575. /**
  28576. * A material implementing toon shading.
  28577. *
  28578. * @augments Material
  28579. * @demo scenes/material-browser.html#MeshToonMaterial
  28580. */
  28581. class MeshToonMaterial extends Material {
  28582. /**
  28583. * Constructs a new mesh toon material.
  28584. *
  28585. * @param {Object} [parameters] - An object with one or more properties
  28586. * defining the material's appearance. Any property of the material
  28587. * (including any property from inherited materials) can be passed
  28588. * in here. Color values can be passed any type of value accepted
  28589. * by {@link Color#set}.
  28590. */
  28591. constructor( parameters ) {
  28592. super();
  28593. /**
  28594. * This flag can be used for type testing.
  28595. *
  28596. * @type {boolean}
  28597. * @readonly
  28598. * @default true
  28599. */
  28600. this.isMeshToonMaterial = true;
  28601. this.defines = { 'TOON': '' };
  28602. this.type = 'MeshToonMaterial';
  28603. /**
  28604. * Color of the material.
  28605. *
  28606. * @type {Color}
  28607. * @default (1,1,1)
  28608. */
  28609. this.color = new Color( 0xffffff );
  28610. /**
  28611. * The color map. May optionally include an alpha channel, typically combined
  28612. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28613. * color is modulated by the diffuse `color`.
  28614. *
  28615. * @type {?Texture}
  28616. * @default null
  28617. */
  28618. this.map = null;
  28619. /**
  28620. * Gradient map for toon shading. It's required to set
  28621. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28622. * when using this type of texture.
  28623. *
  28624. * @type {?Texture}
  28625. * @default null
  28626. */
  28627. this.gradientMap = null;
  28628. /**
  28629. * The light map. Requires a second set of UVs.
  28630. *
  28631. * @type {?Texture}
  28632. * @default null
  28633. */
  28634. this.lightMap = null;
  28635. /**
  28636. * Intensity of the baked light.
  28637. *
  28638. * @type {number}
  28639. * @default 1
  28640. */
  28641. this.lightMapIntensity = 1.0;
  28642. /**
  28643. * The red channel of this texture is used as the ambient occlusion map.
  28644. * Requires a second set of UVs.
  28645. *
  28646. * @type {?Texture}
  28647. * @default null
  28648. */
  28649. this.aoMap = null;
  28650. /**
  28651. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28652. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28653. * red channel is also `1`, ambient light is fully occluded on a surface.
  28654. *
  28655. * @type {number}
  28656. * @default 1
  28657. */
  28658. this.aoMapIntensity = 1.0;
  28659. /**
  28660. * Emissive (light) color of the material, essentially a solid color
  28661. * unaffected by other lighting.
  28662. *
  28663. * @type {Color}
  28664. * @default (0,0,0)
  28665. */
  28666. this.emissive = new Color( 0x000000 );
  28667. /**
  28668. * Intensity of the emissive light. Modulates the emissive color.
  28669. *
  28670. * @type {number}
  28671. * @default 1
  28672. */
  28673. this.emissiveIntensity = 1.0;
  28674. /**
  28675. * Set emissive (glow) map. The emissive map color is modulated by the
  28676. * emissive color and the emissive intensity. If you have an emissive map,
  28677. * be sure to set the emissive color to something other than black.
  28678. *
  28679. * @type {?Texture}
  28680. * @default null
  28681. */
  28682. this.emissiveMap = null;
  28683. /**
  28684. * The texture to create a bump map. The black and white values map to the
  28685. * perceived depth in relation to the lights. Bump doesn't actually affect
  28686. * the geometry of the object, only the lighting. If a normal map is defined
  28687. * this will be ignored.
  28688. *
  28689. * @type {?Texture}
  28690. * @default null
  28691. */
  28692. this.bumpMap = null;
  28693. /**
  28694. * How much the bump map affects the material. Typical range is `[0,1]`.
  28695. *
  28696. * @type {number}
  28697. * @default 1
  28698. */
  28699. this.bumpScale = 1;
  28700. /**
  28701. * The texture to create a normal map. The RGB values affect the surface
  28702. * normal for each pixel fragment and change the way the color is lit. Normal
  28703. * maps do not change the actual shape of the surface, only the lighting. In
  28704. * case the material has a normal map authored using the left handed
  28705. * convention, the `y` component of `normalScale` should be negated to compensate
  28706. * for the different handedness.
  28707. *
  28708. * @type {?Texture}
  28709. * @default null
  28710. */
  28711. this.normalMap = null;
  28712. /**
  28713. * The type of normal map.
  28714. *
  28715. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28716. * @default TangentSpaceNormalMap
  28717. */
  28718. this.normalMapType = TangentSpaceNormalMap;
  28719. /**
  28720. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28721. *
  28722. * @type {Vector2}
  28723. * @default (1,1)
  28724. */
  28725. this.normalScale = new Vector2( 1, 1 );
  28726. /**
  28727. * The displacement map affects the position of the mesh's vertices. Unlike
  28728. * other maps which only affect the light and shade of the material the
  28729. * displaced vertices can cast shadows, block other objects, and otherwise
  28730. * act as real geometry. The displacement texture is an image where the value
  28731. * of each pixel (white being the highest) is mapped against, and
  28732. * repositions, the vertices of the mesh.
  28733. *
  28734. * @type {?Texture}
  28735. * @default null
  28736. */
  28737. this.displacementMap = null;
  28738. /**
  28739. * How much the displacement map affects the mesh (where black is no
  28740. * displacement, and white is maximum displacement). Without a displacement
  28741. * map set, this value is not applied.
  28742. *
  28743. * @type {number}
  28744. * @default 0
  28745. */
  28746. this.displacementScale = 1;
  28747. /**
  28748. * The offset of the displacement map's values on the mesh's vertices.
  28749. * The bias is added to the scaled sample of the displacement map.
  28750. * Without a displacement map set, this value is not applied.
  28751. *
  28752. * @type {number}
  28753. * @default 0
  28754. */
  28755. this.displacementBias = 0;
  28756. /**
  28757. * The alpha map is a grayscale texture that controls the opacity across the
  28758. * surface (black: fully transparent; white: fully opaque).
  28759. *
  28760. * Only the color of the texture is used, ignoring the alpha channel if one
  28761. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28762. * when sampling this texture due to the extra bit of precision provided for
  28763. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28764. * luminance/alpha textures will also still work as expected.
  28765. *
  28766. * @type {?Texture}
  28767. * @default null
  28768. */
  28769. this.alphaMap = null;
  28770. /**
  28771. * Renders the geometry as a wireframe.
  28772. *
  28773. * @type {boolean}
  28774. * @default false
  28775. */
  28776. this.wireframe = false;
  28777. /**
  28778. * Controls the thickness of the wireframe.
  28779. *
  28780. * Can only be used with {@link SVGRenderer}.
  28781. *
  28782. * @type {number}
  28783. * @default 1
  28784. */
  28785. this.wireframeLinewidth = 1;
  28786. /**
  28787. * Defines appearance of wireframe ends.
  28788. *
  28789. * Can only be used with {@link SVGRenderer}.
  28790. *
  28791. * @type {('round'|'bevel'|'miter')}
  28792. * @default 'round'
  28793. */
  28794. this.wireframeLinecap = 'round';
  28795. /**
  28796. * Defines appearance of wireframe joints.
  28797. *
  28798. * Can only be used with {@link SVGRenderer}.
  28799. *
  28800. * @type {('round'|'bevel'|'miter')}
  28801. * @default 'round'
  28802. */
  28803. this.wireframeLinejoin = 'round';
  28804. /**
  28805. * Whether the material is affected by fog or not.
  28806. *
  28807. * @type {boolean}
  28808. * @default true
  28809. */
  28810. this.fog = true;
  28811. this.setValues( parameters );
  28812. }
  28813. copy( source ) {
  28814. super.copy( source );
  28815. this.color.copy( source.color );
  28816. this.map = source.map;
  28817. this.gradientMap = source.gradientMap;
  28818. this.lightMap = source.lightMap;
  28819. this.lightMapIntensity = source.lightMapIntensity;
  28820. this.aoMap = source.aoMap;
  28821. this.aoMapIntensity = source.aoMapIntensity;
  28822. this.emissive.copy( source.emissive );
  28823. this.emissiveMap = source.emissiveMap;
  28824. this.emissiveIntensity = source.emissiveIntensity;
  28825. this.bumpMap = source.bumpMap;
  28826. this.bumpScale = source.bumpScale;
  28827. this.normalMap = source.normalMap;
  28828. this.normalMapType = source.normalMapType;
  28829. this.normalScale.copy( source.normalScale );
  28830. this.displacementMap = source.displacementMap;
  28831. this.displacementScale = source.displacementScale;
  28832. this.displacementBias = source.displacementBias;
  28833. this.alphaMap = source.alphaMap;
  28834. this.wireframe = source.wireframe;
  28835. this.wireframeLinewidth = source.wireframeLinewidth;
  28836. this.wireframeLinecap = source.wireframeLinecap;
  28837. this.wireframeLinejoin = source.wireframeLinejoin;
  28838. this.fog = source.fog;
  28839. return this;
  28840. }
  28841. }
  28842. /**
  28843. * A material that maps the normal vectors to RGB colors.
  28844. *
  28845. * @augments Material
  28846. * @demo scenes/material-browser.html#MeshNormalMaterial
  28847. */
  28848. class MeshNormalMaterial extends Material {
  28849. /**
  28850. * Constructs a new mesh normal material.
  28851. *
  28852. * @param {Object} [parameters] - An object with one or more properties
  28853. * defining the material's appearance. Any property of the material
  28854. * (including any property from inherited materials) can be passed
  28855. * in here. Color values can be passed any type of value accepted
  28856. * by {@link Color#set}.
  28857. */
  28858. constructor( parameters ) {
  28859. super();
  28860. /**
  28861. * This flag can be used for type testing.
  28862. *
  28863. * @type {boolean}
  28864. * @readonly
  28865. * @default true
  28866. */
  28867. this.isMeshNormalMaterial = true;
  28868. this.type = 'MeshNormalMaterial';
  28869. /**
  28870. * The texture to create a bump map. The black and white values map to the
  28871. * perceived depth in relation to the lights. Bump doesn't actually affect
  28872. * the geometry of the object, only the lighting. If a normal map is defined
  28873. * this will be ignored.
  28874. *
  28875. * @type {?Texture}
  28876. * @default null
  28877. */
  28878. this.bumpMap = null;
  28879. /**
  28880. * How much the bump map affects the material. Typical range is `[0,1]`.
  28881. *
  28882. * @type {number}
  28883. * @default 1
  28884. */
  28885. this.bumpScale = 1;
  28886. /**
  28887. * The texture to create a normal map. The RGB values affect the surface
  28888. * normal for each pixel fragment and change the way the color is lit. Normal
  28889. * maps do not change the actual shape of the surface, only the lighting. In
  28890. * case the material has a normal map authored using the left handed
  28891. * convention, the `y` component of `normalScale` should be negated to compensate
  28892. * for the different handedness.
  28893. *
  28894. * @type {?Texture}
  28895. * @default null
  28896. */
  28897. this.normalMap = null;
  28898. /**
  28899. * The type of normal map.
  28900. *
  28901. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28902. * @default TangentSpaceNormalMap
  28903. */
  28904. this.normalMapType = TangentSpaceNormalMap;
  28905. /**
  28906. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28907. *
  28908. * @type {Vector2}
  28909. * @default (1,1)
  28910. */
  28911. this.normalScale = new Vector2( 1, 1 );
  28912. /**
  28913. * The displacement map affects the position of the mesh's vertices. Unlike
  28914. * other maps which only affect the light and shade of the material the
  28915. * displaced vertices can cast shadows, block other objects, and otherwise
  28916. * act as real geometry. The displacement texture is an image where the value
  28917. * of each pixel (white being the highest) is mapped against, and
  28918. * repositions, the vertices of the mesh.
  28919. *
  28920. * @type {?Texture}
  28921. * @default null
  28922. */
  28923. this.displacementMap = null;
  28924. /**
  28925. * How much the displacement map affects the mesh (where black is no
  28926. * displacement, and white is maximum displacement). Without a displacement
  28927. * map set, this value is not applied.
  28928. *
  28929. * @type {number}
  28930. * @default 0
  28931. */
  28932. this.displacementScale = 1;
  28933. /**
  28934. * The offset of the displacement map's values on the mesh's vertices.
  28935. * The bias is added to the scaled sample of the displacement map.
  28936. * Without a displacement map set, this value is not applied.
  28937. *
  28938. * @type {number}
  28939. * @default 0
  28940. */
  28941. this.displacementBias = 0;
  28942. /**
  28943. * Renders the geometry as a wireframe.
  28944. *
  28945. * @type {boolean}
  28946. * @default false
  28947. */
  28948. this.wireframe = false;
  28949. /**
  28950. * Controls the thickness of the wireframe.
  28951. *
  28952. * WebGL and WebGPU ignore this property and always render
  28953. * 1 pixel wide lines.
  28954. *
  28955. * @type {number}
  28956. * @default 1
  28957. */
  28958. this.wireframeLinewidth = 1;
  28959. /**
  28960. * Whether the material is rendered with flat shading or not.
  28961. *
  28962. * @type {boolean}
  28963. * @default false
  28964. */
  28965. this.flatShading = false;
  28966. this.setValues( parameters );
  28967. }
  28968. copy( source ) {
  28969. super.copy( source );
  28970. this.bumpMap = source.bumpMap;
  28971. this.bumpScale = source.bumpScale;
  28972. this.normalMap = source.normalMap;
  28973. this.normalMapType = source.normalMapType;
  28974. this.normalScale.copy( source.normalScale );
  28975. this.displacementMap = source.displacementMap;
  28976. this.displacementScale = source.displacementScale;
  28977. this.displacementBias = source.displacementBias;
  28978. this.wireframe = source.wireframe;
  28979. this.wireframeLinewidth = source.wireframeLinewidth;
  28980. this.flatShading = source.flatShading;
  28981. return this;
  28982. }
  28983. }
  28984. /**
  28985. * A material for non-shiny surfaces, without specular highlights.
  28986. *
  28987. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  28988. * model for calculating reflectance. This can simulate some surfaces (such
  28989. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  28990. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  28991. * shading.
  28992. *
  28993. * Due to the simplicity of the reflectance and illumination models,
  28994. * performance will be greater when using this material over the
  28995. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  28996. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  28997. *
  28998. * @augments Material
  28999. * @demo scenes/material-browser.html#MeshLambertMaterial
  29000. */
  29001. class MeshLambertMaterial extends Material {
  29002. /**
  29003. * Constructs a new mesh lambert material.
  29004. *
  29005. * @param {Object} [parameters] - An object with one or more properties
  29006. * defining the material's appearance. Any property of the material
  29007. * (including any property from inherited materials) can be passed
  29008. * in here. Color values can be passed any type of value accepted
  29009. * by {@link Color#set}.
  29010. */
  29011. constructor( parameters ) {
  29012. super();
  29013. /**
  29014. * This flag can be used for type testing.
  29015. *
  29016. * @type {boolean}
  29017. * @readonly
  29018. * @default true
  29019. */
  29020. this.isMeshLambertMaterial = true;
  29021. this.type = 'MeshLambertMaterial';
  29022. /**
  29023. * Color of the material.
  29024. *
  29025. * @type {Color}
  29026. * @default (1,1,1)
  29027. */
  29028. this.color = new Color( 0xffffff ); // diffuse
  29029. /**
  29030. * The color map. May optionally include an alpha channel, typically combined
  29031. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29032. * color is modulated by the diffuse `color`.
  29033. *
  29034. * @type {?Texture}
  29035. * @default null
  29036. */
  29037. this.map = null;
  29038. /**
  29039. * The light map. Requires a second set of UVs.
  29040. *
  29041. * @type {?Texture}
  29042. * @default null
  29043. */
  29044. this.lightMap = null;
  29045. /**
  29046. * Intensity of the baked light.
  29047. *
  29048. * @type {number}
  29049. * @default 1
  29050. */
  29051. this.lightMapIntensity = 1.0;
  29052. /**
  29053. * The red channel of this texture is used as the ambient occlusion map.
  29054. * Requires a second set of UVs.
  29055. *
  29056. * @type {?Texture}
  29057. * @default null
  29058. */
  29059. this.aoMap = null;
  29060. /**
  29061. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29062. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29063. * red channel is also `1`, ambient light is fully occluded on a surface.
  29064. *
  29065. * @type {number}
  29066. * @default 1
  29067. */
  29068. this.aoMapIntensity = 1.0;
  29069. /**
  29070. * Emissive (light) color of the material, essentially a solid color
  29071. * unaffected by other lighting.
  29072. *
  29073. * @type {Color}
  29074. * @default (0,0,0)
  29075. */
  29076. this.emissive = new Color( 0x000000 );
  29077. /**
  29078. * Intensity of the emissive light. Modulates the emissive color.
  29079. *
  29080. * @type {number}
  29081. * @default 1
  29082. */
  29083. this.emissiveIntensity = 1.0;
  29084. /**
  29085. * Set emissive (glow) map. The emissive map color is modulated by the
  29086. * emissive color and the emissive intensity. If you have an emissive map,
  29087. * be sure to set the emissive color to something other than black.
  29088. *
  29089. * @type {?Texture}
  29090. * @default null
  29091. */
  29092. this.emissiveMap = null;
  29093. /**
  29094. * The texture to create a bump map. The black and white values map to the
  29095. * perceived depth in relation to the lights. Bump doesn't actually affect
  29096. * the geometry of the object, only the lighting. If a normal map is defined
  29097. * this will be ignored.
  29098. *
  29099. * @type {?Texture}
  29100. * @default null
  29101. */
  29102. this.bumpMap = null;
  29103. /**
  29104. * How much the bump map affects the material. Typical range is `[0,1]`.
  29105. *
  29106. * @type {number}
  29107. * @default 1
  29108. */
  29109. this.bumpScale = 1;
  29110. /**
  29111. * The texture to create a normal map. The RGB values affect the surface
  29112. * normal for each pixel fragment and change the way the color is lit. Normal
  29113. * maps do not change the actual shape of the surface, only the lighting. In
  29114. * case the material has a normal map authored using the left handed
  29115. * convention, the `y` component of `normalScale` should be negated to compensate
  29116. * for the different handedness.
  29117. *
  29118. * @type {?Texture}
  29119. * @default null
  29120. */
  29121. this.normalMap = null;
  29122. /**
  29123. * The type of normal map.
  29124. *
  29125. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29126. * @default TangentSpaceNormalMap
  29127. */
  29128. this.normalMapType = TangentSpaceNormalMap;
  29129. /**
  29130. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29131. *
  29132. * @type {Vector2}
  29133. * @default (1,1)
  29134. */
  29135. this.normalScale = new Vector2( 1, 1 );
  29136. /**
  29137. * The displacement map affects the position of the mesh's vertices. Unlike
  29138. * other maps which only affect the light and shade of the material the
  29139. * displaced vertices can cast shadows, block other objects, and otherwise
  29140. * act as real geometry. The displacement texture is an image where the value
  29141. * of each pixel (white being the highest) is mapped against, and
  29142. * repositions, the vertices of the mesh.
  29143. *
  29144. * @type {?Texture}
  29145. * @default null
  29146. */
  29147. this.displacementMap = null;
  29148. /**
  29149. * How much the displacement map affects the mesh (where black is no
  29150. * displacement, and white is maximum displacement). Without a displacement
  29151. * map set, this value is not applied.
  29152. *
  29153. * @type {number}
  29154. * @default 0
  29155. */
  29156. this.displacementScale = 1;
  29157. /**
  29158. * The offset of the displacement map's values on the mesh's vertices.
  29159. * The bias is added to the scaled sample of the displacement map.
  29160. * Without a displacement map set, this value is not applied.
  29161. *
  29162. * @type {number}
  29163. * @default 0
  29164. */
  29165. this.displacementBias = 0;
  29166. /**
  29167. * Specular map used by the material.
  29168. *
  29169. * @type {?Texture}
  29170. * @default null
  29171. */
  29172. this.specularMap = null;
  29173. /**
  29174. * The alpha map is a grayscale texture that controls the opacity across the
  29175. * surface (black: fully transparent; white: fully opaque).
  29176. *
  29177. * Only the color of the texture is used, ignoring the alpha channel if one
  29178. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29179. * when sampling this texture due to the extra bit of precision provided for
  29180. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29181. * luminance/alpha textures will also still work as expected.
  29182. *
  29183. * @type {?Texture}
  29184. * @default null
  29185. */
  29186. this.alphaMap = null;
  29187. /**
  29188. * The environment map.
  29189. *
  29190. * @type {?Texture}
  29191. * @default null
  29192. */
  29193. this.envMap = null;
  29194. /**
  29195. * The rotation of the environment map in radians.
  29196. *
  29197. * @type {Euler}
  29198. * @default (0,0,0)
  29199. */
  29200. this.envMapRotation = new Euler();
  29201. /**
  29202. * How to combine the result of the surface's color with the environment map, if any.
  29203. *
  29204. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29205. * blend between the two colors.
  29206. *
  29207. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29208. * @default MultiplyOperation
  29209. */
  29210. this.combine = MultiplyOperation;
  29211. /**
  29212. * How much the environment map affects the surface.
  29213. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29214. *
  29215. * @type {number}
  29216. * @default 1
  29217. */
  29218. this.reflectivity = 1;
  29219. /**
  29220. * Scales the effect of the environment map by multiplying its color.
  29221. *
  29222. * @type {number}
  29223. * @default 1
  29224. */
  29225. this.envMapIntensity = 1.0;
  29226. /**
  29227. * The index of refraction (IOR) of air (approximately 1) divided by the
  29228. * index of refraction of the material. It is used with environment mapping
  29229. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29230. * The refraction ratio should not exceed `1`.
  29231. *
  29232. * @type {number}
  29233. * @default 0.98
  29234. */
  29235. this.refractionRatio = 0.98;
  29236. /**
  29237. * Renders the geometry as a wireframe.
  29238. *
  29239. * @type {boolean}
  29240. * @default false
  29241. */
  29242. this.wireframe = false;
  29243. /**
  29244. * Controls the thickness of the wireframe.
  29245. *
  29246. * Can only be used with {@link SVGRenderer}.
  29247. *
  29248. * @type {number}
  29249. * @default 1
  29250. */
  29251. this.wireframeLinewidth = 1;
  29252. /**
  29253. * Defines appearance of wireframe ends.
  29254. *
  29255. * Can only be used with {@link SVGRenderer}.
  29256. *
  29257. * @type {('round'|'bevel'|'miter')}
  29258. * @default 'round'
  29259. */
  29260. this.wireframeLinecap = 'round';
  29261. /**
  29262. * Defines appearance of wireframe joints.
  29263. *
  29264. * Can only be used with {@link SVGRenderer}.
  29265. *
  29266. * @type {('round'|'bevel'|'miter')}
  29267. * @default 'round'
  29268. */
  29269. this.wireframeLinejoin = 'round';
  29270. /**
  29271. * Whether the material is rendered with flat shading or not.
  29272. *
  29273. * @type {boolean}
  29274. * @default false
  29275. */
  29276. this.flatShading = false;
  29277. /**
  29278. * Whether the material is affected by fog or not.
  29279. *
  29280. * @type {boolean}
  29281. * @default true
  29282. */
  29283. this.fog = true;
  29284. this.setValues( parameters );
  29285. }
  29286. copy( source ) {
  29287. super.copy( source );
  29288. this.color.copy( source.color );
  29289. this.map = source.map;
  29290. this.lightMap = source.lightMap;
  29291. this.lightMapIntensity = source.lightMapIntensity;
  29292. this.aoMap = source.aoMap;
  29293. this.aoMapIntensity = source.aoMapIntensity;
  29294. this.emissive.copy( source.emissive );
  29295. this.emissiveMap = source.emissiveMap;
  29296. this.emissiveIntensity = source.emissiveIntensity;
  29297. this.bumpMap = source.bumpMap;
  29298. this.bumpScale = source.bumpScale;
  29299. this.normalMap = source.normalMap;
  29300. this.normalMapType = source.normalMapType;
  29301. this.normalScale.copy( source.normalScale );
  29302. this.displacementMap = source.displacementMap;
  29303. this.displacementScale = source.displacementScale;
  29304. this.displacementBias = source.displacementBias;
  29305. this.specularMap = source.specularMap;
  29306. this.alphaMap = source.alphaMap;
  29307. this.envMap = source.envMap;
  29308. this.envMapRotation.copy( source.envMapRotation );
  29309. this.combine = source.combine;
  29310. this.reflectivity = source.reflectivity;
  29311. this.envMapIntensity = source.envMapIntensity;
  29312. this.refractionRatio = source.refractionRatio;
  29313. this.wireframe = source.wireframe;
  29314. this.wireframeLinewidth = source.wireframeLinewidth;
  29315. this.wireframeLinecap = source.wireframeLinecap;
  29316. this.wireframeLinejoin = source.wireframeLinejoin;
  29317. this.flatShading = source.flatShading;
  29318. this.fog = source.fog;
  29319. return this;
  29320. }
  29321. }
  29322. /**
  29323. * A material for drawing geometry by depth. Depth is based off of the camera
  29324. * near and far plane. White is nearest, black is farthest.
  29325. *
  29326. * @augments Material
  29327. * @demo scenes/material-browser.html#MeshDepthMaterial
  29328. */
  29329. class MeshDepthMaterial extends Material {
  29330. /**
  29331. * Constructs a new mesh depth material.
  29332. *
  29333. * @param {Object} [parameters] - An object with one or more properties
  29334. * defining the material's appearance. Any property of the material
  29335. * (including any property from inherited materials) can be passed
  29336. * in here. Color values can be passed any type of value accepted
  29337. * by {@link Color#set}.
  29338. */
  29339. constructor( parameters ) {
  29340. super();
  29341. /**
  29342. * This flag can be used for type testing.
  29343. *
  29344. * @type {boolean}
  29345. * @readonly
  29346. * @default true
  29347. */
  29348. this.isMeshDepthMaterial = true;
  29349. this.type = 'MeshDepthMaterial';
  29350. /**
  29351. * Type for depth packing.
  29352. *
  29353. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29354. * @default BasicDepthPacking
  29355. */
  29356. this.depthPacking = BasicDepthPacking;
  29357. /**
  29358. * The color map. May optionally include an alpha channel, typically combined
  29359. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29360. *
  29361. * @type {?Texture}
  29362. * @default null
  29363. */
  29364. this.map = null;
  29365. /**
  29366. * The alpha map is a grayscale texture that controls the opacity across the
  29367. * surface (black: fully transparent; white: fully opaque).
  29368. *
  29369. * Only the color of the texture is used, ignoring the alpha channel if one
  29370. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29371. * when sampling this texture due to the extra bit of precision provided for
  29372. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29373. * luminance/alpha textures will also still work as expected.
  29374. *
  29375. * @type {?Texture}
  29376. * @default null
  29377. */
  29378. this.alphaMap = null;
  29379. /**
  29380. * The displacement map affects the position of the mesh's vertices. Unlike
  29381. * other maps which only affect the light and shade of the material the
  29382. * displaced vertices can cast shadows, block other objects, and otherwise
  29383. * act as real geometry. The displacement texture is an image where the value
  29384. * of each pixel (white being the highest) is mapped against, and
  29385. * repositions, the vertices of the mesh.
  29386. *
  29387. * @type {?Texture}
  29388. * @default null
  29389. */
  29390. this.displacementMap = null;
  29391. /**
  29392. * How much the displacement map affects the mesh (where black is no
  29393. * displacement, and white is maximum displacement). Without a displacement
  29394. * map set, this value is not applied.
  29395. *
  29396. * @type {number}
  29397. * @default 0
  29398. */
  29399. this.displacementScale = 1;
  29400. /**
  29401. * The offset of the displacement map's values on the mesh's vertices.
  29402. * The bias is added to the scaled sample of the displacement map.
  29403. * Without a displacement map set, this value is not applied.
  29404. *
  29405. * @type {number}
  29406. * @default 0
  29407. */
  29408. this.displacementBias = 0;
  29409. /**
  29410. * Renders the geometry as a wireframe.
  29411. *
  29412. * @type {boolean}
  29413. * @default false
  29414. */
  29415. this.wireframe = false;
  29416. /**
  29417. * Controls the thickness of the wireframe.
  29418. *
  29419. * WebGL and WebGPU ignore this property and always render
  29420. * 1 pixel wide lines.
  29421. *
  29422. * @type {number}
  29423. * @default 1
  29424. */
  29425. this.wireframeLinewidth = 1;
  29426. this.setValues( parameters );
  29427. }
  29428. copy( source ) {
  29429. super.copy( source );
  29430. this.depthPacking = source.depthPacking;
  29431. this.map = source.map;
  29432. this.alphaMap = source.alphaMap;
  29433. this.displacementMap = source.displacementMap;
  29434. this.displacementScale = source.displacementScale;
  29435. this.displacementBias = source.displacementBias;
  29436. this.wireframe = source.wireframe;
  29437. this.wireframeLinewidth = source.wireframeLinewidth;
  29438. return this;
  29439. }
  29440. }
  29441. /**
  29442. * A material used internally for implementing shadow mapping with
  29443. * point lights.
  29444. *
  29445. * Can also be used to customize the shadow casting of an object by assigning
  29446. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29447. * The following examples demonstrates this approach in order to ensure
  29448. * transparent parts of objects do not cast shadows.
  29449. *
  29450. * @augments Material
  29451. */
  29452. class MeshDistanceMaterial extends Material {
  29453. /**
  29454. * Constructs a new mesh distance material.
  29455. *
  29456. * @param {Object} [parameters] - An object with one or more properties
  29457. * defining the material's appearance. Any property of the material
  29458. * (including any property from inherited materials) can be passed
  29459. * in here. Color values can be passed any type of value accepted
  29460. * by {@link Color#set}.
  29461. */
  29462. constructor( parameters ) {
  29463. super();
  29464. /**
  29465. * This flag can be used for type testing.
  29466. *
  29467. * @type {boolean}
  29468. * @readonly
  29469. * @default true
  29470. */
  29471. this.isMeshDistanceMaterial = true;
  29472. this.type = 'MeshDistanceMaterial';
  29473. /**
  29474. * The color map. May optionally include an alpha channel, typically combined
  29475. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29476. *
  29477. * @type {?Texture}
  29478. * @default null
  29479. */
  29480. this.map = null;
  29481. /**
  29482. * The alpha map is a grayscale texture that controls the opacity across the
  29483. * surface (black: fully transparent; white: fully opaque).
  29484. *
  29485. * Only the color of the texture is used, ignoring the alpha channel if one
  29486. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29487. * when sampling this texture due to the extra bit of precision provided for
  29488. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29489. * luminance/alpha textures will also still work as expected.
  29490. *
  29491. * @type {?Texture}
  29492. * @default null
  29493. */
  29494. this.alphaMap = null;
  29495. /**
  29496. * The displacement map affects the position of the mesh's vertices. Unlike
  29497. * other maps which only affect the light and shade of the material the
  29498. * displaced vertices can cast shadows, block other objects, and otherwise
  29499. * act as real geometry. The displacement texture is an image where the value
  29500. * of each pixel (white being the highest) is mapped against, and
  29501. * repositions, the vertices of the mesh.
  29502. *
  29503. * @type {?Texture}
  29504. * @default null
  29505. */
  29506. this.displacementMap = null;
  29507. /**
  29508. * How much the displacement map affects the mesh (where black is no
  29509. * displacement, and white is maximum displacement). Without a displacement
  29510. * map set, this value is not applied.
  29511. *
  29512. * @type {number}
  29513. * @default 0
  29514. */
  29515. this.displacementScale = 1;
  29516. /**
  29517. * The offset of the displacement map's values on the mesh's vertices.
  29518. * The bias is added to the scaled sample of the displacement map.
  29519. * Without a displacement map set, this value is not applied.
  29520. *
  29521. * @type {number}
  29522. * @default 0
  29523. */
  29524. this.displacementBias = 0;
  29525. this.setValues( parameters );
  29526. }
  29527. copy( source ) {
  29528. super.copy( source );
  29529. this.map = source.map;
  29530. this.alphaMap = source.alphaMap;
  29531. this.displacementMap = source.displacementMap;
  29532. this.displacementScale = source.displacementScale;
  29533. this.displacementBias = source.displacementBias;
  29534. return this;
  29535. }
  29536. }
  29537. /**
  29538. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29539. * material color and shading.
  29540. *
  29541. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29542. * baked lighting. It will cast a shadow onto an object that receives shadows
  29543. * (and shadow clipping works), but it will not self-shadow or receive
  29544. * shadows.
  29545. *
  29546. * @augments Material
  29547. * @demo scenes/material-browser.html#MeshMatcapMaterial
  29548. */
  29549. class MeshMatcapMaterial extends Material {
  29550. /**
  29551. * Constructs a new mesh matcap material.
  29552. *
  29553. * @param {Object} [parameters] - An object with one or more properties
  29554. * defining the material's appearance. Any property of the material
  29555. * (including any property from inherited materials) can be passed
  29556. * in here. Color values can be passed any type of value accepted
  29557. * by {@link Color#set}.
  29558. */
  29559. constructor( parameters ) {
  29560. super();
  29561. /**
  29562. * This flag can be used for type testing.
  29563. *
  29564. * @type {boolean}
  29565. * @readonly
  29566. * @default true
  29567. */
  29568. this.isMeshMatcapMaterial = true;
  29569. this.defines = { 'MATCAP': '' };
  29570. this.type = 'MeshMatcapMaterial';
  29571. /**
  29572. * Color of the material.
  29573. *
  29574. * @type {Color}
  29575. * @default (1,1,1)
  29576. */
  29577. this.color = new Color( 0xffffff ); // diffuse
  29578. /**
  29579. * The matcap map.
  29580. *
  29581. * @type {?Texture}
  29582. * @default null
  29583. */
  29584. this.matcap = null;
  29585. /**
  29586. * The color map. May optionally include an alpha channel, typically combined
  29587. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29588. * color is modulated by the diffuse `color`.
  29589. *
  29590. * @type {?Texture}
  29591. * @default null
  29592. */
  29593. this.map = null;
  29594. /**
  29595. * The texture to create a bump map. The black and white values map to the
  29596. * perceived depth in relation to the lights. Bump doesn't actually affect
  29597. * the geometry of the object, only the lighting. If a normal map is defined
  29598. * this will be ignored.
  29599. *
  29600. * @type {?Texture}
  29601. * @default null
  29602. */
  29603. this.bumpMap = null;
  29604. /**
  29605. * How much the bump map affects the material. Typical range is `[0,1]`.
  29606. *
  29607. * @type {number}
  29608. * @default 1
  29609. */
  29610. this.bumpScale = 1;
  29611. /**
  29612. * The texture to create a normal map. The RGB values affect the surface
  29613. * normal for each pixel fragment and change the way the color is lit. Normal
  29614. * maps do not change the actual shape of the surface, only the lighting. In
  29615. * case the material has a normal map authored using the left handed
  29616. * convention, the `y` component of `normalScale` should be negated to compensate
  29617. * for the different handedness.
  29618. *
  29619. * @type {?Texture}
  29620. * @default null
  29621. */
  29622. this.normalMap = null;
  29623. /**
  29624. * The type of normal map.
  29625. *
  29626. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29627. * @default TangentSpaceNormalMap
  29628. */
  29629. this.normalMapType = TangentSpaceNormalMap;
  29630. /**
  29631. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29632. *
  29633. * @type {Vector2}
  29634. * @default (1,1)
  29635. */
  29636. this.normalScale = new Vector2( 1, 1 );
  29637. /**
  29638. * The displacement map affects the position of the mesh's vertices. Unlike
  29639. * other maps which only affect the light and shade of the material the
  29640. * displaced vertices can cast shadows, block other objects, and otherwise
  29641. * act as real geometry. The displacement texture is an image where the value
  29642. * of each pixel (white being the highest) is mapped against, and
  29643. * repositions, the vertices of the mesh.
  29644. *
  29645. * @type {?Texture}
  29646. * @default null
  29647. */
  29648. this.displacementMap = null;
  29649. /**
  29650. * How much the displacement map affects the mesh (where black is no
  29651. * displacement, and white is maximum displacement). Without a displacement
  29652. * map set, this value is not applied.
  29653. *
  29654. * @type {number}
  29655. * @default 0
  29656. */
  29657. this.displacementScale = 1;
  29658. /**
  29659. * The offset of the displacement map's values on the mesh's vertices.
  29660. * The bias is added to the scaled sample of the displacement map.
  29661. * Without a displacement map set, this value is not applied.
  29662. *
  29663. * @type {number}
  29664. * @default 0
  29665. */
  29666. this.displacementBias = 0;
  29667. /**
  29668. * The alpha map is a grayscale texture that controls the opacity across the
  29669. * surface (black: fully transparent; white: fully opaque).
  29670. *
  29671. * Only the color of the texture is used, ignoring the alpha channel if one
  29672. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29673. * when sampling this texture due to the extra bit of precision provided for
  29674. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29675. * luminance/alpha textures will also still work as expected.
  29676. *
  29677. * @type {?Texture}
  29678. * @default null
  29679. */
  29680. this.alphaMap = null;
  29681. /**
  29682. * Renders the geometry as a wireframe.
  29683. *
  29684. * @type {boolean}
  29685. * @default false
  29686. */
  29687. this.wireframe = false;
  29688. /**
  29689. * Controls the thickness of the wireframe.
  29690. *
  29691. * Can only be used with {@link SVGRenderer}.
  29692. *
  29693. * @type {number}
  29694. * @default 1
  29695. */
  29696. this.wireframeLinewidth = 1;
  29697. /**
  29698. * Whether the material is rendered with flat shading or not.
  29699. *
  29700. * @type {boolean}
  29701. * @default false
  29702. */
  29703. this.flatShading = false;
  29704. /**
  29705. * Whether the material is affected by fog or not.
  29706. *
  29707. * @type {boolean}
  29708. * @default true
  29709. */
  29710. this.fog = true;
  29711. this.setValues( parameters );
  29712. }
  29713. copy( source ) {
  29714. super.copy( source );
  29715. this.defines = { 'MATCAP': '' };
  29716. this.color.copy( source.color );
  29717. this.matcap = source.matcap;
  29718. this.map = source.map;
  29719. this.bumpMap = source.bumpMap;
  29720. this.bumpScale = source.bumpScale;
  29721. this.normalMap = source.normalMap;
  29722. this.normalMapType = source.normalMapType;
  29723. this.normalScale.copy( source.normalScale );
  29724. this.displacementMap = source.displacementMap;
  29725. this.displacementScale = source.displacementScale;
  29726. this.displacementBias = source.displacementBias;
  29727. this.alphaMap = source.alphaMap;
  29728. this.wireframe = source.wireframe;
  29729. this.wireframeLinewidth = source.wireframeLinewidth;
  29730. this.flatShading = source.flatShading;
  29731. this.fog = source.fog;
  29732. return this;
  29733. }
  29734. }
  29735. /**
  29736. * A material for rendering line primitives.
  29737. *
  29738. * Materials define the appearance of renderable 3D objects.
  29739. *
  29740. * ```js
  29741. * const material = new THREE.LineDashedMaterial( {
  29742. * color: 0xffffff,
  29743. * scale: 1,
  29744. * dashSize: 3,
  29745. * gapSize: 1,
  29746. * } );
  29747. * ```
  29748. *
  29749. * @augments LineBasicMaterial
  29750. */
  29751. class LineDashedMaterial extends LineBasicMaterial {
  29752. /**
  29753. * Constructs a new line dashed material.
  29754. *
  29755. * @param {Object} [parameters] - An object with one or more properties
  29756. * defining the material's appearance. Any property of the material
  29757. * (including any property from inherited materials) can be passed
  29758. * in here. Color values can be passed any type of value accepted
  29759. * by {@link Color#set}.
  29760. */
  29761. constructor( parameters ) {
  29762. super();
  29763. /**
  29764. * This flag can be used for type testing.
  29765. *
  29766. * @type {boolean}
  29767. * @readonly
  29768. * @default true
  29769. */
  29770. this.isLineDashedMaterial = true;
  29771. this.type = 'LineDashedMaterial';
  29772. /**
  29773. * The scale of the dashed part of a line.
  29774. *
  29775. * @type {number}
  29776. * @default 1
  29777. */
  29778. this.scale = 1;
  29779. /**
  29780. * The size of the dash. This is both the gap with the stroke.
  29781. *
  29782. * @type {number}
  29783. * @default 3
  29784. */
  29785. this.dashSize = 3;
  29786. /**
  29787. * The size of the gap.
  29788. *
  29789. * @type {number}
  29790. * @default 1
  29791. */
  29792. this.gapSize = 1;
  29793. this.setValues( parameters );
  29794. }
  29795. copy( source ) {
  29796. super.copy( source );
  29797. this.scale = source.scale;
  29798. this.dashSize = source.dashSize;
  29799. this.gapSize = source.gapSize;
  29800. return this;
  29801. }
  29802. }
  29803. /**
  29804. * Converts an array to a specific type.
  29805. *
  29806. * @param {TypedArray|Array} array - The array to convert.
  29807. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29808. * @return {TypedArray} The converted array.
  29809. */
  29810. function convertArray( array, type ) {
  29811. if ( ! array || array.constructor === type ) return array;
  29812. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29813. return new type( array ); // create typed array
  29814. }
  29815. return Array.prototype.slice.call( array ); // create Array
  29816. }
  29817. /**
  29818. * Returns an array by which times and values can be sorted.
  29819. *
  29820. * @param {Array<number>} times - The keyframe time values.
  29821. * @return {Array<number>} The array.
  29822. */
  29823. function getKeyframeOrder( times ) {
  29824. function compareTime( i, j ) {
  29825. return times[ i ] - times[ j ];
  29826. }
  29827. const n = times.length;
  29828. const result = new Array( n );
  29829. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29830. result.sort( compareTime );
  29831. return result;
  29832. }
  29833. /**
  29834. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29835. *
  29836. * @param {Array<number>} values - The values to sort.
  29837. * @param {number} stride - The stride.
  29838. * @param {Array<number>} order - The sort order.
  29839. * @return {Array<number>} The sorted values.
  29840. */
  29841. function sortedArray( values, stride, order ) {
  29842. const nValues = values.length;
  29843. const result = new values.constructor( nValues );
  29844. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29845. const srcOffset = order[ i ] * stride;
  29846. for ( let j = 0; j !== stride; ++ j ) {
  29847. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29848. }
  29849. }
  29850. return result;
  29851. }
  29852. /**
  29853. * Used for parsing AOS keyframe formats.
  29854. *
  29855. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29856. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  29857. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  29858. * @param {string} valuePropertyName - The name of the property to use.
  29859. */
  29860. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  29861. let i = 1, key = jsonKeys[ 0 ];
  29862. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  29863. key = jsonKeys[ i ++ ];
  29864. }
  29865. if ( key === undefined ) return; // no data
  29866. let value = key[ valuePropertyName ];
  29867. if ( value === undefined ) return; // no data
  29868. if ( Array.isArray( value ) ) {
  29869. do {
  29870. value = key[ valuePropertyName ];
  29871. if ( value !== undefined ) {
  29872. times.push( key.time );
  29873. values.push( ...value ); // push all elements
  29874. }
  29875. key = jsonKeys[ i ++ ];
  29876. } while ( key !== undefined );
  29877. } else if ( value.toArray !== undefined ) {
  29878. // ...assume THREE.Math-ish
  29879. do {
  29880. value = key[ valuePropertyName ];
  29881. if ( value !== undefined ) {
  29882. times.push( key.time );
  29883. value.toArray( values, values.length );
  29884. }
  29885. key = jsonKeys[ i ++ ];
  29886. } while ( key !== undefined );
  29887. } else {
  29888. // otherwise push as-is
  29889. do {
  29890. value = key[ valuePropertyName ];
  29891. if ( value !== undefined ) {
  29892. times.push( key.time );
  29893. values.push( value );
  29894. }
  29895. key = jsonKeys[ i ++ ];
  29896. } while ( key !== undefined );
  29897. }
  29898. }
  29899. /**
  29900. * Creates a new clip, containing only the segment of the original clip between the given frames.
  29901. *
  29902. * @param {AnimationClip} sourceClip - The values to sort.
  29903. * @param {string} name - The name of the clip.
  29904. * @param {number} startFrame - The start frame.
  29905. * @param {number} endFrame - The end frame.
  29906. * @param {number} [fps=30] - The FPS.
  29907. * @return {AnimationClip} The new sub clip.
  29908. */
  29909. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  29910. const clip = sourceClip.clone();
  29911. clip.name = name;
  29912. const tracks = [];
  29913. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29914. const track = clip.tracks[ i ];
  29915. const valueSize = track.getValueSize();
  29916. const times = [];
  29917. const values = [];
  29918. for ( let j = 0; j < track.times.length; ++ j ) {
  29919. const frame = track.times[ j ] * fps;
  29920. if ( frame < startFrame || frame >= endFrame ) continue;
  29921. times.push( track.times[ j ] );
  29922. for ( let k = 0; k < valueSize; ++ k ) {
  29923. values.push( track.values[ j * valueSize + k ] );
  29924. }
  29925. }
  29926. if ( times.length === 0 ) continue;
  29927. track.times = convertArray( times, track.times.constructor );
  29928. track.values = convertArray( values, track.values.constructor );
  29929. tracks.push( track );
  29930. }
  29931. clip.tracks = tracks;
  29932. // find minimum .times value across all tracks in the trimmed clip
  29933. let minStartTime = Infinity;
  29934. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29935. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  29936. minStartTime = clip.tracks[ i ].times[ 0 ];
  29937. }
  29938. }
  29939. // shift all tracks such that clip begins at t=0
  29940. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29941. clip.tracks[ i ].shift( -1 * minStartTime );
  29942. }
  29943. clip.resetDuration();
  29944. return clip;
  29945. }
  29946. /**
  29947. * Converts the keyframes of the given animation clip to an additive format.
  29948. *
  29949. * @param {AnimationClip} targetClip - The clip to make additive.
  29950. * @param {number} [referenceFrame=0] - The reference frame.
  29951. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  29952. * @param {number} [fps=30] - The FPS.
  29953. * @return {AnimationClip} The updated clip which is now additive.
  29954. */
  29955. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  29956. if ( fps <= 0 ) fps = 30;
  29957. const numTracks = referenceClip.tracks.length;
  29958. const referenceTime = referenceFrame / fps;
  29959. // Make each track's values relative to the values at the reference frame
  29960. for ( let i = 0; i < numTracks; ++ i ) {
  29961. const referenceTrack = referenceClip.tracks[ i ];
  29962. const referenceTrackType = referenceTrack.ValueTypeName;
  29963. // Skip this track if it's non-numeric
  29964. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  29965. // Find the track in the target clip whose name and type matches the reference track
  29966. const targetTrack = targetClip.tracks.find( function ( track ) {
  29967. return track.name === referenceTrack.name
  29968. && track.ValueTypeName === referenceTrackType;
  29969. } );
  29970. if ( targetTrack === undefined ) continue;
  29971. let referenceOffset = 0;
  29972. const referenceValueSize = referenceTrack.getValueSize();
  29973. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  29974. referenceOffset = referenceValueSize / 3;
  29975. }
  29976. let targetOffset = 0;
  29977. const targetValueSize = targetTrack.getValueSize();
  29978. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  29979. targetOffset = targetValueSize / 3;
  29980. }
  29981. const lastIndex = referenceTrack.times.length - 1;
  29982. let referenceValue;
  29983. // Find the value to subtract out of the track
  29984. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  29985. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  29986. const startIndex = referenceOffset;
  29987. const endIndex = referenceValueSize - referenceOffset;
  29988. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  29989. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  29990. // Reference frame is after the last keyframe, so just use the last keyframe
  29991. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  29992. const endIndex = startIndex + referenceValueSize - referenceOffset;
  29993. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  29994. } else {
  29995. // Interpolate to the reference value
  29996. const interpolant = referenceTrack.createInterpolant();
  29997. const startIndex = referenceOffset;
  29998. const endIndex = referenceValueSize - referenceOffset;
  29999. interpolant.evaluate( referenceTime );
  30000. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30001. }
  30002. // Conjugate the quaternion
  30003. if ( referenceTrackType === 'quaternion' ) {
  30004. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30005. referenceQuat.toArray( referenceValue );
  30006. }
  30007. // Subtract the reference value from all of the track values
  30008. const numTimes = targetTrack.times.length;
  30009. for ( let j = 0; j < numTimes; ++ j ) {
  30010. const valueStart = j * targetValueSize + targetOffset;
  30011. if ( referenceTrackType === 'quaternion' ) {
  30012. // Multiply the conjugate for quaternion track types
  30013. Quaternion.multiplyQuaternionsFlat(
  30014. targetTrack.values,
  30015. valueStart,
  30016. referenceValue,
  30017. 0,
  30018. targetTrack.values,
  30019. valueStart
  30020. );
  30021. } else {
  30022. const valueEnd = targetValueSize - targetOffset * 2;
  30023. // Subtract each value for all other numeric track types
  30024. for ( let k = 0; k < valueEnd; ++ k ) {
  30025. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30026. }
  30027. }
  30028. }
  30029. }
  30030. targetClip.blendMode = AdditiveAnimationBlendMode;
  30031. return targetClip;
  30032. }
  30033. /**
  30034. * A class with various methods to assist with animations.
  30035. *
  30036. * @hideconstructor
  30037. */
  30038. class AnimationUtils {
  30039. /**
  30040. * Converts an array to a specific type
  30041. *
  30042. * @static
  30043. * @param {TypedArray|Array} array - The array to convert.
  30044. * @param {TypedArray.constructor} type - The constructor of a type array.
  30045. * @return {TypedArray} The converted array
  30046. */
  30047. static convertArray( array, type ) {
  30048. return convertArray( array, type );
  30049. }
  30050. /**
  30051. * Returns `true` if the given object is a typed array.
  30052. *
  30053. * @static
  30054. * @param {any} object - The object to check.
  30055. * @return {boolean} Whether the given object is a typed array.
  30056. */
  30057. static isTypedArray( object ) {
  30058. return isTypedArray( object );
  30059. }
  30060. /**
  30061. * Returns an array by which times and values can be sorted.
  30062. *
  30063. * @static
  30064. * @param {Array<number>} times - The keyframe time values.
  30065. * @return {Array<number>} The array.
  30066. */
  30067. static getKeyframeOrder( times ) {
  30068. return getKeyframeOrder( times );
  30069. }
  30070. /**
  30071. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30072. *
  30073. * @static
  30074. * @param {Array<number>} values - The values to sort.
  30075. * @param {number} stride - The stride.
  30076. * @param {Array<number>} order - The sort order.
  30077. * @return {Array<number>} The sorted values.
  30078. */
  30079. static sortedArray( values, stride, order ) {
  30080. return sortedArray( values, stride, order );
  30081. }
  30082. /**
  30083. * Used for parsing AOS keyframe formats.
  30084. *
  30085. * @static
  30086. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30087. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30088. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30089. * @param {string} valuePropertyName - The name of the property to use.
  30090. */
  30091. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30092. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30093. }
  30094. /**
  30095. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30096. *
  30097. * @static
  30098. * @param {AnimationClip} sourceClip - The values to sort.
  30099. * @param {string} name - The name of the clip.
  30100. * @param {number} startFrame - The start frame.
  30101. * @param {number} endFrame - The end frame.
  30102. * @param {number} [fps=30] - The FPS.
  30103. * @return {AnimationClip} The new sub clip.
  30104. */
  30105. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30106. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30107. }
  30108. /**
  30109. * Converts the keyframes of the given animation clip to an additive format.
  30110. *
  30111. * @static
  30112. * @param {AnimationClip} targetClip - The clip to make additive.
  30113. * @param {number} [referenceFrame=0] - The reference frame.
  30114. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30115. * @param {number} [fps=30] - The FPS.
  30116. * @return {AnimationClip} The updated clip which is now additive.
  30117. */
  30118. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30119. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30120. }
  30121. }
  30122. /**
  30123. * Abstract base class of interpolants over parametric samples.
  30124. *
  30125. * The parameter domain is one dimensional, typically the time or a path
  30126. * along a curve defined by the data.
  30127. *
  30128. * The sample values can have any dimensionality and derived classes may
  30129. * apply special interpretations to the data.
  30130. *
  30131. * This class provides the interval seek in a Template Method, deferring
  30132. * the actual interpolation to derived classes.
  30133. *
  30134. * Time complexity is O(1) for linear access crossing at most two points
  30135. * and O(log N) for random access, where N is the number of positions.
  30136. *
  30137. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30138. *
  30139. * @abstract
  30140. */
  30141. class Interpolant {
  30142. /**
  30143. * Constructs a new interpolant.
  30144. *
  30145. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30146. * @param {TypedArray} sampleValues - The sample values.
  30147. * @param {number} sampleSize - The sample size
  30148. * @param {TypedArray} [resultBuffer] - The result buffer.
  30149. */
  30150. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30151. /**
  30152. * The parameter positions.
  30153. *
  30154. * @type {TypedArray}
  30155. */
  30156. this.parameterPositions = parameterPositions;
  30157. /**
  30158. * A cache index.
  30159. *
  30160. * @private
  30161. * @type {number}
  30162. * @default 0
  30163. */
  30164. this._cachedIndex = 0;
  30165. /**
  30166. * The result buffer.
  30167. *
  30168. * @type {TypedArray}
  30169. */
  30170. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30171. /**
  30172. * The sample values.
  30173. *
  30174. * @type {TypedArray}
  30175. */
  30176. this.sampleValues = sampleValues;
  30177. /**
  30178. * The value size.
  30179. *
  30180. * @type {TypedArray}
  30181. */
  30182. this.valueSize = sampleSize;
  30183. /**
  30184. * The interpolation settings.
  30185. *
  30186. * @type {?Object}
  30187. * @default null
  30188. */
  30189. this.settings = null;
  30190. /**
  30191. * The default settings object.
  30192. *
  30193. * @type {Object}
  30194. */
  30195. this.DefaultSettings_ = {};
  30196. }
  30197. /**
  30198. * Evaluate the interpolant at position `t`.
  30199. *
  30200. * @param {number} t - The interpolation factor.
  30201. * @return {TypedArray} The result buffer.
  30202. */
  30203. evaluate( t ) {
  30204. const pp = this.parameterPositions;
  30205. let i1 = this._cachedIndex,
  30206. t1 = pp[ i1 ],
  30207. t0 = pp[ i1 - 1 ];
  30208. validate_interval: {
  30209. seek: {
  30210. let right;
  30211. linear_scan: {
  30212. //- See http://jsperf.com/comparison-to-undefined/3
  30213. //- slower code:
  30214. //-
  30215. //- if ( t >= t1 || t1 === undefined ) {
  30216. forward_scan: if ( ! ( t < t1 ) ) {
  30217. for ( let giveUpAt = i1 + 2; ; ) {
  30218. if ( t1 === undefined ) {
  30219. if ( t < t0 ) break forward_scan;
  30220. // after end
  30221. i1 = pp.length;
  30222. this._cachedIndex = i1;
  30223. return this.copySampleValue_( i1 - 1 );
  30224. }
  30225. if ( i1 === giveUpAt ) break; // this loop
  30226. t0 = t1;
  30227. t1 = pp[ ++ i1 ];
  30228. if ( t < t1 ) {
  30229. // we have arrived at the sought interval
  30230. break seek;
  30231. }
  30232. }
  30233. // prepare binary search on the right side of the index
  30234. right = pp.length;
  30235. break linear_scan;
  30236. }
  30237. //- slower code:
  30238. //- if ( t < t0 || t0 === undefined ) {
  30239. if ( ! ( t >= t0 ) ) {
  30240. // looping?
  30241. const t1global = pp[ 1 ];
  30242. if ( t < t1global ) {
  30243. i1 = 2; // + 1, using the scan for the details
  30244. t0 = t1global;
  30245. }
  30246. // linear reverse scan
  30247. for ( let giveUpAt = i1 - 2; ; ) {
  30248. if ( t0 === undefined ) {
  30249. // before start
  30250. this._cachedIndex = 0;
  30251. return this.copySampleValue_( 0 );
  30252. }
  30253. if ( i1 === giveUpAt ) break; // this loop
  30254. t1 = t0;
  30255. t0 = pp[ -- i1 - 1 ];
  30256. if ( t >= t0 ) {
  30257. // we have arrived at the sought interval
  30258. break seek;
  30259. }
  30260. }
  30261. // prepare binary search on the left side of the index
  30262. right = i1;
  30263. i1 = 0;
  30264. break linear_scan;
  30265. }
  30266. // the interval is valid
  30267. break validate_interval;
  30268. } // linear scan
  30269. // binary search
  30270. while ( i1 < right ) {
  30271. const mid = ( i1 + right ) >>> 1;
  30272. if ( t < pp[ mid ] ) {
  30273. right = mid;
  30274. } else {
  30275. i1 = mid + 1;
  30276. }
  30277. }
  30278. t1 = pp[ i1 ];
  30279. t0 = pp[ i1 - 1 ];
  30280. // check boundary cases, again
  30281. if ( t0 === undefined ) {
  30282. this._cachedIndex = 0;
  30283. return this.copySampleValue_( 0 );
  30284. }
  30285. if ( t1 === undefined ) {
  30286. i1 = pp.length;
  30287. this._cachedIndex = i1;
  30288. return this.copySampleValue_( i1 - 1 );
  30289. }
  30290. } // seek
  30291. this._cachedIndex = i1;
  30292. this.intervalChanged_( i1, t0, t1 );
  30293. } // validate_interval
  30294. return this.interpolate_( i1, t0, t, t1 );
  30295. }
  30296. /**
  30297. * Returns the interpolation settings.
  30298. *
  30299. * @return {Object} The interpolation settings.
  30300. */
  30301. getSettings_() {
  30302. return this.settings || this.DefaultSettings_;
  30303. }
  30304. /**
  30305. * Copies a sample value to the result buffer.
  30306. *
  30307. * @param {number} index - An index into the sample value buffer.
  30308. * @return {TypedArray} The result buffer.
  30309. */
  30310. copySampleValue_( index ) {
  30311. // copies a sample value to the result buffer
  30312. const result = this.resultBuffer,
  30313. values = this.sampleValues,
  30314. stride = this.valueSize,
  30315. offset = index * stride;
  30316. for ( let i = 0; i !== stride; ++ i ) {
  30317. result[ i ] = values[ offset + i ];
  30318. }
  30319. return result;
  30320. }
  30321. /**
  30322. * Copies a sample value to the result buffer.
  30323. *
  30324. * @abstract
  30325. * @param {number} i1 - An index into the sample value buffer.
  30326. * @param {number} t0 - The previous interpolation factor.
  30327. * @param {number} t - The current interpolation factor.
  30328. * @param {number} t1 - The next interpolation factor.
  30329. * @return {TypedArray} The result buffer.
  30330. */
  30331. interpolate_( /* i1, t0, t, t1 */ ) {
  30332. throw new Error( 'call to abstract method' );
  30333. // implementations shall return this.resultBuffer
  30334. }
  30335. /**
  30336. * Optional method that is executed when the interval has changed.
  30337. *
  30338. * @param {number} i1 - An index into the sample value buffer.
  30339. * @param {number} t0 - The previous interpolation factor.
  30340. * @param {number} t - The current interpolation factor.
  30341. */
  30342. intervalChanged_( /* i1, t0, t1 */ ) {
  30343. // empty
  30344. }
  30345. }
  30346. /**
  30347. * Fast and simple cubic spline interpolant.
  30348. *
  30349. * It was derived from a Hermitian construction setting the first derivative
  30350. * at each sample position to the linear slope between neighboring positions
  30351. * over their parameter interval.
  30352. *
  30353. * @augments Interpolant
  30354. */
  30355. class CubicInterpolant extends Interpolant {
  30356. /**
  30357. * Constructs a new cubic interpolant.
  30358. *
  30359. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30360. * @param {TypedArray} sampleValues - The sample values.
  30361. * @param {number} sampleSize - The sample size
  30362. * @param {TypedArray} [resultBuffer] - The result buffer.
  30363. */
  30364. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30365. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30366. this._weightPrev = -0;
  30367. this._offsetPrev = -0;
  30368. this._weightNext = -0;
  30369. this._offsetNext = -0;
  30370. this.DefaultSettings_ = {
  30371. endingStart: ZeroCurvatureEnding,
  30372. endingEnd: ZeroCurvatureEnding
  30373. };
  30374. }
  30375. intervalChanged_( i1, t0, t1 ) {
  30376. const pp = this.parameterPositions;
  30377. let iPrev = i1 - 2,
  30378. iNext = i1 + 1,
  30379. tPrev = pp[ iPrev ],
  30380. tNext = pp[ iNext ];
  30381. if ( tPrev === undefined ) {
  30382. switch ( this.getSettings_().endingStart ) {
  30383. case ZeroSlopeEnding:
  30384. // f'(t0) = 0
  30385. iPrev = i1;
  30386. tPrev = 2 * t0 - t1;
  30387. break;
  30388. case WrapAroundEnding:
  30389. // use the other end of the curve
  30390. iPrev = pp.length - 2;
  30391. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30392. break;
  30393. default: // ZeroCurvatureEnding
  30394. // f''(t0) = 0 a.k.a. Natural Spline
  30395. iPrev = i1;
  30396. tPrev = t1;
  30397. }
  30398. }
  30399. if ( tNext === undefined ) {
  30400. switch ( this.getSettings_().endingEnd ) {
  30401. case ZeroSlopeEnding:
  30402. // f'(tN) = 0
  30403. iNext = i1;
  30404. tNext = 2 * t1 - t0;
  30405. break;
  30406. case WrapAroundEnding:
  30407. // use the other end of the curve
  30408. iNext = 1;
  30409. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30410. break;
  30411. default: // ZeroCurvatureEnding
  30412. // f''(tN) = 0, a.k.a. Natural Spline
  30413. iNext = i1 - 1;
  30414. tNext = t0;
  30415. }
  30416. }
  30417. const halfDt = ( t1 - t0 ) * 0.5,
  30418. stride = this.valueSize;
  30419. this._weightPrev = halfDt / ( t0 - tPrev );
  30420. this._weightNext = halfDt / ( tNext - t1 );
  30421. this._offsetPrev = iPrev * stride;
  30422. this._offsetNext = iNext * stride;
  30423. }
  30424. interpolate_( i1, t0, t, t1 ) {
  30425. const result = this.resultBuffer,
  30426. values = this.sampleValues,
  30427. stride = this.valueSize,
  30428. o1 = i1 * stride, o0 = o1 - stride,
  30429. oP = this._offsetPrev, oN = this._offsetNext,
  30430. wP = this._weightPrev, wN = this._weightNext,
  30431. p = ( t - t0 ) / ( t1 - t0 ),
  30432. pp = p * p,
  30433. ppp = pp * p;
  30434. // evaluate polynomials
  30435. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30436. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30437. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30438. const sN = wN * ppp - wN * pp;
  30439. // combine data linearly
  30440. for ( let i = 0; i !== stride; ++ i ) {
  30441. result[ i ] =
  30442. sP * values[ oP + i ] +
  30443. s0 * values[ o0 + i ] +
  30444. s1 * values[ o1 + i ] +
  30445. sN * values[ oN + i ];
  30446. }
  30447. return result;
  30448. }
  30449. }
  30450. /**
  30451. * A basic linear interpolant.
  30452. *
  30453. * @augments Interpolant
  30454. */
  30455. class LinearInterpolant extends Interpolant {
  30456. /**
  30457. * Constructs a new linear interpolant.
  30458. *
  30459. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30460. * @param {TypedArray} sampleValues - The sample values.
  30461. * @param {number} sampleSize - The sample size
  30462. * @param {TypedArray} [resultBuffer] - The result buffer.
  30463. */
  30464. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30465. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30466. }
  30467. interpolate_( i1, t0, t, t1 ) {
  30468. const result = this.resultBuffer,
  30469. values = this.sampleValues,
  30470. stride = this.valueSize,
  30471. offset1 = i1 * stride,
  30472. offset0 = offset1 - stride,
  30473. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30474. weight0 = 1 - weight1;
  30475. for ( let i = 0; i !== stride; ++ i ) {
  30476. result[ i ] =
  30477. values[ offset0 + i ] * weight0 +
  30478. values[ offset1 + i ] * weight1;
  30479. }
  30480. return result;
  30481. }
  30482. }
  30483. /**
  30484. * Interpolant that evaluates to the sample value at the position preceding
  30485. * the parameter.
  30486. *
  30487. * @augments Interpolant
  30488. */
  30489. class DiscreteInterpolant extends Interpolant {
  30490. /**
  30491. * Constructs a new discrete interpolant.
  30492. *
  30493. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30494. * @param {TypedArray} sampleValues - The sample values.
  30495. * @param {number} sampleSize - The sample size
  30496. * @param {TypedArray} [resultBuffer] - The result buffer.
  30497. */
  30498. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30499. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30500. }
  30501. interpolate_( i1 /*, t0, t, t1 */ ) {
  30502. return this.copySampleValue_( i1 - 1 );
  30503. }
  30504. }
  30505. /**
  30506. * A Bezier interpolant using cubic Bezier curves with 2D control points.
  30507. *
  30508. * This interpolant supports the COLLADA/Maya style of Bezier animation where
  30509. * each keyframe has explicit in/out tangent control points specified as
  30510. * 2D coordinates (time, value).
  30511. *
  30512. * The tangent data must be provided via the `settings` object:
  30513. * - `settings.inTangents`: Float32Array with [time, value] pairs per keyframe per component
  30514. * - `settings.outTangents`: Float32Array with [time, value] pairs per keyframe per component
  30515. *
  30516. * For a track with N keyframes and stride S:
  30517. * - Each tangent array has N * S * 2 values
  30518. * - Layout: [k0_c0_time, k0_c0_value, k0_c1_time, k0_c1_value, ..., k0_cS_time, k0_cS_value,
  30519. * k1_c0_time, k1_c0_value, ...]
  30520. *
  30521. * @augments Interpolant
  30522. */
  30523. class BezierInterpolant extends Interpolant {
  30524. interpolate_( i1, t0, t, t1 ) {
  30525. const result = this.resultBuffer;
  30526. const values = this.sampleValues;
  30527. const stride = this.valueSize;
  30528. const offset1 = i1 * stride;
  30529. const offset0 = offset1 - stride;
  30530. const settings = this.settings || this.DefaultSettings_;
  30531. const inTangents = settings.inTangents;
  30532. const outTangents = settings.outTangents;
  30533. // If no tangent data, fall back to linear interpolation
  30534. if ( ! inTangents || ! outTangents ) {
  30535. const weight1 = ( t - t0 ) / ( t1 - t0 );
  30536. const weight0 = 1 - weight1;
  30537. for ( let i = 0; i !== stride; ++ i ) {
  30538. result[ i ] = values[ offset0 + i ] * weight0 + values[ offset1 + i ] * weight1;
  30539. }
  30540. return result;
  30541. }
  30542. const tangentStride = stride * 2;
  30543. const i0 = i1 - 1;
  30544. for ( let i = 0; i !== stride; ++ i ) {
  30545. const v0 = values[ offset0 + i ];
  30546. const v1 = values[ offset1 + i ];
  30547. // outTangent of previous keyframe (C0)
  30548. const outTangentOffset = i0 * tangentStride + i * 2;
  30549. const c0x = outTangents[ outTangentOffset ];
  30550. const c0y = outTangents[ outTangentOffset + 1 ];
  30551. // inTangent of current keyframe (C1)
  30552. const inTangentOffset = i1 * tangentStride + i * 2;
  30553. const c1x = inTangents[ inTangentOffset ];
  30554. const c1y = inTangents[ inTangentOffset + 1 ];
  30555. // Solve for Bezier parameter s where Bx(s) = t using Newton-Raphson
  30556. let s = ( t - t0 ) / ( t1 - t0 );
  30557. let s2, s3, oneMinusS, oneMinusS2, oneMinusS3;
  30558. for ( let iter = 0; iter < 8; iter ++ ) {
  30559. s2 = s * s;
  30560. s3 = s2 * s;
  30561. oneMinusS = 1 - s;
  30562. oneMinusS2 = oneMinusS * oneMinusS;
  30563. oneMinusS3 = oneMinusS2 * oneMinusS;
  30564. // Bezier X(s) = (1-s)³·t0 + 3(1-s)²s·c0x + 3(1-s)s²·c1x + s³·t1
  30565. const bx = oneMinusS3 * t0 + 3 * oneMinusS2 * s * c0x + 3 * oneMinusS * s2 * c1x + s3 * t1;
  30566. const error = bx - t;
  30567. if ( Math.abs( error ) < 1e-10 ) break;
  30568. // Derivative dX/ds
  30569. const dbx = 3 * oneMinusS2 * ( c0x - t0 ) + 6 * oneMinusS * s * ( c1x - c0x ) + 3 * s2 * ( t1 - c1x );
  30570. if ( Math.abs( dbx ) < 1e-10 ) break;
  30571. s = s - error / dbx;
  30572. s = Math.max( 0, Math.min( 1, s ) );
  30573. }
  30574. // Evaluate Bezier Y(s)
  30575. result[ i ] = oneMinusS3 * v0 + 3 * oneMinusS2 * s * c0y + 3 * oneMinusS * s2 * c1y + s3 * v1;
  30576. }
  30577. return result;
  30578. }
  30579. }
  30580. /**
  30581. * Represents a timed sequence of keyframes, which are composed of lists of
  30582. * times and related values, and which are used to animate a specific property
  30583. * of an object.
  30584. */
  30585. class KeyframeTrack {
  30586. /**
  30587. * Constructs a new keyframe track.
  30588. *
  30589. * @param {string} name - The keyframe track's name.
  30590. * @param {Array<number>} times - A list of keyframe times.
  30591. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30592. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} [interpolation] - The interpolation type.
  30593. */
  30594. constructor( name, times, values, interpolation ) {
  30595. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30596. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30597. /**
  30598. * The track's name can refer to morph targets or bones or
  30599. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30600. * for the forms of strings that can be parsed for property binding.
  30601. *
  30602. * @type {string}
  30603. */
  30604. this.name = name;
  30605. /**
  30606. * The keyframe times.
  30607. *
  30608. * @type {Float32Array}
  30609. */
  30610. this.times = convertArray( times, this.TimeBufferType );
  30611. /**
  30612. * The keyframe values.
  30613. *
  30614. * @type {Float32Array}
  30615. */
  30616. this.values = convertArray( values, this.ValueBufferType );
  30617. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30618. }
  30619. /**
  30620. * Converts the keyframe track to JSON.
  30621. *
  30622. * @static
  30623. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30624. * @return {Object} The serialized keyframe track as JSON.
  30625. */
  30626. static toJSON( track ) {
  30627. const trackType = track.constructor;
  30628. let json;
  30629. // derived classes can define a static toJSON method
  30630. if ( trackType.toJSON !== this.toJSON ) {
  30631. json = trackType.toJSON( track );
  30632. } else {
  30633. // by default, we assume the data can be serialized as-is
  30634. json = {
  30635. 'name': track.name,
  30636. 'times': convertArray( track.times, Array ),
  30637. 'values': convertArray( track.values, Array )
  30638. };
  30639. const interpolation = track.getInterpolation();
  30640. if ( interpolation !== track.DefaultInterpolation ) {
  30641. json.interpolation = interpolation;
  30642. }
  30643. }
  30644. json.type = track.ValueTypeName; // mandatory
  30645. return json;
  30646. }
  30647. /**
  30648. * Factory method for creating a new discrete interpolant.
  30649. *
  30650. * @static
  30651. * @param {TypedArray} [result] - The result buffer.
  30652. * @return {DiscreteInterpolant} The new interpolant.
  30653. */
  30654. InterpolantFactoryMethodDiscrete( result ) {
  30655. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30656. }
  30657. /**
  30658. * Factory method for creating a new linear interpolant.
  30659. *
  30660. * @static
  30661. * @param {TypedArray} [result] - The result buffer.
  30662. * @return {LinearInterpolant} The new interpolant.
  30663. */
  30664. InterpolantFactoryMethodLinear( result ) {
  30665. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30666. }
  30667. /**
  30668. * Factory method for creating a new smooth interpolant.
  30669. *
  30670. * @static
  30671. * @param {TypedArray} [result] - The result buffer.
  30672. * @return {CubicInterpolant} The new interpolant.
  30673. */
  30674. InterpolantFactoryMethodSmooth( result ) {
  30675. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30676. }
  30677. /**
  30678. * Factory method for creating a new Bezier interpolant.
  30679. *
  30680. * The Bezier interpolant requires tangent data to be set via the `settings` property
  30681. * on the track before creating the interpolant. The settings should contain:
  30682. * - `inTangents`: Float32Array with [time, value] pairs per keyframe per component
  30683. * - `outTangents`: Float32Array with [time, value] pairs per keyframe per component
  30684. *
  30685. * @static
  30686. * @param {TypedArray} [result] - The result buffer.
  30687. * @return {BezierInterpolant} The new interpolant.
  30688. */
  30689. InterpolantFactoryMethodBezier( result ) {
  30690. const interpolant = new BezierInterpolant( this.times, this.values, this.getValueSize(), result );
  30691. // Pass tangent data from track settings to interpolant
  30692. if ( this.settings ) {
  30693. interpolant.settings = this.settings;
  30694. }
  30695. return interpolant;
  30696. }
  30697. /**
  30698. * Defines the interpolation factor method for this keyframe track.
  30699. *
  30700. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} interpolation - The interpolation type.
  30701. * @return {KeyframeTrack} A reference to this keyframe track.
  30702. */
  30703. setInterpolation( interpolation ) {
  30704. let factoryMethod;
  30705. switch ( interpolation ) {
  30706. case InterpolateDiscrete:
  30707. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30708. break;
  30709. case InterpolateLinear:
  30710. factoryMethod = this.InterpolantFactoryMethodLinear;
  30711. break;
  30712. case InterpolateSmooth:
  30713. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30714. break;
  30715. case InterpolateBezier:
  30716. factoryMethod = this.InterpolantFactoryMethodBezier;
  30717. break;
  30718. }
  30719. if ( factoryMethod === undefined ) {
  30720. const message = 'unsupported interpolation for ' +
  30721. this.ValueTypeName + ' keyframe track named ' + this.name;
  30722. if ( this.createInterpolant === undefined ) {
  30723. // fall back to default, unless the default itself is messed up
  30724. if ( interpolation !== this.DefaultInterpolation ) {
  30725. this.setInterpolation( this.DefaultInterpolation );
  30726. } else {
  30727. throw new Error( message ); // fatal, in this case
  30728. }
  30729. }
  30730. warn( 'KeyframeTrack:', message );
  30731. return this;
  30732. }
  30733. this.createInterpolant = factoryMethod;
  30734. return this;
  30735. }
  30736. /**
  30737. * Returns the current interpolation type.
  30738. *
  30739. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} The interpolation type.
  30740. */
  30741. getInterpolation() {
  30742. switch ( this.createInterpolant ) {
  30743. case this.InterpolantFactoryMethodDiscrete:
  30744. return InterpolateDiscrete;
  30745. case this.InterpolantFactoryMethodLinear:
  30746. return InterpolateLinear;
  30747. case this.InterpolantFactoryMethodSmooth:
  30748. return InterpolateSmooth;
  30749. case this.InterpolantFactoryMethodBezier:
  30750. return InterpolateBezier;
  30751. }
  30752. }
  30753. /**
  30754. * Returns the value size.
  30755. *
  30756. * @return {number} The value size.
  30757. */
  30758. getValueSize() {
  30759. return this.values.length / this.times.length;
  30760. }
  30761. /**
  30762. * Moves all keyframes either forward or backward in time.
  30763. *
  30764. * @param {number} timeOffset - The offset to move the time values.
  30765. * @return {KeyframeTrack} A reference to this keyframe track.
  30766. */
  30767. shift( timeOffset ) {
  30768. if ( timeOffset !== 0.0 ) {
  30769. const times = this.times;
  30770. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30771. times[ i ] += timeOffset;
  30772. }
  30773. }
  30774. return this;
  30775. }
  30776. /**
  30777. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30778. *
  30779. * @param {number} timeScale - The time scale.
  30780. * @return {KeyframeTrack} A reference to this keyframe track.
  30781. */
  30782. scale( timeScale ) {
  30783. if ( timeScale !== 1.0 ) {
  30784. const times = this.times;
  30785. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30786. times[ i ] *= timeScale;
  30787. }
  30788. }
  30789. return this;
  30790. }
  30791. /**
  30792. * Removes keyframes before and after animation without changing any values within the defined time range.
  30793. *
  30794. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30795. * keys this will change their values
  30796. *
  30797. * @param {number} startTime - The start time.
  30798. * @param {number} endTime - The end time.
  30799. * @return {KeyframeTrack} A reference to this keyframe track.
  30800. */
  30801. trim( startTime, endTime ) {
  30802. const times = this.times,
  30803. nKeys = times.length;
  30804. let from = 0,
  30805. to = nKeys - 1;
  30806. while ( from !== nKeys && times[ from ] < startTime ) {
  30807. ++ from;
  30808. }
  30809. while ( to !== -1 && times[ to ] > endTime ) {
  30810. -- to;
  30811. }
  30812. ++ to; // inclusive -> exclusive bound
  30813. if ( from !== 0 || to !== nKeys ) {
  30814. // empty tracks are forbidden, so keep at least one keyframe
  30815. if ( from >= to ) {
  30816. to = Math.max( to, 1 );
  30817. from = to - 1;
  30818. }
  30819. const stride = this.getValueSize();
  30820. this.times = times.slice( from, to );
  30821. this.values = this.values.slice( from * stride, to * stride );
  30822. }
  30823. return this;
  30824. }
  30825. /**
  30826. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30827. * are valid.
  30828. *
  30829. * @return {boolean} Whether the keyframes are valid or not.
  30830. */
  30831. validate() {
  30832. let valid = true;
  30833. const valueSize = this.getValueSize();
  30834. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30835. error( 'KeyframeTrack: Invalid value size in track.', this );
  30836. valid = false;
  30837. }
  30838. const times = this.times,
  30839. values = this.values,
  30840. nKeys = times.length;
  30841. if ( nKeys === 0 ) {
  30842. error( 'KeyframeTrack: Track is empty.', this );
  30843. valid = false;
  30844. }
  30845. let prevTime = null;
  30846. for ( let i = 0; i !== nKeys; i ++ ) {
  30847. const currTime = times[ i ];
  30848. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30849. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30850. valid = false;
  30851. break;
  30852. }
  30853. if ( prevTime !== null && prevTime > currTime ) {
  30854. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30855. valid = false;
  30856. break;
  30857. }
  30858. prevTime = currTime;
  30859. }
  30860. if ( values !== undefined ) {
  30861. if ( isTypedArray( values ) ) {
  30862. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30863. const value = values[ i ];
  30864. if ( isNaN( value ) ) {
  30865. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  30866. valid = false;
  30867. break;
  30868. }
  30869. }
  30870. }
  30871. }
  30872. return valid;
  30873. }
  30874. /**
  30875. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30876. * common in morph target sequences).
  30877. *
  30878. * @return {KeyframeTrack} A reference to this keyframe track.
  30879. */
  30880. optimize() {
  30881. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30882. // times or values may be shared with other tracks, so overwriting is unsafe
  30883. const times = this.times.slice(),
  30884. values = this.values.slice(),
  30885. stride = this.getValueSize(),
  30886. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30887. lastIndex = times.length - 1;
  30888. let writeIndex = 1;
  30889. for ( let i = 1; i < lastIndex; ++ i ) {
  30890. let keep = false;
  30891. const time = times[ i ];
  30892. const timeNext = times[ i + 1 ];
  30893. // remove adjacent keyframes scheduled at the same time
  30894. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30895. if ( ! smoothInterpolation ) {
  30896. // remove unnecessary keyframes same as their neighbors
  30897. const offset = i * stride,
  30898. offsetP = offset - stride,
  30899. offsetN = offset + stride;
  30900. for ( let j = 0; j !== stride; ++ j ) {
  30901. const value = values[ offset + j ];
  30902. if ( value !== values[ offsetP + j ] ||
  30903. value !== values[ offsetN + j ] ) {
  30904. keep = true;
  30905. break;
  30906. }
  30907. }
  30908. } else {
  30909. keep = true;
  30910. }
  30911. }
  30912. // in-place compaction
  30913. if ( keep ) {
  30914. if ( i !== writeIndex ) {
  30915. times[ writeIndex ] = times[ i ];
  30916. const readOffset = i * stride,
  30917. writeOffset = writeIndex * stride;
  30918. for ( let j = 0; j !== stride; ++ j ) {
  30919. values[ writeOffset + j ] = values[ readOffset + j ];
  30920. }
  30921. }
  30922. ++ writeIndex;
  30923. }
  30924. }
  30925. // flush last keyframe (compaction looks ahead)
  30926. if ( lastIndex > 0 ) {
  30927. times[ writeIndex ] = times[ lastIndex ];
  30928. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  30929. values[ writeOffset + j ] = values[ readOffset + j ];
  30930. }
  30931. ++ writeIndex;
  30932. }
  30933. if ( writeIndex !== times.length ) {
  30934. this.times = times.slice( 0, writeIndex );
  30935. this.values = values.slice( 0, writeIndex * stride );
  30936. } else {
  30937. this.times = times;
  30938. this.values = values;
  30939. }
  30940. return this;
  30941. }
  30942. /**
  30943. * Returns a new keyframe track with copied values from this instance.
  30944. *
  30945. * @return {KeyframeTrack} A clone of this instance.
  30946. */
  30947. clone() {
  30948. const times = this.times.slice();
  30949. const values = this.values.slice();
  30950. const TypedKeyframeTrack = this.constructor;
  30951. const track = new TypedKeyframeTrack( this.name, times, values );
  30952. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  30953. track.createInterpolant = this.createInterpolant;
  30954. return track;
  30955. }
  30956. }
  30957. /**
  30958. * The value type name.
  30959. *
  30960. * @type {string}
  30961. * @default ''
  30962. */
  30963. KeyframeTrack.prototype.ValueTypeName = '';
  30964. /**
  30965. * The time buffer type of this keyframe track.
  30966. *
  30967. * @type {TypedArray|Array}
  30968. * @default Float32Array.constructor
  30969. */
  30970. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  30971. /**
  30972. * The value buffer type of this keyframe track.
  30973. *
  30974. * @type {TypedArray|Array}
  30975. * @default Float32Array.constructor
  30976. */
  30977. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  30978. /**
  30979. * The default interpolation type of this keyframe track.
  30980. *
  30981. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)}
  30982. * @default InterpolateLinear
  30983. */
  30984. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  30985. /**
  30986. * A track for boolean keyframe values.
  30987. *
  30988. * @augments KeyframeTrack
  30989. */
  30990. class BooleanKeyframeTrack extends KeyframeTrack {
  30991. /**
  30992. * Constructs a new boolean keyframe track.
  30993. *
  30994. * This keyframe track type has no `interpolation` parameter because the
  30995. * interpolation is always discrete.
  30996. *
  30997. * @param {string} name - The keyframe track's name.
  30998. * @param {Array<number>} times - A list of keyframe times.
  30999. * @param {Array<boolean>} values - A list of keyframe values.
  31000. */
  31001. constructor( name, times, values ) {
  31002. super( name, times, values );
  31003. }
  31004. }
  31005. /**
  31006. * The value type name.
  31007. *
  31008. * @type {string}
  31009. * @default 'bool'
  31010. */
  31011. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31012. /**
  31013. * The value buffer type of this keyframe track.
  31014. *
  31015. * @type {TypedArray|Array}
  31016. * @default Array.constructor
  31017. */
  31018. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31019. /**
  31020. * The default interpolation type of this keyframe track.
  31021. *
  31022. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31023. * @default InterpolateDiscrete
  31024. */
  31025. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31026. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31027. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31028. /**
  31029. * A track for color keyframe values.
  31030. *
  31031. * @augments KeyframeTrack
  31032. */
  31033. class ColorKeyframeTrack extends KeyframeTrack {
  31034. /**
  31035. * Constructs a new color keyframe track.
  31036. *
  31037. * @param {string} name - The keyframe track's name.
  31038. * @param {Array<number>} times - A list of keyframe times.
  31039. * @param {Array<number>} values - A list of keyframe values.
  31040. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31041. */
  31042. constructor( name, times, values, interpolation ) {
  31043. super( name, times, values, interpolation );
  31044. }
  31045. }
  31046. /**
  31047. * The value type name.
  31048. *
  31049. * @type {string}
  31050. * @default 'color'
  31051. */
  31052. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31053. /**
  31054. * A track for numeric keyframe values.
  31055. *
  31056. * @augments KeyframeTrack
  31057. */
  31058. class NumberKeyframeTrack extends KeyframeTrack {
  31059. /**
  31060. * Constructs a new number keyframe track.
  31061. *
  31062. * @param {string} name - The keyframe track's name.
  31063. * @param {Array<number>} times - A list of keyframe times.
  31064. * @param {Array<number>} values - A list of keyframe values.
  31065. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31066. */
  31067. constructor( name, times, values, interpolation ) {
  31068. super( name, times, values, interpolation );
  31069. }
  31070. }
  31071. /**
  31072. * The value type name.
  31073. *
  31074. * @type {string}
  31075. * @default 'number'
  31076. */
  31077. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31078. /**
  31079. * Spherical linear unit quaternion interpolant.
  31080. *
  31081. * @augments Interpolant
  31082. */
  31083. class QuaternionLinearInterpolant extends Interpolant {
  31084. /**
  31085. * Constructs a new SLERP interpolant.
  31086. *
  31087. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31088. * @param {TypedArray} sampleValues - The sample values.
  31089. * @param {number} sampleSize - The sample size
  31090. * @param {TypedArray} [resultBuffer] - The result buffer.
  31091. */
  31092. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31093. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31094. }
  31095. interpolate_( i1, t0, t, t1 ) {
  31096. const result = this.resultBuffer,
  31097. values = this.sampleValues,
  31098. stride = this.valueSize,
  31099. alpha = ( t - t0 ) / ( t1 - t0 );
  31100. let offset = i1 * stride;
  31101. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31102. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31103. }
  31104. return result;
  31105. }
  31106. }
  31107. /**
  31108. * A track for Quaternion keyframe values.
  31109. *
  31110. * @augments KeyframeTrack
  31111. */
  31112. class QuaternionKeyframeTrack extends KeyframeTrack {
  31113. /**
  31114. * Constructs a new Quaternion keyframe track.
  31115. *
  31116. * @param {string} name - The keyframe track's name.
  31117. * @param {Array<number>} times - A list of keyframe times.
  31118. * @param {Array<number>} values - A list of keyframe values.
  31119. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31120. */
  31121. constructor( name, times, values, interpolation ) {
  31122. super( name, times, values, interpolation );
  31123. }
  31124. /**
  31125. * Overwritten so the method returns Quaternion based interpolant.
  31126. *
  31127. * @static
  31128. * @param {TypedArray} [result] - The result buffer.
  31129. * @return {QuaternionLinearInterpolant} The new interpolant.
  31130. */
  31131. InterpolantFactoryMethodLinear( result ) {
  31132. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31133. }
  31134. }
  31135. /**
  31136. * The value type name.
  31137. *
  31138. * @type {string}
  31139. * @default 'quaternion'
  31140. */
  31141. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31142. // ValueBufferType is inherited
  31143. // DefaultInterpolation is inherited;
  31144. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31145. /**
  31146. * A track for string keyframe values.
  31147. *
  31148. * @augments KeyframeTrack
  31149. */
  31150. class StringKeyframeTrack extends KeyframeTrack {
  31151. /**
  31152. * Constructs a new string keyframe track.
  31153. *
  31154. * This keyframe track type has no `interpolation` parameter because the
  31155. * interpolation is always discrete.
  31156. *
  31157. * @param {string} name - The keyframe track's name.
  31158. * @param {Array<number>} times - A list of keyframe times.
  31159. * @param {Array<string>} values - A list of keyframe values.
  31160. */
  31161. constructor( name, times, values ) {
  31162. super( name, times, values );
  31163. }
  31164. }
  31165. /**
  31166. * The value type name.
  31167. *
  31168. * @type {string}
  31169. * @default 'string'
  31170. */
  31171. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31172. /**
  31173. * The value buffer type of this keyframe track.
  31174. *
  31175. * @type {TypedArray|Array}
  31176. * @default Array.constructor
  31177. */
  31178. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31179. /**
  31180. * The default interpolation type of this keyframe track.
  31181. *
  31182. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31183. * @default InterpolateDiscrete
  31184. */
  31185. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31186. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31187. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31188. /**
  31189. * A track for vector keyframe values.
  31190. *
  31191. * @augments KeyframeTrack
  31192. */
  31193. class VectorKeyframeTrack extends KeyframeTrack {
  31194. /**
  31195. * Constructs a new vector keyframe track.
  31196. *
  31197. * @param {string} name - The keyframe track's name.
  31198. * @param {Array<number>} times - A list of keyframe times.
  31199. * @param {Array<number>} values - A list of keyframe values.
  31200. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31201. */
  31202. constructor( name, times, values, interpolation ) {
  31203. super( name, times, values, interpolation );
  31204. }
  31205. }
  31206. /**
  31207. * The value type name.
  31208. *
  31209. * @type {string}
  31210. * @default 'vector'
  31211. */
  31212. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31213. /**
  31214. * A reusable set of keyframe tracks which represent an animation.
  31215. */
  31216. class AnimationClip {
  31217. /**
  31218. * Constructs a new animation clip.
  31219. *
  31220. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31221. * use the static interface of this class for creating clips. In most cases though, animation clips
  31222. * will automatically be created by loaders when importing animated 3D assets.
  31223. *
  31224. * @param {string} [name=''] - The clip's name.
  31225. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31226. * the duration will be calculated from the passed keyframes.
  31227. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31228. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31229. * is blended/combined when two or more animations are simultaneously played.
  31230. */
  31231. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31232. /**
  31233. * The clip's name.
  31234. *
  31235. * @type {string}
  31236. */
  31237. this.name = name;
  31238. /**
  31239. * An array of keyframe tracks.
  31240. *
  31241. * @type {Array<KeyframeTrack>}
  31242. */
  31243. this.tracks = tracks;
  31244. /**
  31245. * The clip's duration in seconds.
  31246. *
  31247. * @type {number}
  31248. */
  31249. this.duration = duration;
  31250. /**
  31251. * Defines how the animation is blended/combined when two or more animations
  31252. * are simultaneously played.
  31253. *
  31254. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31255. */
  31256. this.blendMode = blendMode;
  31257. /**
  31258. * The UUID of the animation clip.
  31259. *
  31260. * @type {string}
  31261. * @readonly
  31262. */
  31263. this.uuid = generateUUID();
  31264. /**
  31265. * An object that can be used to store custom data about the animation clip.
  31266. * It should not hold references to functions as these will not be cloned.
  31267. *
  31268. * @type {Object}
  31269. */
  31270. this.userData = {};
  31271. // this means it should figure out its duration by scanning the tracks
  31272. if ( this.duration < 0 ) {
  31273. this.resetDuration();
  31274. }
  31275. }
  31276. /**
  31277. * Factory method for creating an animation clip from the given JSON.
  31278. *
  31279. * @static
  31280. * @param {Object} json - The serialized animation clip.
  31281. * @return {AnimationClip} The new animation clip.
  31282. */
  31283. static parse( json ) {
  31284. const tracks = [],
  31285. jsonTracks = json.tracks,
  31286. frameTime = 1.0 / ( json.fps || 1.0 );
  31287. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31288. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31289. }
  31290. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31291. clip.uuid = json.uuid;
  31292. clip.userData = JSON.parse( json.userData || '{}' );
  31293. return clip;
  31294. }
  31295. /**
  31296. * Serializes the given animation clip into JSON.
  31297. *
  31298. * @static
  31299. * @param {AnimationClip} clip - The animation clip to serialize.
  31300. * @return {Object} The JSON object.
  31301. */
  31302. static toJSON( clip ) {
  31303. const tracks = [],
  31304. clipTracks = clip.tracks;
  31305. const json = {
  31306. 'name': clip.name,
  31307. 'duration': clip.duration,
  31308. 'tracks': tracks,
  31309. 'uuid': clip.uuid,
  31310. 'blendMode': clip.blendMode,
  31311. 'userData': JSON.stringify( clip.userData ),
  31312. };
  31313. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31314. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31315. }
  31316. return json;
  31317. }
  31318. /**
  31319. * Returns a new animation clip from the passed morph targets array of a
  31320. * geometry, taking a name and the number of frames per second.
  31321. *
  31322. * Note: The fps parameter is required, but the animation speed can be
  31323. * overridden via {@link AnimationAction#setDuration}.
  31324. *
  31325. * @static
  31326. * @param {string} name - The name of the animation clip.
  31327. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31328. * @param {number} fps - The Frames-Per-Second value.
  31329. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31330. * @return {AnimationClip} The new animation clip.
  31331. */
  31332. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31333. const numMorphTargets = morphTargetSequence.length;
  31334. const tracks = [];
  31335. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31336. let times = [];
  31337. let values = [];
  31338. times.push(
  31339. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31340. i,
  31341. ( i + 1 ) % numMorphTargets );
  31342. values.push( 0, 1, 0 );
  31343. const order = getKeyframeOrder( times );
  31344. times = sortedArray( times, 1, order );
  31345. values = sortedArray( values, 1, order );
  31346. // if there is a key at the first frame, duplicate it as the
  31347. // last frame as well for perfect loop.
  31348. if ( ! noLoop && times[ 0 ] === 0 ) {
  31349. times.push( numMorphTargets );
  31350. values.push( values[ 0 ] );
  31351. }
  31352. tracks.push(
  31353. new NumberKeyframeTrack(
  31354. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31355. times, values
  31356. ).scale( 1.0 / fps ) );
  31357. }
  31358. return new this( name, -1, tracks );
  31359. }
  31360. /**
  31361. * Searches for an animation clip by name, taking as its first parameter
  31362. * either an array of clips, or a mesh or geometry that contains an
  31363. * array named "animations" property.
  31364. *
  31365. * @static
  31366. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31367. * @param {string} name - The name to search for.
  31368. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31369. */
  31370. static findByName( objectOrClipArray, name ) {
  31371. let clipArray = objectOrClipArray;
  31372. if ( ! Array.isArray( objectOrClipArray ) ) {
  31373. const o = objectOrClipArray;
  31374. clipArray = o.geometry && o.geometry.animations || o.animations;
  31375. }
  31376. for ( let i = 0; i < clipArray.length; i ++ ) {
  31377. if ( clipArray[ i ].name === name ) {
  31378. return clipArray[ i ];
  31379. }
  31380. }
  31381. return null;
  31382. }
  31383. /**
  31384. * Returns an array of new AnimationClips created from the morph target
  31385. * sequences of a geometry, trying to sort morph target names into
  31386. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31387. *
  31388. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31389. *
  31390. * @static
  31391. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31392. * @param {number} fps - The Frames-Per-Second value.
  31393. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31394. * @return {Array<AnimationClip>} An array of new animation clips.
  31395. */
  31396. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31397. const animationToMorphTargets = {};
  31398. // tested with https://regex101.com/ on trick sequences
  31399. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31400. const pattern = /^([\w-]*?)([\d]+)$/;
  31401. // sort morph target names into animation groups based
  31402. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31403. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31404. const morphTarget = morphTargets[ i ];
  31405. const parts = morphTarget.name.match( pattern );
  31406. if ( parts && parts.length > 1 ) {
  31407. const name = parts[ 1 ];
  31408. let animationMorphTargets = animationToMorphTargets[ name ];
  31409. if ( ! animationMorphTargets ) {
  31410. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31411. }
  31412. animationMorphTargets.push( morphTarget );
  31413. }
  31414. }
  31415. const clips = [];
  31416. for ( const name in animationToMorphTargets ) {
  31417. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31418. }
  31419. return clips;
  31420. }
  31421. /**
  31422. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31423. *
  31424. * @static
  31425. * @deprecated since r175.
  31426. * @param {Object} animation - A serialized animation clip as JSON.
  31427. * @param {Array<Bone>} bones - An array of bones.
  31428. * @return {?AnimationClip} The new animation clip.
  31429. */
  31430. static parseAnimation( animation, bones ) {
  31431. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31432. if ( ! animation ) {
  31433. error( 'AnimationClip: No animation in JSONLoader data.' );
  31434. return null;
  31435. }
  31436. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31437. // only return track if there are actually keys.
  31438. if ( animationKeys.length !== 0 ) {
  31439. const times = [];
  31440. const values = [];
  31441. flattenJSON( animationKeys, times, values, propertyName );
  31442. // empty keys are filtered out, so check again
  31443. if ( times.length !== 0 ) {
  31444. destTracks.push( new trackType( trackName, times, values ) );
  31445. }
  31446. }
  31447. };
  31448. const tracks = [];
  31449. const clipName = animation.name || 'default';
  31450. const fps = animation.fps || 30;
  31451. const blendMode = animation.blendMode;
  31452. // automatic length determination in AnimationClip.
  31453. let duration = animation.length || -1;
  31454. const hierarchyTracks = animation.hierarchy || [];
  31455. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31456. const animationKeys = hierarchyTracks[ h ].keys;
  31457. // skip empty tracks
  31458. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31459. // process morph targets
  31460. if ( animationKeys[ 0 ].morphTargets ) {
  31461. // figure out all morph targets used in this track
  31462. const morphTargetNames = {};
  31463. let k;
  31464. for ( k = 0; k < animationKeys.length; k ++ ) {
  31465. if ( animationKeys[ k ].morphTargets ) {
  31466. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31467. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31468. }
  31469. }
  31470. }
  31471. // create a track for each morph target with all zero
  31472. // morphTargetInfluences except for the keys in which
  31473. // the morphTarget is named.
  31474. for ( const morphTargetName in morphTargetNames ) {
  31475. const times = [];
  31476. const values = [];
  31477. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31478. const animationKey = animationKeys[ k ];
  31479. times.push( animationKey.time );
  31480. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31481. }
  31482. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31483. }
  31484. duration = morphTargetNames.length * fps;
  31485. } else {
  31486. // ...assume skeletal animation
  31487. const boneName = '.bones[' + bones[ h ].name + ']';
  31488. addNonemptyTrack(
  31489. VectorKeyframeTrack, boneName + '.position',
  31490. animationKeys, 'pos', tracks );
  31491. addNonemptyTrack(
  31492. QuaternionKeyframeTrack, boneName + '.quaternion',
  31493. animationKeys, 'rot', tracks );
  31494. addNonemptyTrack(
  31495. VectorKeyframeTrack, boneName + '.scale',
  31496. animationKeys, 'scl', tracks );
  31497. }
  31498. }
  31499. if ( tracks.length === 0 ) {
  31500. return null;
  31501. }
  31502. const clip = new this( clipName, duration, tracks, blendMode );
  31503. return clip;
  31504. }
  31505. /**
  31506. * Sets the duration of this clip to the duration of its longest keyframe track.
  31507. *
  31508. * @return {AnimationClip} A reference to this animation clip.
  31509. */
  31510. resetDuration() {
  31511. const tracks = this.tracks;
  31512. let duration = 0;
  31513. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31514. const track = this.tracks[ i ];
  31515. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31516. }
  31517. this.duration = duration;
  31518. return this;
  31519. }
  31520. /**
  31521. * Trims all tracks to the clip's duration.
  31522. *
  31523. * @return {AnimationClip} A reference to this animation clip.
  31524. */
  31525. trim() {
  31526. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31527. this.tracks[ i ].trim( 0, this.duration );
  31528. }
  31529. return this;
  31530. }
  31531. /**
  31532. * Performs minimal validation on each track in the clip. Returns `true` if all
  31533. * tracks are valid.
  31534. *
  31535. * @return {boolean} Whether the clip's keyframes are valid or not.
  31536. */
  31537. validate() {
  31538. let valid = true;
  31539. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31540. valid = valid && this.tracks[ i ].validate();
  31541. }
  31542. return valid;
  31543. }
  31544. /**
  31545. * Optimizes each track by removing equivalent sequential keys (which are
  31546. * common in morph target sequences).
  31547. *
  31548. * @return {AnimationClip} A reference to this animation clip.
  31549. */
  31550. optimize() {
  31551. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31552. this.tracks[ i ].optimize();
  31553. }
  31554. return this;
  31555. }
  31556. /**
  31557. * Returns a new animation clip with copied values from this instance.
  31558. *
  31559. * @return {AnimationClip} A clone of this instance.
  31560. */
  31561. clone() {
  31562. const tracks = [];
  31563. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31564. tracks.push( this.tracks[ i ].clone() );
  31565. }
  31566. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31567. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31568. return clip;
  31569. }
  31570. /**
  31571. * Serializes this animation clip into JSON.
  31572. *
  31573. * @return {Object} The JSON object.
  31574. */
  31575. toJSON() {
  31576. return this.constructor.toJSON( this );
  31577. }
  31578. }
  31579. function getTrackTypeForValueTypeName( typeName ) {
  31580. switch ( typeName.toLowerCase() ) {
  31581. case 'scalar':
  31582. case 'double':
  31583. case 'float':
  31584. case 'number':
  31585. case 'integer':
  31586. return NumberKeyframeTrack;
  31587. case 'vector':
  31588. case 'vector2':
  31589. case 'vector3':
  31590. case 'vector4':
  31591. return VectorKeyframeTrack;
  31592. case 'color':
  31593. return ColorKeyframeTrack;
  31594. case 'quaternion':
  31595. return QuaternionKeyframeTrack;
  31596. case 'bool':
  31597. case 'boolean':
  31598. return BooleanKeyframeTrack;
  31599. case 'string':
  31600. return StringKeyframeTrack;
  31601. }
  31602. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31603. }
  31604. function parseKeyframeTrack( json ) {
  31605. if ( json.type === undefined ) {
  31606. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31607. }
  31608. const trackType = getTrackTypeForValueTypeName( json.type );
  31609. if ( json.times === undefined ) {
  31610. const times = [], values = [];
  31611. flattenJSON( json.keys, times, values, 'value' );
  31612. json.times = times;
  31613. json.values = values;
  31614. }
  31615. // derived classes can define a static parse method
  31616. if ( trackType.parse !== undefined ) {
  31617. return trackType.parse( json );
  31618. } else {
  31619. // by default, we assume a constructor compatible with the base
  31620. return new trackType( json.name, json.times, json.values, json.interpolation );
  31621. }
  31622. }
  31623. /**
  31624. * @class
  31625. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31626. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31627. * @hideconstructor
  31628. */
  31629. const Cache = {
  31630. /**
  31631. * Whether caching is enabled or not.
  31632. *
  31633. * @static
  31634. * @type {boolean}
  31635. * @default false
  31636. */
  31637. enabled: false,
  31638. /**
  31639. * A dictionary that holds cached files.
  31640. *
  31641. * @static
  31642. * @type {Object<string,Object>}
  31643. */
  31644. files: {},
  31645. /**
  31646. * Adds a cache entry with a key to reference the file. If this key already
  31647. * holds a file, it is overwritten.
  31648. *
  31649. * @static
  31650. * @param {string} key - The key to reference the cached file.
  31651. * @param {Object} file - The file to be cached.
  31652. */
  31653. add: function ( key, file ) {
  31654. if ( this.enabled === false ) return;
  31655. // log( 'Cache', 'Adding key:', key );
  31656. this.files[ key ] = file;
  31657. },
  31658. /**
  31659. * Gets the cached value for the given key.
  31660. *
  31661. * @static
  31662. * @param {string} key - The key to reference the cached file.
  31663. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31664. */
  31665. get: function ( key ) {
  31666. if ( this.enabled === false ) return;
  31667. // log( 'Cache', 'Checking key:', key );
  31668. return this.files[ key ];
  31669. },
  31670. /**
  31671. * Removes the cached file associated with the given key.
  31672. *
  31673. * @static
  31674. * @param {string} key - The key to reference the cached file.
  31675. */
  31676. remove: function ( key ) {
  31677. delete this.files[ key ];
  31678. },
  31679. /**
  31680. * Remove all values from the cache.
  31681. *
  31682. * @static
  31683. */
  31684. clear: function () {
  31685. this.files = {};
  31686. }
  31687. };
  31688. /**
  31689. * Handles and keeps track of loaded and pending data. A default global
  31690. * instance of this class is created and used by loaders if not supplied
  31691. * manually.
  31692. *
  31693. * In general that should be sufficient, however there are times when it can
  31694. * be useful to have separate loaders - for example if you want to show
  31695. * separate loading bars for objects and textures.
  31696. *
  31697. * ```js
  31698. * const manager = new THREE.LoadingManager();
  31699. * manager.onLoad = () => console.log( 'Loading complete!' );
  31700. *
  31701. * const loader1 = new OBJLoader( manager );
  31702. * const loader2 = new ColladaLoader( manager );
  31703. * ```
  31704. */
  31705. class LoadingManager {
  31706. /**
  31707. * Constructs a new loading manager.
  31708. *
  31709. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31710. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31711. * @param {Function} [onError] - Executes when an error occurs.
  31712. */
  31713. constructor( onLoad, onProgress, onError ) {
  31714. const scope = this;
  31715. let isLoading = false;
  31716. let itemsLoaded = 0;
  31717. let itemsTotal = 0;
  31718. let urlModifier = undefined;
  31719. const handlers = [];
  31720. // Refer to #5689 for the reason why we don't set .onStart
  31721. // in the constructor
  31722. /**
  31723. * Executes when an item starts loading.
  31724. *
  31725. * @type {Function|undefined}
  31726. * @default undefined
  31727. */
  31728. this.onStart = undefined;
  31729. /**
  31730. * Executes when all items have been loaded.
  31731. *
  31732. * @type {Function|undefined}
  31733. * @default undefined
  31734. */
  31735. this.onLoad = onLoad;
  31736. /**
  31737. * Executes when single items have been loaded.
  31738. *
  31739. * @type {Function|undefined}
  31740. * @default undefined
  31741. */
  31742. this.onProgress = onProgress;
  31743. /**
  31744. * Executes when an error occurs.
  31745. *
  31746. * @type {Function|undefined}
  31747. * @default undefined
  31748. */
  31749. this.onError = onError;
  31750. /**
  31751. * Used for aborting ongoing requests in loaders using this manager.
  31752. *
  31753. * @private
  31754. * @type {AbortController | null}
  31755. */
  31756. this._abortController = null;
  31757. /**
  31758. * This should be called by any loader using the manager when the loader
  31759. * starts loading an item.
  31760. *
  31761. * @param {string} url - The URL to load.
  31762. */
  31763. this.itemStart = function ( url ) {
  31764. itemsTotal ++;
  31765. if ( isLoading === false ) {
  31766. if ( scope.onStart !== undefined ) {
  31767. scope.onStart( url, itemsLoaded, itemsTotal );
  31768. }
  31769. }
  31770. isLoading = true;
  31771. };
  31772. /**
  31773. * This should be called by any loader using the manager when the loader
  31774. * ended loading an item.
  31775. *
  31776. * @param {string} url - The URL of the loaded item.
  31777. */
  31778. this.itemEnd = function ( url ) {
  31779. itemsLoaded ++;
  31780. if ( scope.onProgress !== undefined ) {
  31781. scope.onProgress( url, itemsLoaded, itemsTotal );
  31782. }
  31783. if ( itemsLoaded === itemsTotal ) {
  31784. isLoading = false;
  31785. if ( scope.onLoad !== undefined ) {
  31786. scope.onLoad();
  31787. }
  31788. }
  31789. };
  31790. /**
  31791. * This should be called by any loader using the manager when the loader
  31792. * encounters an error when loading an item.
  31793. *
  31794. * @param {string} url - The URL of the item that produces an error.
  31795. */
  31796. this.itemError = function ( url ) {
  31797. if ( scope.onError !== undefined ) {
  31798. scope.onError( url );
  31799. }
  31800. };
  31801. /**
  31802. * Given a URL, uses the URL modifier callback (if any) and returns a
  31803. * resolved URL. If no URL modifier is set, returns the original URL.
  31804. *
  31805. * @param {string} url - The URL to load.
  31806. * @return {string} The resolved URL.
  31807. */
  31808. this.resolveURL = function ( url ) {
  31809. if ( urlModifier ) {
  31810. return urlModifier( url );
  31811. }
  31812. return url;
  31813. };
  31814. /**
  31815. * If provided, the callback will be passed each resource URL before a
  31816. * request is sent. The callback may return the original URL, or a new URL to
  31817. * override loading behavior. This behavior can be used to load assets from
  31818. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31819. *
  31820. * ```js
  31821. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31822. *
  31823. * const manager = new THREE.LoadingManager();
  31824. *
  31825. * // Initialize loading manager with URL callback.
  31826. * const objectURLs = [];
  31827. * manager.setURLModifier( ( url ) => {
  31828. *
  31829. * url = URL.createObjectURL( blobs[ url ] );
  31830. * objectURLs.push( url );
  31831. * return url;
  31832. *
  31833. * } );
  31834. *
  31835. * // Load as usual, then revoke the blob URLs.
  31836. * const loader = new GLTFLoader( manager );
  31837. * loader.load( 'fish.gltf', (gltf) => {
  31838. *
  31839. * scene.add( gltf.scene );
  31840. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31841. *
  31842. * } );
  31843. * ```
  31844. *
  31845. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31846. * @return {LoadingManager} A reference to this loading manager.
  31847. */
  31848. this.setURLModifier = function ( transform ) {
  31849. urlModifier = transform;
  31850. return this;
  31851. };
  31852. /**
  31853. * Registers a loader with the given regular expression. Can be used to
  31854. * define what loader should be used in order to load specific files. A
  31855. * typical use case is to overwrite the default loader for textures.
  31856. *
  31857. * ```js
  31858. * // add handler for TGA textures
  31859. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31860. * ```
  31861. *
  31862. * @param {string} regex - A regular expression.
  31863. * @param {Loader} loader - A loader that should handle matched cases.
  31864. * @return {LoadingManager} A reference to this loading manager.
  31865. */
  31866. this.addHandler = function ( regex, loader ) {
  31867. handlers.push( regex, loader );
  31868. return this;
  31869. };
  31870. /**
  31871. * Removes the loader for the given regular expression.
  31872. *
  31873. * @param {string} regex - A regular expression.
  31874. * @return {LoadingManager} A reference to this loading manager.
  31875. */
  31876. this.removeHandler = function ( regex ) {
  31877. const index = handlers.indexOf( regex );
  31878. if ( index !== -1 ) {
  31879. handlers.splice( index, 2 );
  31880. }
  31881. return this;
  31882. };
  31883. /**
  31884. * Can be used to retrieve the registered loader for the given file path.
  31885. *
  31886. * @param {string} file - The file path.
  31887. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31888. */
  31889. this.getHandler = function ( file ) {
  31890. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31891. const regex = handlers[ i ];
  31892. const loader = handlers[ i + 1 ];
  31893. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31894. if ( regex.test( file ) ) {
  31895. return loader;
  31896. }
  31897. }
  31898. return null;
  31899. };
  31900. /**
  31901. * Can be used to abort ongoing loading requests in loaders using this manager.
  31902. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  31903. * is supported in the browser.
  31904. *
  31905. * @return {LoadingManager} A reference to this loading manager.
  31906. */
  31907. this.abort = function () {
  31908. this.abortController.abort();
  31909. this._abortController = null;
  31910. return this;
  31911. };
  31912. }
  31913. // TODO: Revert this back to a single member variable once this issue has been fixed
  31914. // https://github.com/cloudflare/workerd/issues/3657
  31915. /**
  31916. * Used for aborting ongoing requests in loaders using this manager.
  31917. *
  31918. * @type {AbortController}
  31919. */
  31920. get abortController() {
  31921. if ( ! this._abortController ) {
  31922. this._abortController = new AbortController();
  31923. }
  31924. return this._abortController;
  31925. }
  31926. }
  31927. /**
  31928. * The global default loading manager.
  31929. *
  31930. * @constant
  31931. * @type {LoadingManager}
  31932. */
  31933. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  31934. /**
  31935. * Abstract base class for loaders.
  31936. *
  31937. * @abstract
  31938. */
  31939. class Loader {
  31940. /**
  31941. * Constructs a new loader.
  31942. *
  31943. * @param {LoadingManager} [manager] - The loading manager.
  31944. */
  31945. constructor( manager ) {
  31946. /**
  31947. * The loading manager.
  31948. *
  31949. * @type {LoadingManager}
  31950. * @default DefaultLoadingManager
  31951. */
  31952. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  31953. /**
  31954. * The crossOrigin string to implement CORS for loading the url from a
  31955. * different domain that allows CORS.
  31956. *
  31957. * @type {string}
  31958. * @default 'anonymous'
  31959. */
  31960. this.crossOrigin = 'anonymous';
  31961. /**
  31962. * Whether the XMLHttpRequest uses credentials.
  31963. *
  31964. * @type {boolean}
  31965. * @default false
  31966. */
  31967. this.withCredentials = false;
  31968. /**
  31969. * The base path from which the asset will be loaded.
  31970. *
  31971. * @type {string}
  31972. */
  31973. this.path = '';
  31974. /**
  31975. * The base path from which additional resources like textures will be loaded.
  31976. *
  31977. * @type {string}
  31978. */
  31979. this.resourcePath = '';
  31980. /**
  31981. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  31982. * used in HTTP request.
  31983. *
  31984. * @type {Object<string, any>}
  31985. */
  31986. this.requestHeader = {};
  31987. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  31988. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  31989. }
  31990. }
  31991. /**
  31992. * This method needs to be implemented by all concrete loaders. It holds the
  31993. * logic for loading assets from the backend.
  31994. *
  31995. * @abstract
  31996. * @param {string} url - The path/URL of the file to be loaded.
  31997. * @param {Function} onLoad - Executed when the loading process has been finished.
  31998. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  31999. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32000. */
  32001. load( /* url, onLoad, onProgress, onError */ ) {}
  32002. /**
  32003. * A async version of {@link Loader#load}.
  32004. *
  32005. * @param {string} url - The path/URL of the file to be loaded.
  32006. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32007. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32008. */
  32009. loadAsync( url, onProgress ) {
  32010. const scope = this;
  32011. return new Promise( function ( resolve, reject ) {
  32012. scope.load( url, resolve, onProgress, reject );
  32013. } );
  32014. }
  32015. /**
  32016. * This method needs to be implemented by all concrete loaders. It holds the
  32017. * logic for parsing the asset into three.js entities.
  32018. *
  32019. * @abstract
  32020. * @param {any} data - The data to parse.
  32021. */
  32022. parse( /* data */ ) {}
  32023. /**
  32024. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32025. * from a different domain that allows CORS.
  32026. *
  32027. * @param {string} crossOrigin - The `crossOrigin` value.
  32028. * @return {Loader} A reference to this instance.
  32029. */
  32030. setCrossOrigin( crossOrigin ) {
  32031. this.crossOrigin = crossOrigin;
  32032. return this;
  32033. }
  32034. /**
  32035. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32036. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32037. *
  32038. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32039. *
  32040. * @param {boolean} value - The `withCredentials` value.
  32041. * @return {Loader} A reference to this instance.
  32042. */
  32043. setWithCredentials( value ) {
  32044. this.withCredentials = value;
  32045. return this;
  32046. }
  32047. /**
  32048. * Sets the base path for the asset.
  32049. *
  32050. * @param {string} path - The base path.
  32051. * @return {Loader} A reference to this instance.
  32052. */
  32053. setPath( path ) {
  32054. this.path = path;
  32055. return this;
  32056. }
  32057. /**
  32058. * Sets the base path for dependent resources like textures.
  32059. *
  32060. * @param {string} resourcePath - The resource path.
  32061. * @return {Loader} A reference to this instance.
  32062. */
  32063. setResourcePath( resourcePath ) {
  32064. this.resourcePath = resourcePath;
  32065. return this;
  32066. }
  32067. /**
  32068. * Sets the given request header.
  32069. *
  32070. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32071. * for configuring the HTTP request.
  32072. * @return {Loader} A reference to this instance.
  32073. */
  32074. setRequestHeader( requestHeader ) {
  32075. this.requestHeader = requestHeader;
  32076. return this;
  32077. }
  32078. /**
  32079. * This method can be implemented in loaders for aborting ongoing requests.
  32080. *
  32081. * @abstract
  32082. * @return {Loader} A reference to this instance.
  32083. */
  32084. abort() {
  32085. return this;
  32086. }
  32087. }
  32088. /**
  32089. * Callback for onProgress in loaders.
  32090. *
  32091. * @callback onProgressCallback
  32092. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32093. */
  32094. /**
  32095. * Callback for onError in loaders.
  32096. *
  32097. * @callback onErrorCallback
  32098. * @param {Error} error - The error which occurred during the loading process.
  32099. */
  32100. /**
  32101. * The default material name that is used by loaders
  32102. * when creating materials for loaded 3D objects.
  32103. *
  32104. * Note: Not all loaders might honor this setting.
  32105. *
  32106. * @static
  32107. * @type {string}
  32108. * @default '__DEFAULT'
  32109. */
  32110. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32111. const loading = {};
  32112. class HttpError extends Error {
  32113. constructor( message, response ) {
  32114. super( message );
  32115. this.response = response;
  32116. }
  32117. }
  32118. /**
  32119. * A low level class for loading resources with the Fetch API, used internally by
  32120. * most loaders. It can also be used directly to load any file type that does
  32121. * not have a loader.
  32122. *
  32123. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32124. * once to your application.
  32125. *
  32126. * ```js
  32127. * const loader = new THREE.FileLoader();
  32128. * const data = await loader.loadAsync( 'example.txt' );
  32129. * ```
  32130. *
  32131. * @augments Loader
  32132. */
  32133. class FileLoader extends Loader {
  32134. /**
  32135. * Constructs a new file loader.
  32136. *
  32137. * @param {LoadingManager} [manager] - The loading manager.
  32138. */
  32139. constructor( manager ) {
  32140. super( manager );
  32141. /**
  32142. * The expected mime type. Valid values can be found
  32143. * [here](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32144. *
  32145. * @type {string}
  32146. */
  32147. this.mimeType = '';
  32148. /**
  32149. * The expected response type.
  32150. *
  32151. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32152. * @default ''
  32153. */
  32154. this.responseType = '';
  32155. /**
  32156. * Used for aborting requests.
  32157. *
  32158. * @private
  32159. * @type {AbortController}
  32160. */
  32161. this._abortController = new AbortController();
  32162. }
  32163. /**
  32164. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32165. *
  32166. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32167. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32168. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32169. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32170. * @return {any|undefined} The cached resource if available.
  32171. */
  32172. load( url, onLoad, onProgress, onError ) {
  32173. if ( url === undefined ) url = '';
  32174. if ( this.path !== undefined ) url = this.path + url;
  32175. url = this.manager.resolveURL( url );
  32176. const cached = Cache.get( `file:${url}` );
  32177. if ( cached !== undefined ) {
  32178. this.manager.itemStart( url );
  32179. setTimeout( () => {
  32180. if ( onLoad ) onLoad( cached );
  32181. this.manager.itemEnd( url );
  32182. }, 0 );
  32183. return cached;
  32184. }
  32185. // Check if request is duplicate
  32186. if ( loading[ url ] !== undefined ) {
  32187. loading[ url ].push( {
  32188. onLoad: onLoad,
  32189. onProgress: onProgress,
  32190. onError: onError
  32191. } );
  32192. return;
  32193. }
  32194. // Initialise array for duplicate requests
  32195. loading[ url ] = [];
  32196. loading[ url ].push( {
  32197. onLoad: onLoad,
  32198. onProgress: onProgress,
  32199. onError: onError,
  32200. } );
  32201. // create request
  32202. const req = new Request( url, {
  32203. headers: new Headers( this.requestHeader ),
  32204. credentials: this.withCredentials ? 'include' : 'same-origin',
  32205. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32206. } );
  32207. // record states ( avoid data race )
  32208. const mimeType = this.mimeType;
  32209. const responseType = this.responseType;
  32210. // start the fetch
  32211. fetch( req )
  32212. .then( response => {
  32213. if ( response.status === 200 || response.status === 0 ) {
  32214. // Some browsers return HTTP Status 0 when using non-http protocol
  32215. // e.g. 'file://' or 'data://'. Handle as success.
  32216. if ( response.status === 0 ) {
  32217. warn( 'FileLoader: HTTP Status 0 received.' );
  32218. }
  32219. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32220. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32221. return response;
  32222. }
  32223. const callbacks = loading[ url ];
  32224. const reader = response.body.getReader();
  32225. // Nginx needs X-File-Size check
  32226. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32227. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32228. const total = contentLength ? parseInt( contentLength ) : 0;
  32229. const lengthComputable = total !== 0;
  32230. let loaded = 0;
  32231. // periodically read data into the new stream tracking while download progress
  32232. const stream = new ReadableStream( {
  32233. start( controller ) {
  32234. readData();
  32235. function readData() {
  32236. reader.read().then( ( { done, value } ) => {
  32237. if ( done ) {
  32238. controller.close();
  32239. } else {
  32240. loaded += value.byteLength;
  32241. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32242. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32243. const callback = callbacks[ i ];
  32244. if ( callback.onProgress ) callback.onProgress( event );
  32245. }
  32246. controller.enqueue( value );
  32247. readData();
  32248. }
  32249. }, ( e ) => {
  32250. controller.error( e );
  32251. } );
  32252. }
  32253. }
  32254. } );
  32255. return new Response( stream );
  32256. } else {
  32257. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32258. }
  32259. } )
  32260. .then( response => {
  32261. switch ( responseType ) {
  32262. case 'arraybuffer':
  32263. return response.arrayBuffer();
  32264. case 'blob':
  32265. return response.blob();
  32266. case 'document':
  32267. return response.text()
  32268. .then( text => {
  32269. const parser = new DOMParser();
  32270. return parser.parseFromString( text, mimeType );
  32271. } );
  32272. case 'json':
  32273. return response.json();
  32274. default:
  32275. if ( mimeType === '' ) {
  32276. return response.text();
  32277. } else {
  32278. // sniff encoding
  32279. const re = /charset="?([^;"\s]*)"?/i;
  32280. const exec = re.exec( mimeType );
  32281. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32282. const decoder = new TextDecoder( label );
  32283. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32284. }
  32285. }
  32286. } )
  32287. .then( data => {
  32288. // Add to cache only on HTTP success, so that we do not cache
  32289. // error response bodies as proper responses to requests.
  32290. Cache.add( `file:${url}`, data );
  32291. const callbacks = loading[ url ];
  32292. delete loading[ url ];
  32293. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32294. const callback = callbacks[ i ];
  32295. if ( callback.onLoad ) callback.onLoad( data );
  32296. }
  32297. } )
  32298. .catch( err => {
  32299. // Abort errors and other errors are handled the same
  32300. const callbacks = loading[ url ];
  32301. if ( callbacks === undefined ) {
  32302. // When onLoad was called and url was deleted in `loading`
  32303. this.manager.itemError( url );
  32304. throw err;
  32305. }
  32306. delete loading[ url ];
  32307. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32308. const callback = callbacks[ i ];
  32309. if ( callback.onError ) callback.onError( err );
  32310. }
  32311. this.manager.itemError( url );
  32312. } )
  32313. .finally( () => {
  32314. this.manager.itemEnd( url );
  32315. } );
  32316. this.manager.itemStart( url );
  32317. }
  32318. /**
  32319. * Sets the expected response type.
  32320. *
  32321. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32322. * @return {FileLoader} A reference to this file loader.
  32323. */
  32324. setResponseType( value ) {
  32325. this.responseType = value;
  32326. return this;
  32327. }
  32328. /**
  32329. * Sets the expected mime type of the loaded file.
  32330. *
  32331. * @param {string} value - The mime type.
  32332. * @return {FileLoader} A reference to this file loader.
  32333. */
  32334. setMimeType( value ) {
  32335. this.mimeType = value;
  32336. return this;
  32337. }
  32338. /**
  32339. * Aborts ongoing fetch requests.
  32340. *
  32341. * @return {FileLoader} A reference to this instance.
  32342. */
  32343. abort() {
  32344. this._abortController.abort();
  32345. this._abortController = new AbortController();
  32346. return this;
  32347. }
  32348. }
  32349. /**
  32350. * Class for loading animation clips in the JSON format. The files are internally
  32351. * loaded via {@link FileLoader}.
  32352. *
  32353. * ```js
  32354. * const loader = new THREE.AnimationLoader();
  32355. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32356. * ```
  32357. *
  32358. * @augments Loader
  32359. */
  32360. class AnimationLoader extends Loader {
  32361. /**
  32362. * Constructs a new animation loader.
  32363. *
  32364. * @param {LoadingManager} [manager] - The loading manager.
  32365. */
  32366. constructor( manager ) {
  32367. super( manager );
  32368. }
  32369. /**
  32370. * Starts loading from the given URL and pass the loaded animations as an array
  32371. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32372. *
  32373. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32374. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32375. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32376. * @param {onErrorCallback} onError - Executed when errors occur.
  32377. */
  32378. load( url, onLoad, onProgress, onError ) {
  32379. const scope = this;
  32380. const loader = new FileLoader( this.manager );
  32381. loader.setPath( this.path );
  32382. loader.setRequestHeader( this.requestHeader );
  32383. loader.setWithCredentials( this.withCredentials );
  32384. loader.load( url, function ( text ) {
  32385. try {
  32386. onLoad( scope.parse( JSON.parse( text ) ) );
  32387. } catch ( e ) {
  32388. if ( onError ) {
  32389. onError( e );
  32390. } else {
  32391. error( e );
  32392. }
  32393. scope.manager.itemError( url );
  32394. }
  32395. }, onProgress, onError );
  32396. }
  32397. /**
  32398. * Parses the given JSON object and returns an array of animation clips.
  32399. *
  32400. * @param {Object} json - The serialized animation clips.
  32401. * @return {Array<AnimationClip>} The parsed animation clips.
  32402. */
  32403. parse( json ) {
  32404. const animations = [];
  32405. for ( let i = 0; i < json.length; i ++ ) {
  32406. const clip = AnimationClip.parse( json[ i ] );
  32407. animations.push( clip );
  32408. }
  32409. return animations;
  32410. }
  32411. }
  32412. /**
  32413. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32414. * Textures are internally loaded via {@link FileLoader}.
  32415. *
  32416. * Derived classes have to implement the `parse()` method which holds the parsing
  32417. * for the respective format.
  32418. *
  32419. * @abstract
  32420. * @augments Loader
  32421. */
  32422. class CompressedTextureLoader extends Loader {
  32423. /**
  32424. * Constructs a new compressed texture loader.
  32425. *
  32426. * @param {LoadingManager} [manager] - The loading manager.
  32427. */
  32428. constructor( manager ) {
  32429. super( manager );
  32430. }
  32431. /**
  32432. * Starts loading from the given URL and passes the loaded compressed texture
  32433. * to the `onLoad()` callback. The method also returns a new texture object which can
  32434. * directly be used for material creation. If you do it this way, the texture
  32435. * may pop up in your scene once the respective loading process is finished.
  32436. *
  32437. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32438. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32439. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32440. * @param {onErrorCallback} onError - Executed when errors occur.
  32441. * @return {CompressedTexture} The compressed texture.
  32442. */
  32443. load( url, onLoad, onProgress, onError ) {
  32444. const scope = this;
  32445. const images = [];
  32446. const texture = new CompressedTexture();
  32447. const loader = new FileLoader( this.manager );
  32448. loader.setPath( this.path );
  32449. loader.setResponseType( 'arraybuffer' );
  32450. loader.setRequestHeader( this.requestHeader );
  32451. loader.setWithCredentials( scope.withCredentials );
  32452. let loaded = 0;
  32453. function loadTexture( i ) {
  32454. loader.load( url[ i ], function ( buffer ) {
  32455. const texDatas = scope.parse( buffer, true );
  32456. images[ i ] = {
  32457. width: texDatas.width,
  32458. height: texDatas.height,
  32459. format: texDatas.format,
  32460. mipmaps: texDatas.mipmaps
  32461. };
  32462. loaded += 1;
  32463. if ( loaded === 6 ) {
  32464. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32465. texture.image = images;
  32466. texture.format = texDatas.format;
  32467. texture.needsUpdate = true;
  32468. if ( onLoad ) onLoad( texture );
  32469. }
  32470. }, onProgress, onError );
  32471. }
  32472. if ( Array.isArray( url ) ) {
  32473. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32474. loadTexture( i );
  32475. }
  32476. } else {
  32477. // compressed cubemap texture stored in a single DDS file
  32478. loader.load( url, function ( buffer ) {
  32479. const texDatas = scope.parse( buffer, true );
  32480. if ( texDatas.isCubemap ) {
  32481. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32482. for ( let f = 0; f < faces; f ++ ) {
  32483. images[ f ] = { mipmaps: [] };
  32484. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32485. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32486. images[ f ].format = texDatas.format;
  32487. images[ f ].width = texDatas.width;
  32488. images[ f ].height = texDatas.height;
  32489. }
  32490. }
  32491. texture.image = images;
  32492. } else {
  32493. texture.image.width = texDatas.width;
  32494. texture.image.height = texDatas.height;
  32495. texture.mipmaps = texDatas.mipmaps;
  32496. }
  32497. if ( texDatas.mipmapCount === 1 ) {
  32498. texture.minFilter = LinearFilter;
  32499. }
  32500. texture.format = texDatas.format;
  32501. texture.needsUpdate = true;
  32502. if ( onLoad ) onLoad( texture );
  32503. }, onProgress, onError );
  32504. }
  32505. return texture;
  32506. }
  32507. }
  32508. const _loading = new WeakMap();
  32509. /**
  32510. * A loader for loading images. The class loads images with the HTML `Image` API.
  32511. *
  32512. * ```js
  32513. * const loader = new THREE.ImageLoader();
  32514. * const image = await loader.loadAsync( 'image.png' );
  32515. * ```
  32516. * Please note that `ImageLoader` has dropped support for progress
  32517. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32518. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  32519. *
  32520. * @augments Loader
  32521. */
  32522. class ImageLoader extends Loader {
  32523. /**
  32524. * Constructs a new image loader.
  32525. *
  32526. * @param {LoadingManager} [manager] - The loading manager.
  32527. */
  32528. constructor( manager ) {
  32529. super( manager );
  32530. }
  32531. /**
  32532. * Starts loading from the given URL and passes the loaded image
  32533. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32534. * directly be used for texture creation. If you do it this way, the texture
  32535. * may pop up in your scene once the respective loading process is finished.
  32536. *
  32537. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32538. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32539. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32540. * @param {onErrorCallback} onError - Executed when errors occur.
  32541. * @return {Image} The image.
  32542. */
  32543. load( url, onLoad, onProgress, onError ) {
  32544. if ( this.path !== undefined ) url = this.path + url;
  32545. url = this.manager.resolveURL( url );
  32546. const scope = this;
  32547. const cached = Cache.get( `image:${url}` );
  32548. if ( cached !== undefined ) {
  32549. if ( cached.complete === true ) {
  32550. scope.manager.itemStart( url );
  32551. setTimeout( function () {
  32552. if ( onLoad ) onLoad( cached );
  32553. scope.manager.itemEnd( url );
  32554. }, 0 );
  32555. } else {
  32556. let arr = _loading.get( cached );
  32557. if ( arr === undefined ) {
  32558. arr = [];
  32559. _loading.set( cached, arr );
  32560. }
  32561. arr.push( { onLoad, onError } );
  32562. }
  32563. return cached;
  32564. }
  32565. const image = createElementNS( 'img' );
  32566. function onImageLoad() {
  32567. removeEventListeners();
  32568. if ( onLoad ) onLoad( this );
  32569. //
  32570. const callbacks = _loading.get( this ) || [];
  32571. for ( let i = 0; i < callbacks.length; i ++ ) {
  32572. const callback = callbacks[ i ];
  32573. if ( callback.onLoad ) callback.onLoad( this );
  32574. }
  32575. _loading.delete( this );
  32576. scope.manager.itemEnd( url );
  32577. }
  32578. function onImageError( event ) {
  32579. removeEventListeners();
  32580. if ( onError ) onError( event );
  32581. Cache.remove( `image:${url}` );
  32582. //
  32583. const callbacks = _loading.get( this ) || [];
  32584. for ( let i = 0; i < callbacks.length; i ++ ) {
  32585. const callback = callbacks[ i ];
  32586. if ( callback.onError ) callback.onError( event );
  32587. }
  32588. _loading.delete( this );
  32589. scope.manager.itemError( url );
  32590. scope.manager.itemEnd( url );
  32591. }
  32592. function removeEventListeners() {
  32593. image.removeEventListener( 'load', onImageLoad, false );
  32594. image.removeEventListener( 'error', onImageError, false );
  32595. }
  32596. image.addEventListener( 'load', onImageLoad, false );
  32597. image.addEventListener( 'error', onImageError, false );
  32598. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32599. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32600. }
  32601. Cache.add( `image:${url}`, image );
  32602. scope.manager.itemStart( url );
  32603. image.src = url;
  32604. return image;
  32605. }
  32606. }
  32607. /**
  32608. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32609. *
  32610. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32611. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32612. * like vertical and horizontal cross, column and row layouts are not supported.
  32613. *
  32614. * Note that, by convention, cube maps are specified in a coordinate system
  32615. * in which positive-x is to the right when looking up the positive-z axis --
  32616. * in other words, using a left-handed coordinate system. Since three.js uses
  32617. * a right-handed coordinate system, environment maps used in three.js will
  32618. * have pos-x and neg-x swapped.
  32619. *
  32620. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32621. * is set to `SRGBColorSpace` by default.
  32622. *
  32623. * ```js
  32624. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32625. * const cubeTexture = await loader.loadAsync( [
  32626. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32627. * ] );
  32628. * scene.background = cubeTexture;
  32629. * ```
  32630. *
  32631. * @augments Loader
  32632. */
  32633. class CubeTextureLoader extends Loader {
  32634. /**
  32635. * Constructs a new cube texture loader.
  32636. *
  32637. * @param {LoadingManager} [manager] - The loading manager.
  32638. */
  32639. constructor( manager ) {
  32640. super( manager );
  32641. }
  32642. /**
  32643. * Starts loading from the given URL and pass the fully loaded cube texture
  32644. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32645. * directly be used for material creation. If you do it this way, the cube texture
  32646. * may pop up in your scene once the respective loading process is finished.
  32647. *
  32648. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32649. * cube texture. The urls should be specified in the following order: pos-x,
  32650. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32651. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32652. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32653. * @param {onErrorCallback} onError - Executed when errors occur.
  32654. * @return {CubeTexture} The cube texture.
  32655. */
  32656. load( urls, onLoad, onProgress, onError ) {
  32657. const texture = new CubeTexture();
  32658. texture.colorSpace = SRGBColorSpace;
  32659. const loader = new ImageLoader( this.manager );
  32660. loader.setCrossOrigin( this.crossOrigin );
  32661. loader.setPath( this.path );
  32662. let loaded = 0;
  32663. function loadTexture( i ) {
  32664. loader.load( urls[ i ], function ( image ) {
  32665. texture.images[ i ] = image;
  32666. loaded ++;
  32667. if ( loaded === 6 ) {
  32668. texture.needsUpdate = true;
  32669. if ( onLoad ) onLoad( texture );
  32670. }
  32671. }, undefined, onError );
  32672. }
  32673. for ( let i = 0; i < urls.length; ++ i ) {
  32674. loadTexture( i );
  32675. }
  32676. return texture;
  32677. }
  32678. }
  32679. /**
  32680. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32681. * Textures are internally loaded via {@link FileLoader}.
  32682. *
  32683. * Derived classes have to implement the `parse()` method which holds the parsing
  32684. * for the respective format.
  32685. *
  32686. * @abstract
  32687. * @augments Loader
  32688. */
  32689. class DataTextureLoader extends Loader {
  32690. /**
  32691. * Constructs a new data texture loader.
  32692. *
  32693. * @param {LoadingManager} [manager] - The loading manager.
  32694. */
  32695. constructor( manager ) {
  32696. super( manager );
  32697. }
  32698. /**
  32699. * Starts loading from the given URL and passes the loaded data texture
  32700. * to the `onLoad()` callback. The method also returns a new texture object which can
  32701. * directly be used for material creation. If you do it this way, the texture
  32702. * may pop up in your scene once the respective loading process is finished.
  32703. *
  32704. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32705. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32706. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32707. * @param {onErrorCallback} onError - Executed when errors occur.
  32708. * @return {DataTexture} The data texture.
  32709. */
  32710. load( url, onLoad, onProgress, onError ) {
  32711. const scope = this;
  32712. const texture = new DataTexture();
  32713. const loader = new FileLoader( this.manager );
  32714. loader.setResponseType( 'arraybuffer' );
  32715. loader.setRequestHeader( this.requestHeader );
  32716. loader.setPath( this.path );
  32717. loader.setWithCredentials( scope.withCredentials );
  32718. loader.load( url, function ( buffer ) {
  32719. let texData;
  32720. try {
  32721. texData = scope.parse( buffer );
  32722. } catch ( error ) {
  32723. if ( onError !== undefined ) {
  32724. onError( error );
  32725. } else {
  32726. error( error );
  32727. return;
  32728. }
  32729. }
  32730. if ( texData.image !== undefined ) {
  32731. texture.image = texData.image;
  32732. } else if ( texData.data !== undefined ) {
  32733. texture.image.width = texData.width;
  32734. texture.image.height = texData.height;
  32735. texture.image.data = texData.data;
  32736. }
  32737. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32738. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32739. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32740. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32741. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32742. if ( texData.colorSpace !== undefined ) {
  32743. texture.colorSpace = texData.colorSpace;
  32744. }
  32745. if ( texData.flipY !== undefined ) {
  32746. texture.flipY = texData.flipY;
  32747. }
  32748. if ( texData.format !== undefined ) {
  32749. texture.format = texData.format;
  32750. }
  32751. if ( texData.type !== undefined ) {
  32752. texture.type = texData.type;
  32753. }
  32754. if ( texData.mipmaps !== undefined ) {
  32755. texture.mipmaps = texData.mipmaps;
  32756. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32757. }
  32758. if ( texData.mipmapCount === 1 ) {
  32759. texture.minFilter = LinearFilter;
  32760. }
  32761. if ( texData.generateMipmaps !== undefined ) {
  32762. texture.generateMipmaps = texData.generateMipmaps;
  32763. }
  32764. texture.needsUpdate = true;
  32765. if ( onLoad ) onLoad( texture, texData );
  32766. }, onProgress, onError );
  32767. return texture;
  32768. }
  32769. }
  32770. /**
  32771. * Class for loading textures. Images are internally
  32772. * loaded via {@link ImageLoader}.
  32773. *
  32774. * ```js
  32775. * const loader = new THREE.TextureLoader();
  32776. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32777. *
  32778. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32779. * ```
  32780. * Please note that `TextureLoader` has dropped support for progress
  32781. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32782. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  32783. *
  32784. * @augments Loader
  32785. */
  32786. class TextureLoader extends Loader {
  32787. /**
  32788. * Constructs a new texture loader.
  32789. *
  32790. * @param {LoadingManager} [manager] - The loading manager.
  32791. */
  32792. constructor( manager ) {
  32793. super( manager );
  32794. }
  32795. /**
  32796. * Starts loading from the given URL and pass the fully loaded texture
  32797. * to the `onLoad()` callback. The method also returns a new texture object which can
  32798. * directly be used for material creation. If you do it this way, the texture
  32799. * may pop up in your scene once the respective loading process is finished.
  32800. *
  32801. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32802. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32803. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32804. * @param {onErrorCallback} onError - Executed when errors occur.
  32805. * @return {Texture} The texture.
  32806. */
  32807. load( url, onLoad, onProgress, onError ) {
  32808. const texture = new Texture();
  32809. const loader = new ImageLoader( this.manager );
  32810. loader.setCrossOrigin( this.crossOrigin );
  32811. loader.setPath( this.path );
  32812. loader.load( url, function ( image ) {
  32813. texture.image = image;
  32814. texture.needsUpdate = true;
  32815. if ( onLoad !== undefined ) {
  32816. onLoad( texture );
  32817. }
  32818. }, onProgress, onError );
  32819. return texture;
  32820. }
  32821. }
  32822. /**
  32823. * Abstract base class for lights - all other light types inherit the
  32824. * properties and methods described here.
  32825. *
  32826. * @abstract
  32827. * @augments Object3D
  32828. */
  32829. class Light extends Object3D {
  32830. /**
  32831. * Constructs a new light.
  32832. *
  32833. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32834. * @param {number} [intensity=1] - The light's strength/intensity.
  32835. */
  32836. constructor( color, intensity = 1 ) {
  32837. super();
  32838. /**
  32839. * This flag can be used for type testing.
  32840. *
  32841. * @type {boolean}
  32842. * @readonly
  32843. * @default true
  32844. */
  32845. this.isLight = true;
  32846. this.type = 'Light';
  32847. /**
  32848. * The light's color.
  32849. *
  32850. * @type {Color}
  32851. */
  32852. this.color = new Color( color );
  32853. /**
  32854. * The light's intensity.
  32855. *
  32856. * @type {number}
  32857. * @default 1
  32858. */
  32859. this.intensity = intensity;
  32860. }
  32861. /**
  32862. * Frees the GPU-related resources allocated by this instance. Call this
  32863. * method whenever this instance is no longer used in your app.
  32864. */
  32865. dispose() {
  32866. this.dispatchEvent( { type: 'dispose' } );
  32867. }
  32868. copy( source, recursive ) {
  32869. super.copy( source, recursive );
  32870. this.color.copy( source.color );
  32871. this.intensity = source.intensity;
  32872. return this;
  32873. }
  32874. toJSON( meta ) {
  32875. const data = super.toJSON( meta );
  32876. data.object.color = this.color.getHex();
  32877. data.object.intensity = this.intensity;
  32878. return data;
  32879. }
  32880. }
  32881. /**
  32882. * A light source positioned directly above the scene, with color fading from
  32883. * the sky color to the ground color.
  32884. *
  32885. * This light cannot be used to cast shadows.
  32886. *
  32887. * ```js
  32888. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32889. * scene.add( light );
  32890. * ```
  32891. *
  32892. * @augments Light
  32893. */
  32894. class HemisphereLight extends Light {
  32895. /**
  32896. * Constructs a new hemisphere light.
  32897. *
  32898. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32899. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32900. * @param {number} [intensity=1] - The light's strength/intensity.
  32901. */
  32902. constructor( skyColor, groundColor, intensity ) {
  32903. super( skyColor, intensity );
  32904. /**
  32905. * This flag can be used for type testing.
  32906. *
  32907. * @type {boolean}
  32908. * @readonly
  32909. * @default true
  32910. */
  32911. this.isHemisphereLight = true;
  32912. this.type = 'HemisphereLight';
  32913. this.position.copy( Object3D.DEFAULT_UP );
  32914. this.updateMatrix();
  32915. /**
  32916. * The light's ground color.
  32917. *
  32918. * @type {Color}
  32919. */
  32920. this.groundColor = new Color( groundColor );
  32921. }
  32922. copy( source, recursive ) {
  32923. super.copy( source, recursive );
  32924. this.groundColor.copy( source.groundColor );
  32925. return this;
  32926. }
  32927. toJSON( meta ) {
  32928. const data = super.toJSON( meta );
  32929. data.object.groundColor = this.groundColor.getHex();
  32930. return data;
  32931. }
  32932. }
  32933. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  32934. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  32935. const _lookTarget = /*@__PURE__*/ new Vector3();
  32936. /**
  32937. * Abstract base class for light shadow classes. These classes
  32938. * represent the shadow configuration for different light types.
  32939. *
  32940. * @abstract
  32941. */
  32942. class LightShadow {
  32943. /**
  32944. * Constructs a new light shadow.
  32945. *
  32946. * @param {Camera} camera - The light's view of the world.
  32947. */
  32948. constructor( camera ) {
  32949. /**
  32950. * The light's view of the world.
  32951. *
  32952. * @type {Camera}
  32953. */
  32954. this.camera = camera;
  32955. /**
  32956. * The intensity of the shadow. The default is `1`.
  32957. * Valid values are in the range `[0, 1]`.
  32958. *
  32959. * @type {number}
  32960. * @default 1
  32961. */
  32962. this.intensity = 1;
  32963. /**
  32964. * Shadow map bias, how much to add or subtract from the normalized depth
  32965. * when deciding whether a surface is in shadow.
  32966. *
  32967. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  32968. * may help reduce artifacts in shadows.
  32969. *
  32970. * @type {number}
  32971. * @default 0
  32972. */
  32973. this.bias = 0;
  32974. /**
  32975. * A node version of `bias`. Only supported with `WebGPURenderer`.
  32976. *
  32977. * If a bias node is defined, `bias` has no effect.
  32978. *
  32979. * @type {?Node<float>}
  32980. * @default null
  32981. */
  32982. this.biasNode = null;
  32983. /**
  32984. * Defines how much the position used to query the shadow map is offset along
  32985. * the object normal. The default is `0`. Increasing this value can be used to
  32986. * reduce shadow acne especially in large scenes where light shines onto
  32987. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  32988. *
  32989. * @type {number}
  32990. * @default 0
  32991. */
  32992. this.normalBias = 0;
  32993. /**
  32994. * Setting this to values greater than 1 will blur the edges of the shadow.
  32995. * High values will cause unwanted banding effects in the shadows - a greater
  32996. * map size will allow for a higher value to be used here before these effects
  32997. * become visible.
  32998. *
  32999. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33000. *
  33001. * @type {number}
  33002. * @default 1
  33003. */
  33004. this.radius = 1;
  33005. /**
  33006. * The amount of samples to use when blurring a VSM shadow map.
  33007. *
  33008. * @type {number}
  33009. * @default 8
  33010. */
  33011. this.blurSamples = 8;
  33012. /**
  33013. * Defines the width and height of the shadow map. Higher values give better quality
  33014. * shadows at the cost of computation time. Values must be powers of two.
  33015. *
  33016. * @type {Vector2}
  33017. * @default (512,512)
  33018. */
  33019. this.mapSize = new Vector2( 512, 512 );
  33020. /**
  33021. * The type of shadow texture. The default is `UnsignedByteType`.
  33022. *
  33023. * @type {number}
  33024. * @default UnsignedByteType
  33025. */
  33026. this.mapType = UnsignedByteType;
  33027. /**
  33028. * The depth map generated using the internal camera; a location beyond a
  33029. * pixel's depth is in shadow. Computed internally during rendering.
  33030. *
  33031. * @type {?RenderTarget}
  33032. * @default null
  33033. */
  33034. this.map = null;
  33035. /**
  33036. * The distribution map generated using the internal camera; an occlusion is
  33037. * calculated based on the distribution of depths. Computed internally during
  33038. * rendering.
  33039. *
  33040. * @type {?RenderTarget}
  33041. * @default null
  33042. */
  33043. this.mapPass = null;
  33044. /**
  33045. * Model to shadow camera space, to compute location and depth in shadow map.
  33046. * This is computed internally during rendering.
  33047. *
  33048. * @type {Matrix4}
  33049. */
  33050. this.matrix = new Matrix4();
  33051. /**
  33052. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33053. * lighting / shadows, you may set this to `false`.
  33054. *
  33055. * @type {boolean}
  33056. * @default true
  33057. */
  33058. this.autoUpdate = true;
  33059. /**
  33060. * When set to `true`, shadow maps will be updated in the next `render` call.
  33061. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33062. * set this property to `true` and then make a render call to update the light's shadow.
  33063. *
  33064. * @type {boolean}
  33065. * @default false
  33066. */
  33067. this.needsUpdate = false;
  33068. this._frustum = new Frustum();
  33069. this._frameExtents = new Vector2( 1, 1 );
  33070. this._viewportCount = 1;
  33071. this._viewports = [
  33072. new Vector4( 0, 0, 1, 1 )
  33073. ];
  33074. }
  33075. /**
  33076. * Used internally by the renderer to get the number of viewports that need
  33077. * to be rendered for this shadow.
  33078. *
  33079. * @return {number} The viewport count.
  33080. */
  33081. getViewportCount() {
  33082. return this._viewportCount;
  33083. }
  33084. /**
  33085. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33086. *
  33087. * @return {Frustum} The shadow camera frustum.
  33088. */
  33089. getFrustum() {
  33090. return this._frustum;
  33091. }
  33092. /**
  33093. * Update the matrices for the camera and shadow, used internally by the renderer.
  33094. *
  33095. * @param {Light} light - The light for which the shadow is being rendered.
  33096. */
  33097. updateMatrices( light ) {
  33098. const shadowCamera = this.camera;
  33099. const shadowMatrix = this.matrix;
  33100. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33101. shadowCamera.position.copy( _lightPositionWorld );
  33102. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  33103. shadowCamera.lookAt( _lookTarget );
  33104. shadowCamera.updateMatrixWorld();
  33105. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33106. this._frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33107. if ( shadowCamera.reversedDepth ) {
  33108. shadowMatrix.set(
  33109. 0.5, 0.0, 0.0, 0.5,
  33110. 0.0, 0.5, 0.0, 0.5,
  33111. 0.0, 0.0, 1.0, 0.0,
  33112. 0.0, 0.0, 0.0, 1.0
  33113. );
  33114. } else {
  33115. shadowMatrix.set(
  33116. 0.5, 0.0, 0.0, 0.5,
  33117. 0.0, 0.5, 0.0, 0.5,
  33118. 0.0, 0.0, 0.5, 0.5,
  33119. 0.0, 0.0, 0.0, 1.0
  33120. );
  33121. }
  33122. shadowMatrix.multiply( _projScreenMatrix );
  33123. }
  33124. /**
  33125. * Returns a viewport definition for the given viewport index.
  33126. *
  33127. * @param {number} viewportIndex - The viewport index.
  33128. * @return {Vector4} The viewport.
  33129. */
  33130. getViewport( viewportIndex ) {
  33131. return this._viewports[ viewportIndex ];
  33132. }
  33133. /**
  33134. * Returns the frame extends.
  33135. *
  33136. * @return {Vector2} The frame extends.
  33137. */
  33138. getFrameExtents() {
  33139. return this._frameExtents;
  33140. }
  33141. /**
  33142. * Frees the GPU-related resources allocated by this instance. Call this
  33143. * method whenever this instance is no longer used in your app.
  33144. */
  33145. dispose() {
  33146. if ( this.map ) {
  33147. this.map.dispose();
  33148. }
  33149. if ( this.mapPass ) {
  33150. this.mapPass.dispose();
  33151. }
  33152. }
  33153. /**
  33154. * Copies the values of the given light shadow instance to this instance.
  33155. *
  33156. * @param {LightShadow} source - The light shadow to copy.
  33157. * @return {LightShadow} A reference to this light shadow instance.
  33158. */
  33159. copy( source ) {
  33160. this.camera = source.camera.clone();
  33161. this.intensity = source.intensity;
  33162. this.bias = source.bias;
  33163. this.radius = source.radius;
  33164. this.autoUpdate = source.autoUpdate;
  33165. this.needsUpdate = source.needsUpdate;
  33166. this.normalBias = source.normalBias;
  33167. this.blurSamples = source.blurSamples;
  33168. this.mapSize.copy( source.mapSize );
  33169. this.biasNode = source.biasNode;
  33170. return this;
  33171. }
  33172. /**
  33173. * Returns a new light shadow instance with copied values from this instance.
  33174. *
  33175. * @return {LightShadow} A clone of this instance.
  33176. */
  33177. clone() {
  33178. return new this.constructor().copy( this );
  33179. }
  33180. /**
  33181. * Serializes the light shadow into JSON.
  33182. *
  33183. * @return {Object} A JSON object representing the serialized light shadow.
  33184. * @see {@link ObjectLoader#parse}
  33185. */
  33186. toJSON() {
  33187. const object = {};
  33188. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33189. if ( this.bias !== 0 ) object.bias = this.bias;
  33190. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33191. if ( this.radius !== 1 ) object.radius = this.radius;
  33192. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33193. object.camera = this.camera.toJSON( false ).object;
  33194. delete object.camera.matrix;
  33195. return object;
  33196. }
  33197. }
  33198. const _position$2 = /*@__PURE__*/ new Vector3();
  33199. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  33200. const _scale$2 = /*@__PURE__*/ new Vector3();
  33201. /**
  33202. * Abstract base class for cameras. This class should always be inherited
  33203. * when you build a new camera.
  33204. *
  33205. * @abstract
  33206. * @augments Object3D
  33207. */
  33208. class Camera extends Object3D {
  33209. /**
  33210. * Constructs a new camera.
  33211. */
  33212. constructor() {
  33213. super();
  33214. /**
  33215. * This flag can be used for type testing.
  33216. *
  33217. * @type {boolean}
  33218. * @readonly
  33219. * @default true
  33220. */
  33221. this.isCamera = true;
  33222. this.type = 'Camera';
  33223. /**
  33224. * The inverse of the camera's world matrix.
  33225. *
  33226. * @type {Matrix4}
  33227. */
  33228. this.matrixWorldInverse = new Matrix4();
  33229. /**
  33230. * The camera's projection matrix.
  33231. *
  33232. * @type {Matrix4}
  33233. */
  33234. this.projectionMatrix = new Matrix4();
  33235. /**
  33236. * The inverse of the camera's projection matrix.
  33237. *
  33238. * @type {Matrix4}
  33239. */
  33240. this.projectionMatrixInverse = new Matrix4();
  33241. /**
  33242. * The coordinate system in which the camera is used.
  33243. *
  33244. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  33245. */
  33246. this.coordinateSystem = WebGLCoordinateSystem;
  33247. this._reversedDepth = false;
  33248. }
  33249. /**
  33250. * The flag that indicates whether the camera uses a reversed depth buffer.
  33251. *
  33252. * @type {boolean}
  33253. * @default false
  33254. */
  33255. get reversedDepth() {
  33256. return this._reversedDepth;
  33257. }
  33258. copy( source, recursive ) {
  33259. super.copy( source, recursive );
  33260. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  33261. this.projectionMatrix.copy( source.projectionMatrix );
  33262. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  33263. this.coordinateSystem = source.coordinateSystem;
  33264. return this;
  33265. }
  33266. /**
  33267. * Returns a vector representing the ("look") direction of the 3D object in world space.
  33268. *
  33269. * This method is overwritten since cameras have a different forward vector compared to other
  33270. * 3D objects. A camera looks down its local, negative z-axis by default.
  33271. *
  33272. * @param {Vector3} target - The target vector the result is stored to.
  33273. * @return {Vector3} The 3D object's direction in world space.
  33274. */
  33275. getWorldDirection( target ) {
  33276. return super.getWorldDirection( target ).negate();
  33277. }
  33278. updateMatrixWorld( force ) {
  33279. super.updateMatrixWorld( force );
  33280. // exclude scale from view matrix to be glTF conform
  33281. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33282. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33283. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33284. } else {
  33285. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33286. }
  33287. }
  33288. updateWorldMatrix( updateParents, updateChildren ) {
  33289. super.updateWorldMatrix( updateParents, updateChildren );
  33290. // exclude scale from view matrix to be glTF conform
  33291. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33292. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33293. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33294. } else {
  33295. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33296. }
  33297. }
  33298. clone() {
  33299. return new this.constructor().copy( this );
  33300. }
  33301. }
  33302. const _v3$1 = /*@__PURE__*/ new Vector3();
  33303. const _minTarget = /*@__PURE__*/ new Vector2();
  33304. const _maxTarget = /*@__PURE__*/ new Vector2();
  33305. /**
  33306. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  33307. *
  33308. * This projection mode is designed to mimic the way the human eye sees. It
  33309. * is the most common projection mode used for rendering a 3D scene.
  33310. *
  33311. * ```js
  33312. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  33313. * scene.add( camera );
  33314. * ```
  33315. *
  33316. * @augments Camera
  33317. */
  33318. class PerspectiveCamera extends Camera {
  33319. /**
  33320. * Constructs a new perspective camera.
  33321. *
  33322. * @param {number} [fov=50] - The vertical field of view.
  33323. * @param {number} [aspect=1] - The aspect ratio.
  33324. * @param {number} [near=0.1] - The camera's near plane.
  33325. * @param {number} [far=2000] - The camera's far plane.
  33326. */
  33327. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  33328. super();
  33329. /**
  33330. * This flag can be used for type testing.
  33331. *
  33332. * @type {boolean}
  33333. * @readonly
  33334. * @default true
  33335. */
  33336. this.isPerspectiveCamera = true;
  33337. this.type = 'PerspectiveCamera';
  33338. /**
  33339. * The vertical field of view, from bottom to top of view,
  33340. * in degrees.
  33341. *
  33342. * @type {number}
  33343. * @default 50
  33344. */
  33345. this.fov = fov;
  33346. /**
  33347. * The zoom factor of the camera.
  33348. *
  33349. * @type {number}
  33350. * @default 1
  33351. */
  33352. this.zoom = 1;
  33353. /**
  33354. * The camera's near plane. The valid range is greater than `0`
  33355. * and less than the current value of {@link PerspectiveCamera#far}.
  33356. *
  33357. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  33358. * valid value for a perspective camera's near plane.
  33359. *
  33360. * @type {number}
  33361. * @default 0.1
  33362. */
  33363. this.near = near;
  33364. /**
  33365. * The camera's far plane. Must be greater than the
  33366. * current value of {@link PerspectiveCamera#near}.
  33367. *
  33368. * @type {number}
  33369. * @default 2000
  33370. */
  33371. this.far = far;
  33372. /**
  33373. * Object distance used for stereoscopy and depth-of-field effects. This
  33374. * parameter does not influence the projection matrix unless a
  33375. * {@link StereoCamera} is being used.
  33376. *
  33377. * @type {number}
  33378. * @default 10
  33379. */
  33380. this.focus = 10;
  33381. /**
  33382. * The aspect ratio, usually the canvas width / canvas height.
  33383. *
  33384. * @type {number}
  33385. * @default 1
  33386. */
  33387. this.aspect = aspect;
  33388. /**
  33389. * Represents the frustum window specification. This property should not be edited
  33390. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33391. *
  33392. * @type {?Object}
  33393. * @default null
  33394. */
  33395. this.view = null;
  33396. /**
  33397. * Film size used for the larger axis. Default is `35` (millimeters). This
  33398. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  33399. * is set to a nonzero value.
  33400. *
  33401. * @type {number}
  33402. * @default 35
  33403. */
  33404. this.filmGauge = 35;
  33405. /**
  33406. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  33407. *
  33408. * @type {number}
  33409. * @default 0
  33410. */
  33411. this.filmOffset = 0;
  33412. this.updateProjectionMatrix();
  33413. }
  33414. copy( source, recursive ) {
  33415. super.copy( source, recursive );
  33416. this.fov = source.fov;
  33417. this.zoom = source.zoom;
  33418. this.near = source.near;
  33419. this.far = source.far;
  33420. this.focus = source.focus;
  33421. this.aspect = source.aspect;
  33422. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33423. this.filmGauge = source.filmGauge;
  33424. this.filmOffset = source.filmOffset;
  33425. return this;
  33426. }
  33427. /**
  33428. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  33429. *
  33430. * The default film gauge is 35, so that the focal length can be specified for
  33431. * a 35mm (full frame) camera.
  33432. *
  33433. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  33434. */
  33435. setFocalLength( focalLength ) {
  33436. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  33437. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  33438. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  33439. this.updateProjectionMatrix();
  33440. }
  33441. /**
  33442. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  33443. * {@link PerspectiveCamera#filmGauge}.
  33444. *
  33445. * @return {number} The computed focal length.
  33446. */
  33447. getFocalLength() {
  33448. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  33449. return 0.5 * this.getFilmHeight() / vExtentSlope;
  33450. }
  33451. /**
  33452. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  33453. *
  33454. * @return {number} The effective FOV.
  33455. */
  33456. getEffectiveFOV() {
  33457. return RAD2DEG * 2 * Math.atan(
  33458. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  33459. }
  33460. /**
  33461. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  33462. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  33463. *
  33464. * @return {number} The film width.
  33465. */
  33466. getFilmWidth() {
  33467. // film not completely covered in portrait format (aspect < 1)
  33468. return this.filmGauge * Math.min( this.aspect, 1 );
  33469. }
  33470. /**
  33471. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  33472. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  33473. *
  33474. * @return {number} The film width.
  33475. */
  33476. getFilmHeight() {
  33477. // film not completely covered in landscape format (aspect > 1)
  33478. return this.filmGauge / Math.max( this.aspect, 1 );
  33479. }
  33480. /**
  33481. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  33482. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  33483. *
  33484. * @param {number} distance - The viewing distance.
  33485. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  33486. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  33487. */
  33488. getViewBounds( distance, minTarget, maxTarget ) {
  33489. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  33490. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  33491. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  33492. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  33493. }
  33494. /**
  33495. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  33496. *
  33497. * @param {number} distance - The viewing distance.
  33498. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  33499. * @returns {Vector2} The view size.
  33500. */
  33501. getViewSize( distance, target ) {
  33502. this.getViewBounds( distance, _minTarget, _maxTarget );
  33503. return target.subVectors( _maxTarget, _minTarget );
  33504. }
  33505. /**
  33506. * Sets an offset in a larger frustum. This is useful for multi-window or
  33507. * multi-monitor/multi-machine setups.
  33508. *
  33509. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  33510. * the monitors are in grid like this
  33511. *```
  33512. * +---+---+---+
  33513. * | A | B | C |
  33514. * +---+---+---+
  33515. * | D | E | F |
  33516. * +---+---+---+
  33517. *```
  33518. * then for each monitor you would call it like this:
  33519. *```js
  33520. * const w = 1920;
  33521. * const h = 1080;
  33522. * const fullWidth = w * 3;
  33523. * const fullHeight = h * 2;
  33524. *
  33525. * // --A--
  33526. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  33527. * // --B--
  33528. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  33529. * // --C--
  33530. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  33531. * // --D--
  33532. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  33533. * // --E--
  33534. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  33535. * // --F--
  33536. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  33537. * ```
  33538. *
  33539. * Note there is no reason monitors have to be the same size or in a grid.
  33540. *
  33541. * @param {number} fullWidth - The full width of multiview setup.
  33542. * @param {number} fullHeight - The full height of multiview setup.
  33543. * @param {number} x - The horizontal offset of the subcamera.
  33544. * @param {number} y - The vertical offset of the subcamera.
  33545. * @param {number} width - The width of subcamera.
  33546. * @param {number} height - The height of subcamera.
  33547. */
  33548. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33549. this.aspect = fullWidth / fullHeight;
  33550. if ( this.view === null ) {
  33551. this.view = {
  33552. enabled: true,
  33553. fullWidth: 1,
  33554. fullHeight: 1,
  33555. offsetX: 0,
  33556. offsetY: 0,
  33557. width: 1,
  33558. height: 1
  33559. };
  33560. }
  33561. this.view.enabled = true;
  33562. this.view.fullWidth = fullWidth;
  33563. this.view.fullHeight = fullHeight;
  33564. this.view.offsetX = x;
  33565. this.view.offsetY = y;
  33566. this.view.width = width;
  33567. this.view.height = height;
  33568. this.updateProjectionMatrix();
  33569. }
  33570. /**
  33571. * Removes the view offset from the projection matrix.
  33572. */
  33573. clearViewOffset() {
  33574. if ( this.view !== null ) {
  33575. this.view.enabled = false;
  33576. }
  33577. this.updateProjectionMatrix();
  33578. }
  33579. /**
  33580. * Updates the camera's projection matrix. Must be called after any change of
  33581. * camera properties.
  33582. */
  33583. updateProjectionMatrix() {
  33584. const near = this.near;
  33585. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  33586. let height = 2 * top;
  33587. let width = this.aspect * height;
  33588. let left = -0.5 * width;
  33589. const view = this.view;
  33590. if ( this.view !== null && this.view.enabled ) {
  33591. const fullWidth = view.fullWidth,
  33592. fullHeight = view.fullHeight;
  33593. left += view.offsetX * width / fullWidth;
  33594. top -= view.offsetY * height / fullHeight;
  33595. width *= view.width / fullWidth;
  33596. height *= view.height / fullHeight;
  33597. }
  33598. const skew = this.filmOffset;
  33599. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  33600. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  33601. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33602. }
  33603. toJSON( meta ) {
  33604. const data = super.toJSON( meta );
  33605. data.object.fov = this.fov;
  33606. data.object.zoom = this.zoom;
  33607. data.object.near = this.near;
  33608. data.object.far = this.far;
  33609. data.object.focus = this.focus;
  33610. data.object.aspect = this.aspect;
  33611. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33612. data.object.filmGauge = this.filmGauge;
  33613. data.object.filmOffset = this.filmOffset;
  33614. return data;
  33615. }
  33616. }
  33617. /**
  33618. * Represents the shadow configuration of directional lights.
  33619. *
  33620. * @augments LightShadow
  33621. */
  33622. class SpotLightShadow extends LightShadow {
  33623. /**
  33624. * Constructs a new spot light shadow.
  33625. */
  33626. constructor() {
  33627. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33628. /**
  33629. * This flag can be used for type testing.
  33630. *
  33631. * @type {boolean}
  33632. * @readonly
  33633. * @default true
  33634. */
  33635. this.isSpotLightShadow = true;
  33636. /**
  33637. * Used to focus the shadow camera. The camera's field of view is set as a
  33638. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33639. *
  33640. * @type {number}
  33641. * @default 1
  33642. */
  33643. this.focus = 1;
  33644. /**
  33645. * Texture aspect ratio.
  33646. *
  33647. * @type {number}
  33648. * @default 1
  33649. */
  33650. this.aspect = 1;
  33651. }
  33652. updateMatrices( light ) {
  33653. const camera = this.camera;
  33654. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33655. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33656. const far = light.distance || camera.far;
  33657. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33658. camera.fov = fov;
  33659. camera.aspect = aspect;
  33660. camera.far = far;
  33661. camera.updateProjectionMatrix();
  33662. }
  33663. super.updateMatrices( light );
  33664. }
  33665. copy( source ) {
  33666. super.copy( source );
  33667. this.focus = source.focus;
  33668. return this;
  33669. }
  33670. }
  33671. /**
  33672. * This light gets emitted from a single point in one direction, along a cone
  33673. * that increases in size the further from the light it gets.
  33674. *
  33675. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33676. *
  33677. * ```js
  33678. * // white spotlight shining from the side, modulated by a texture
  33679. * const spotLight = new THREE.SpotLight( 0xffffff );
  33680. * spotLight.position.set( 100, 1000, 100 );
  33681. * spotLight.map = new THREE.TextureLoader().load( url );
  33682. *
  33683. * spotLight.castShadow = true;
  33684. * spotLight.shadow.mapSize.width = 1024;
  33685. * spotLight.shadow.mapSize.height = 1024;
  33686. * spotLight.shadow.camera.near = 500;
  33687. * spotLight.shadow.camera.far = 4000;
  33688. * spotLight.shadow.camera.fov = 30;s
  33689. * ```
  33690. *
  33691. * @augments Light
  33692. */
  33693. class SpotLight extends Light {
  33694. /**
  33695. * Constructs a new spot light.
  33696. *
  33697. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33698. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33699. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33700. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33701. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33702. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33703. */
  33704. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33705. super( color, intensity );
  33706. /**
  33707. * This flag can be used for type testing.
  33708. *
  33709. * @type {boolean}
  33710. * @readonly
  33711. * @default true
  33712. */
  33713. this.isSpotLight = true;
  33714. this.type = 'SpotLight';
  33715. this.position.copy( Object3D.DEFAULT_UP );
  33716. this.updateMatrix();
  33717. /**
  33718. * The spot light points from its position to the
  33719. * target's position.
  33720. *
  33721. * For the target's position to be changed to anything other
  33722. * than the default, it must be added to the scene.
  33723. *
  33724. * It is also possible to set the target to be another 3D object
  33725. * in the scene. The light will now track the target object.
  33726. *
  33727. * @type {Object3D}
  33728. */
  33729. this.target = new Object3D();
  33730. /**
  33731. * Maximum range of the light. `0` means no limit.
  33732. *
  33733. * @type {number}
  33734. * @default 0
  33735. */
  33736. this.distance = distance;
  33737. /**
  33738. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33739. *
  33740. * @type {number}
  33741. * @default Math.PI/3
  33742. */
  33743. this.angle = angle;
  33744. /**
  33745. * Percent of the spotlight cone that is attenuated due to penumbra.
  33746. * Value range is `[0,1]`.
  33747. *
  33748. * @type {number}
  33749. * @default 0
  33750. */
  33751. this.penumbra = penumbra;
  33752. /**
  33753. * The amount the light dims along the distance of the light. In context of
  33754. * physically-correct rendering the default value should not be changed.
  33755. *
  33756. * @type {number}
  33757. * @default 2
  33758. */
  33759. this.decay = decay;
  33760. /**
  33761. * A texture used to modulate the color of the light. The spot light
  33762. * color is mixed with the RGB value of this texture, with a ratio
  33763. * corresponding to its alpha value. The cookie-like masking effect is
  33764. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33765. *
  33766. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33767. *
  33768. * @type {?Texture}
  33769. * @default null
  33770. */
  33771. this.map = null;
  33772. /**
  33773. * This property holds the light's shadow configuration.
  33774. *
  33775. * @type {SpotLightShadow}
  33776. */
  33777. this.shadow = new SpotLightShadow();
  33778. }
  33779. /**
  33780. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33781. * Changing the power will also change the light's intensity.
  33782. *
  33783. * @type {number}
  33784. */
  33785. get power() {
  33786. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33787. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33788. return this.intensity * Math.PI;
  33789. }
  33790. set power( power ) {
  33791. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33792. this.intensity = power / Math.PI;
  33793. }
  33794. dispose() {
  33795. super.dispose();
  33796. this.shadow.dispose();
  33797. }
  33798. copy( source, recursive ) {
  33799. super.copy( source, recursive );
  33800. this.distance = source.distance;
  33801. this.angle = source.angle;
  33802. this.penumbra = source.penumbra;
  33803. this.decay = source.decay;
  33804. this.target = source.target.clone();
  33805. this.map = source.map;
  33806. this.shadow = source.shadow.clone();
  33807. return this;
  33808. }
  33809. toJSON( meta ) {
  33810. const data = super.toJSON( meta );
  33811. data.object.distance = this.distance;
  33812. data.object.angle = this.angle;
  33813. data.object.decay = this.decay;
  33814. data.object.penumbra = this.penumbra;
  33815. data.object.target = this.target.uuid;
  33816. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  33817. data.object.shadow = this.shadow.toJSON();
  33818. return data;
  33819. }
  33820. }
  33821. /**
  33822. * Represents the shadow configuration of point lights.
  33823. *
  33824. * @augments LightShadow
  33825. */
  33826. class PointLightShadow extends LightShadow {
  33827. /**
  33828. * Constructs a new point light shadow.
  33829. */
  33830. constructor() {
  33831. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33832. /**
  33833. * This flag can be used for type testing.
  33834. *
  33835. * @type {boolean}
  33836. * @readonly
  33837. * @default true
  33838. */
  33839. this.isPointLightShadow = true;
  33840. }
  33841. }
  33842. /**
  33843. * A light that gets emitted from a single point in all directions. A common
  33844. * use case for this is to replicate the light emitted from a bare
  33845. * lightbulb.
  33846. *
  33847. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33848. *
  33849. * ```js
  33850. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33851. * light.position.set( 50, 50, 50 );
  33852. * scene.add( light );
  33853. * ```
  33854. *
  33855. * @augments Light
  33856. */
  33857. class PointLight extends Light {
  33858. /**
  33859. * Constructs a new point light.
  33860. *
  33861. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33862. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33863. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33864. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33865. */
  33866. constructor( color, intensity, distance = 0, decay = 2 ) {
  33867. super( color, intensity );
  33868. /**
  33869. * This flag can be used for type testing.
  33870. *
  33871. * @type {boolean}
  33872. * @readonly
  33873. * @default true
  33874. */
  33875. this.isPointLight = true;
  33876. this.type = 'PointLight';
  33877. /**
  33878. * When distance is zero, light will attenuate according to inverse-square
  33879. * law to infinite distance. When distance is non-zero, light will attenuate
  33880. * according to inverse-square law until near the distance cutoff, where it
  33881. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33882. * physically correct.
  33883. *
  33884. * @type {number}
  33885. * @default 0
  33886. */
  33887. this.distance = distance;
  33888. /**
  33889. * The amount the light dims along the distance of the light. In context of
  33890. * physically-correct rendering the default value should not be changed.
  33891. *
  33892. * @type {number}
  33893. * @default 2
  33894. */
  33895. this.decay = decay;
  33896. /**
  33897. * This property holds the light's shadow configuration.
  33898. *
  33899. * @type {PointLightShadow}
  33900. */
  33901. this.shadow = new PointLightShadow();
  33902. }
  33903. /**
  33904. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33905. * Changing the power will also change the light's intensity.
  33906. *
  33907. * @type {number}
  33908. */
  33909. get power() {
  33910. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33911. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33912. return this.intensity * 4 * Math.PI;
  33913. }
  33914. set power( power ) {
  33915. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33916. this.intensity = power / ( 4 * Math.PI );
  33917. }
  33918. dispose() {
  33919. super.dispose();
  33920. this.shadow.dispose();
  33921. }
  33922. copy( source, recursive ) {
  33923. super.copy( source, recursive );
  33924. this.distance = source.distance;
  33925. this.decay = source.decay;
  33926. this.shadow = source.shadow.clone();
  33927. return this;
  33928. }
  33929. toJSON( meta ) {
  33930. const data = super.toJSON( meta );
  33931. data.object.distance = this.distance;
  33932. data.object.decay = this.decay;
  33933. data.object.shadow = this.shadow.toJSON();
  33934. return data;
  33935. }
  33936. }
  33937. /**
  33938. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  33939. *
  33940. * In this projection mode, an object's size in the rendered image stays
  33941. * constant regardless of its distance from the camera. This can be useful
  33942. * for rendering 2D scenes and UI elements, amongst other things.
  33943. *
  33944. * ```js
  33945. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33946. * scene.add( camera );
  33947. * ```
  33948. *
  33949. * @augments Camera
  33950. */
  33951. class OrthographicCamera extends Camera {
  33952. /**
  33953. * Constructs a new orthographic camera.
  33954. *
  33955. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33956. * @param {number} [right=1] - The right plane of the camera's frustum.
  33957. * @param {number} [top=1] - The top plane of the camera's frustum.
  33958. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33959. * @param {number} [near=0.1] - The camera's near plane.
  33960. * @param {number} [far=2000] - The camera's far plane.
  33961. */
  33962. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33963. super();
  33964. /**
  33965. * This flag can be used for type testing.
  33966. *
  33967. * @type {boolean}
  33968. * @readonly
  33969. * @default true
  33970. */
  33971. this.isOrthographicCamera = true;
  33972. this.type = 'OrthographicCamera';
  33973. /**
  33974. * The zoom factor of the camera.
  33975. *
  33976. * @type {number}
  33977. * @default 1
  33978. */
  33979. this.zoom = 1;
  33980. /**
  33981. * Represents the frustum window specification. This property should not be edited
  33982. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33983. *
  33984. * @type {?Object}
  33985. * @default null
  33986. */
  33987. this.view = null;
  33988. /**
  33989. * The left plane of the camera's frustum.
  33990. *
  33991. * @type {number}
  33992. * @default -1
  33993. */
  33994. this.left = left;
  33995. /**
  33996. * The right plane of the camera's frustum.
  33997. *
  33998. * @type {number}
  33999. * @default 1
  34000. */
  34001. this.right = right;
  34002. /**
  34003. * The top plane of the camera's frustum.
  34004. *
  34005. * @type {number}
  34006. * @default 1
  34007. */
  34008. this.top = top;
  34009. /**
  34010. * The bottom plane of the camera's frustum.
  34011. *
  34012. * @type {number}
  34013. * @default -1
  34014. */
  34015. this.bottom = bottom;
  34016. /**
  34017. * The camera's near plane. The valid range is greater than `0`
  34018. * and less than the current value of {@link OrthographicCamera#far}.
  34019. *
  34020. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  34021. * valid value for an orthographic camera's near plane.
  34022. *
  34023. * @type {number}
  34024. * @default 0.1
  34025. */
  34026. this.near = near;
  34027. /**
  34028. * The camera's far plane. Must be greater than the
  34029. * current value of {@link OrthographicCamera#near}.
  34030. *
  34031. * @type {number}
  34032. * @default 2000
  34033. */
  34034. this.far = far;
  34035. this.updateProjectionMatrix();
  34036. }
  34037. copy( source, recursive ) {
  34038. super.copy( source, recursive );
  34039. this.left = source.left;
  34040. this.right = source.right;
  34041. this.top = source.top;
  34042. this.bottom = source.bottom;
  34043. this.near = source.near;
  34044. this.far = source.far;
  34045. this.zoom = source.zoom;
  34046. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34047. return this;
  34048. }
  34049. /**
  34050. * Sets an offset in a larger frustum. This is useful for multi-window or
  34051. * multi-monitor/multi-machine setups.
  34052. *
  34053. * @param {number} fullWidth - The full width of multiview setup.
  34054. * @param {number} fullHeight - The full height of multiview setup.
  34055. * @param {number} x - The horizontal offset of the subcamera.
  34056. * @param {number} y - The vertical offset of the subcamera.
  34057. * @param {number} width - The width of subcamera.
  34058. * @param {number} height - The height of subcamera.
  34059. * @see {@link PerspectiveCamera#setViewOffset}
  34060. */
  34061. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34062. if ( this.view === null ) {
  34063. this.view = {
  34064. enabled: true,
  34065. fullWidth: 1,
  34066. fullHeight: 1,
  34067. offsetX: 0,
  34068. offsetY: 0,
  34069. width: 1,
  34070. height: 1
  34071. };
  34072. }
  34073. this.view.enabled = true;
  34074. this.view.fullWidth = fullWidth;
  34075. this.view.fullHeight = fullHeight;
  34076. this.view.offsetX = x;
  34077. this.view.offsetY = y;
  34078. this.view.width = width;
  34079. this.view.height = height;
  34080. this.updateProjectionMatrix();
  34081. }
  34082. /**
  34083. * Removes the view offset from the projection matrix.
  34084. */
  34085. clearViewOffset() {
  34086. if ( this.view !== null ) {
  34087. this.view.enabled = false;
  34088. }
  34089. this.updateProjectionMatrix();
  34090. }
  34091. /**
  34092. * Updates the camera's projection matrix. Must be called after any change of
  34093. * camera properties.
  34094. */
  34095. updateProjectionMatrix() {
  34096. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34097. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34098. const cx = ( this.right + this.left ) / 2;
  34099. const cy = ( this.top + this.bottom ) / 2;
  34100. let left = cx - dx;
  34101. let right = cx + dx;
  34102. let top = cy + dy;
  34103. let bottom = cy - dy;
  34104. if ( this.view !== null && this.view.enabled ) {
  34105. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34106. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34107. left += scaleW * this.view.offsetX;
  34108. right = left + scaleW * this.view.width;
  34109. top -= scaleH * this.view.offsetY;
  34110. bottom = top - scaleH * this.view.height;
  34111. }
  34112. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34113. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34114. }
  34115. toJSON( meta ) {
  34116. const data = super.toJSON( meta );
  34117. data.object.zoom = this.zoom;
  34118. data.object.left = this.left;
  34119. data.object.right = this.right;
  34120. data.object.top = this.top;
  34121. data.object.bottom = this.bottom;
  34122. data.object.near = this.near;
  34123. data.object.far = this.far;
  34124. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34125. return data;
  34126. }
  34127. }
  34128. /**
  34129. * Represents the shadow configuration of directional lights.
  34130. *
  34131. * @augments LightShadow
  34132. */
  34133. class DirectionalLightShadow extends LightShadow {
  34134. /**
  34135. * Constructs a new directional light shadow.
  34136. */
  34137. constructor() {
  34138. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34139. /**
  34140. * This flag can be used for type testing.
  34141. *
  34142. * @type {boolean}
  34143. * @readonly
  34144. * @default true
  34145. */
  34146. this.isDirectionalLightShadow = true;
  34147. }
  34148. }
  34149. /**
  34150. * A light that gets emitted in a specific direction. This light will behave
  34151. * as though it is infinitely far away and the rays produced from it are all
  34152. * parallel. The common use case for this is to simulate daylight; the sun is
  34153. * far enough away that its position can be considered to be infinite, and
  34154. * all light rays coming from it are parallel.
  34155. *
  34156. * A common point of confusion for directional lights is that setting the
  34157. * rotation has no effect. This is because three.js's DirectionalLight is the
  34158. * equivalent to what is often called a 'Target Direct Light' in other
  34159. * applications.
  34160. *
  34161. * This means that its direction is calculated as pointing from the light's
  34162. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34163. * (as opposed to a 'Free Direct Light' that just has a rotation
  34164. * component).
  34165. *
  34166. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34167. *
  34168. * ```js
  34169. * // White directional light at half intensity shining from the top.
  34170. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34171. * scene.add( directionalLight );
  34172. * ```
  34173. *
  34174. * @augments Light
  34175. */
  34176. class DirectionalLight extends Light {
  34177. /**
  34178. * Constructs a new directional light.
  34179. *
  34180. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34181. * @param {number} [intensity=1] - The light's strength/intensity.
  34182. */
  34183. constructor( color, intensity ) {
  34184. super( color, intensity );
  34185. /**
  34186. * This flag can be used for type testing.
  34187. *
  34188. * @type {boolean}
  34189. * @readonly
  34190. * @default true
  34191. */
  34192. this.isDirectionalLight = true;
  34193. this.type = 'DirectionalLight';
  34194. this.position.copy( Object3D.DEFAULT_UP );
  34195. this.updateMatrix();
  34196. /**
  34197. * The directional light points from its position to the
  34198. * target's position.
  34199. *
  34200. * For the target's position to be changed to anything other
  34201. * than the default, it must be added to the scene.
  34202. *
  34203. * It is also possible to set the target to be another 3D object
  34204. * in the scene. The light will now track the target object.
  34205. *
  34206. * @type {Object3D}
  34207. */
  34208. this.target = new Object3D();
  34209. /**
  34210. * This property holds the light's shadow configuration.
  34211. *
  34212. * @type {DirectionalLightShadow}
  34213. */
  34214. this.shadow = new DirectionalLightShadow();
  34215. }
  34216. dispose() {
  34217. super.dispose();
  34218. this.shadow.dispose();
  34219. }
  34220. copy( source ) {
  34221. super.copy( source );
  34222. this.target = source.target.clone();
  34223. this.shadow = source.shadow.clone();
  34224. return this;
  34225. }
  34226. toJSON( meta ) {
  34227. const data = super.toJSON( meta );
  34228. data.object.shadow = this.shadow.toJSON();
  34229. data.object.target = this.target.uuid;
  34230. return data;
  34231. }
  34232. }
  34233. /**
  34234. * This light globally illuminates all objects in the scene equally.
  34235. *
  34236. * It cannot be used to cast shadows as it does not have a direction.
  34237. *
  34238. * ```js
  34239. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34240. * scene.add( light );
  34241. * ```
  34242. *
  34243. * @augments Light
  34244. */
  34245. class AmbientLight extends Light {
  34246. /**
  34247. * Constructs a new ambient light.
  34248. *
  34249. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34250. * @param {number} [intensity=1] - The light's strength/intensity.
  34251. */
  34252. constructor( color, intensity ) {
  34253. super( color, intensity );
  34254. /**
  34255. * This flag can be used for type testing.
  34256. *
  34257. * @type {boolean}
  34258. * @readonly
  34259. * @default true
  34260. */
  34261. this.isAmbientLight = true;
  34262. this.type = 'AmbientLight';
  34263. }
  34264. }
  34265. /**
  34266. * This class emits light uniformly across the face a rectangular plane.
  34267. * This light type can be used to simulate light sources such as bright
  34268. * windows or strip lighting.
  34269. *
  34270. * Important Notes:
  34271. *
  34272. * - There is no shadow support.
  34273. * - Only PBR materials are supported.
  34274. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34275. * into your app and init the uniforms/textures.
  34276. *
  34277. * ```js
  34278. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34279. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34280. *
  34281. * const intensity = 1; const width = 10; const height = 10;
  34282. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34283. * rectLight.position.set( 5, 5, 0 );
  34284. * rectLight.lookAt( 0, 0, 0 );
  34285. * scene.add( rectLight )
  34286. * ```
  34287. *
  34288. * @augments Light
  34289. */
  34290. class RectAreaLight extends Light {
  34291. /**
  34292. * Constructs a new area light.
  34293. *
  34294. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34295. * @param {number} [intensity=1] - The light's strength/intensity.
  34296. * @param {number} [width=10] - The width of the light.
  34297. * @param {number} [height=10] - The height of the light.
  34298. */
  34299. constructor( color, intensity, width = 10, height = 10 ) {
  34300. super( color, intensity );
  34301. /**
  34302. * This flag can be used for type testing.
  34303. *
  34304. * @type {boolean}
  34305. * @readonly
  34306. * @default true
  34307. */
  34308. this.isRectAreaLight = true;
  34309. this.type = 'RectAreaLight';
  34310. /**
  34311. * The width of the light.
  34312. *
  34313. * @type {number}
  34314. * @default 10
  34315. */
  34316. this.width = width;
  34317. /**
  34318. * The height of the light.
  34319. *
  34320. * @type {number}
  34321. * @default 10
  34322. */
  34323. this.height = height;
  34324. }
  34325. /**
  34326. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34327. * Changing the power will also change the light's intensity.
  34328. *
  34329. * @type {number}
  34330. */
  34331. get power() {
  34332. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34333. return this.intensity * this.width * this.height * Math.PI;
  34334. }
  34335. set power( power ) {
  34336. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34337. this.intensity = power / ( this.width * this.height * Math.PI );
  34338. }
  34339. copy( source ) {
  34340. super.copy( source );
  34341. this.width = source.width;
  34342. this.height = source.height;
  34343. return this;
  34344. }
  34345. toJSON( meta ) {
  34346. const data = super.toJSON( meta );
  34347. data.object.width = this.width;
  34348. data.object.height = this.height;
  34349. return data;
  34350. }
  34351. }
  34352. /**
  34353. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34354. * to encode lighting information.
  34355. *
  34356. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34357. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34358. */
  34359. class SphericalHarmonics3 {
  34360. /**
  34361. * Constructs a new spherical harmonics.
  34362. */
  34363. constructor() {
  34364. /**
  34365. * This flag can be used for type testing.
  34366. *
  34367. * @type {boolean}
  34368. * @readonly
  34369. * @default true
  34370. */
  34371. this.isSphericalHarmonics3 = true;
  34372. /**
  34373. * An array holding the (9) SH coefficients.
  34374. *
  34375. * @type {Array<Vector3>}
  34376. */
  34377. this.coefficients = [];
  34378. for ( let i = 0; i < 9; i ++ ) {
  34379. this.coefficients.push( new Vector3() );
  34380. }
  34381. }
  34382. /**
  34383. * Sets the given SH coefficients to this instance by copying
  34384. * the values.
  34385. *
  34386. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34387. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34388. */
  34389. set( coefficients ) {
  34390. for ( let i = 0; i < 9; i ++ ) {
  34391. this.coefficients[ i ].copy( coefficients[ i ] );
  34392. }
  34393. return this;
  34394. }
  34395. /**
  34396. * Sets all SH coefficients to `0`.
  34397. *
  34398. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34399. */
  34400. zero() {
  34401. for ( let i = 0; i < 9; i ++ ) {
  34402. this.coefficients[ i ].set( 0, 0, 0 );
  34403. }
  34404. return this;
  34405. }
  34406. /**
  34407. * Returns the radiance in the direction of the given normal.
  34408. *
  34409. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34410. * @param {Vector3} target - The target vector that is used to store the method's result.
  34411. * @return {Vector3} The radiance.
  34412. */
  34413. getAt( normal, target ) {
  34414. // normal is assumed to be unit length
  34415. const x = normal.x, y = normal.y, z = normal.z;
  34416. const coeff = this.coefficients;
  34417. // band 0
  34418. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34419. // band 1
  34420. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34421. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34422. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34423. // band 2
  34424. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34425. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34426. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34427. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34428. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34429. return target;
  34430. }
  34431. /**
  34432. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34433. * direction of the given normal.
  34434. *
  34435. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34436. * @param {Vector3} target - The target vector that is used to store the method's result.
  34437. * @return {Vector3} The irradiance.
  34438. */
  34439. getIrradianceAt( normal, target ) {
  34440. // normal is assumed to be unit length
  34441. const x = normal.x, y = normal.y, z = normal.z;
  34442. const coeff = this.coefficients;
  34443. // band 0
  34444. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34445. // band 1
  34446. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34447. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34448. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34449. // band 2
  34450. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34451. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34452. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34453. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34454. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34455. return target;
  34456. }
  34457. /**
  34458. * Adds the given SH to this instance.
  34459. *
  34460. * @param {SphericalHarmonics3} sh - The SH to add.
  34461. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34462. */
  34463. add( sh ) {
  34464. for ( let i = 0; i < 9; i ++ ) {
  34465. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34466. }
  34467. return this;
  34468. }
  34469. /**
  34470. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34471. * {@link SphericalHarmonics3#scale} at once.
  34472. *
  34473. * @param {SphericalHarmonics3} sh - The SH to add.
  34474. * @param {number} s - The scale factor.
  34475. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34476. */
  34477. addScaledSH( sh, s ) {
  34478. for ( let i = 0; i < 9; i ++ ) {
  34479. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34480. }
  34481. return this;
  34482. }
  34483. /**
  34484. * Scales this SH by the given scale factor.
  34485. *
  34486. * @param {number} s - The scale factor.
  34487. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34488. */
  34489. scale( s ) {
  34490. for ( let i = 0; i < 9; i ++ ) {
  34491. this.coefficients[ i ].multiplyScalar( s );
  34492. }
  34493. return this;
  34494. }
  34495. /**
  34496. * Linear interpolates between the given SH and this instance by the given
  34497. * alpha factor.
  34498. *
  34499. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34500. * @param {number} alpha - The alpha factor.
  34501. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34502. */
  34503. lerp( sh, alpha ) {
  34504. for ( let i = 0; i < 9; i ++ ) {
  34505. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34506. }
  34507. return this;
  34508. }
  34509. /**
  34510. * Returns `true` if this spherical harmonics is equal with the given one.
  34511. *
  34512. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34513. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34514. */
  34515. equals( sh ) {
  34516. for ( let i = 0; i < 9; i ++ ) {
  34517. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34518. return false;
  34519. }
  34520. }
  34521. return true;
  34522. }
  34523. /**
  34524. * Copies the values of the given spherical harmonics to this instance.
  34525. *
  34526. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34527. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34528. */
  34529. copy( sh ) {
  34530. return this.set( sh.coefficients );
  34531. }
  34532. /**
  34533. * Returns a new spherical harmonics with copied values from this instance.
  34534. *
  34535. * @return {SphericalHarmonics3} A clone of this instance.
  34536. */
  34537. clone() {
  34538. return new this.constructor().copy( this );
  34539. }
  34540. /**
  34541. * Sets the SH coefficients of this instance from the given array.
  34542. *
  34543. * @param {Array<number>} array - An array holding the SH coefficients.
  34544. * @param {number} [offset=0] - The array offset where to start copying.
  34545. * @return {SphericalHarmonics3} A clone of this instance.
  34546. */
  34547. fromArray( array, offset = 0 ) {
  34548. const coefficients = this.coefficients;
  34549. for ( let i = 0; i < 9; i ++ ) {
  34550. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34551. }
  34552. return this;
  34553. }
  34554. /**
  34555. * Returns an array with the SH coefficients, or copies them into the provided
  34556. * array. The coefficients are represented as numbers.
  34557. *
  34558. * @param {Array<number>} [array=[]] - The target array.
  34559. * @param {number} [offset=0] - The array offset where to start copying.
  34560. * @return {Array<number>} An array with flat SH coefficients.
  34561. */
  34562. toArray( array = [], offset = 0 ) {
  34563. const coefficients = this.coefficients;
  34564. for ( let i = 0; i < 9; i ++ ) {
  34565. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34566. }
  34567. return array;
  34568. }
  34569. /**
  34570. * Computes the SH basis for the given normal vector.
  34571. *
  34572. * @param {Vector3} normal - The normal.
  34573. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34574. */
  34575. static getBasisAt( normal, shBasis ) {
  34576. // normal is assumed to be unit length
  34577. const x = normal.x, y = normal.y, z = normal.z;
  34578. // band 0
  34579. shBasis[ 0 ] = 0.282095;
  34580. // band 1
  34581. shBasis[ 1 ] = 0.488603 * y;
  34582. shBasis[ 2 ] = 0.488603 * z;
  34583. shBasis[ 3 ] = 0.488603 * x;
  34584. // band 2
  34585. shBasis[ 4 ] = 1.092548 * x * y;
  34586. shBasis[ 5 ] = 1.092548 * y * z;
  34587. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34588. shBasis[ 7 ] = 1.092548 * x * z;
  34589. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34590. }
  34591. }
  34592. /**
  34593. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34594. * classical light sources (e.g. directional, point or spot lights), light
  34595. * probes do not emit light. Instead they store information about light
  34596. * passing through 3D space. During rendering, the light that hits a 3D
  34597. * object is approximated by using the data from the light probe.
  34598. *
  34599. * Light probes are usually created from (radiance) environment maps. The
  34600. * class {@link LightProbeGenerator} can be used to create light probes from
  34601. * cube textures or render targets. However, light estimation data could also
  34602. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34603. * augmented reality content that reacts to real world lighting.
  34604. *
  34605. * The current probe implementation in three.js supports so-called diffuse
  34606. * light probes. This type of light probe is functionally equivalent to an
  34607. * irradiance environment map.
  34608. *
  34609. * @augments Light
  34610. */
  34611. class LightProbe extends Light {
  34612. /**
  34613. * Constructs a new light probe.
  34614. *
  34615. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34616. * @param {number} [intensity=1] - The light's strength/intensity.
  34617. */
  34618. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34619. super( undefined, intensity );
  34620. /**
  34621. * This flag can be used for type testing.
  34622. *
  34623. * @type {boolean}
  34624. * @readonly
  34625. * @default true
  34626. */
  34627. this.isLightProbe = true;
  34628. /**
  34629. * A light probe uses spherical harmonics to encode lighting information.
  34630. *
  34631. * @type {SphericalHarmonics3}
  34632. */
  34633. this.sh = sh;
  34634. }
  34635. copy( source ) {
  34636. super.copy( source );
  34637. this.sh.copy( source.sh );
  34638. return this;
  34639. }
  34640. toJSON( meta ) {
  34641. const data = super.toJSON( meta );
  34642. data.object.sh = this.sh.toArray();
  34643. return data;
  34644. }
  34645. }
  34646. /**
  34647. * Class for loading materials. The files are internally
  34648. * loaded via {@link FileLoader}.
  34649. *
  34650. * ```js
  34651. * const loader = new THREE.MaterialLoader();
  34652. * const material = await loader.loadAsync( 'material.json' );
  34653. * ```
  34654. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34655. *
  34656. * @augments Loader
  34657. */
  34658. class MaterialLoader extends Loader {
  34659. /**
  34660. * Constructs a new material loader.
  34661. *
  34662. * @param {LoadingManager} [manager] - The loading manager.
  34663. */
  34664. constructor( manager ) {
  34665. super( manager );
  34666. /**
  34667. * A dictionary holding textures used by the material.
  34668. *
  34669. * @type {Object<string,Texture>}
  34670. */
  34671. this.textures = {};
  34672. }
  34673. /**
  34674. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34675. *
  34676. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34677. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34678. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34679. * @param {onErrorCallback} onError - Executed when errors occur.
  34680. */
  34681. load( url, onLoad, onProgress, onError ) {
  34682. const scope = this;
  34683. const loader = new FileLoader( scope.manager );
  34684. loader.setPath( scope.path );
  34685. loader.setRequestHeader( scope.requestHeader );
  34686. loader.setWithCredentials( scope.withCredentials );
  34687. loader.load( url, function ( text ) {
  34688. try {
  34689. onLoad( scope.parse( JSON.parse( text ) ) );
  34690. } catch ( e ) {
  34691. if ( onError ) {
  34692. onError( e );
  34693. } else {
  34694. error( e );
  34695. }
  34696. scope.manager.itemError( url );
  34697. }
  34698. }, onProgress, onError );
  34699. }
  34700. /**
  34701. * Parses the given JSON object and returns a material.
  34702. *
  34703. * @param {Object} json - The serialized material.
  34704. * @return {Material} The parsed material.
  34705. */
  34706. parse( json ) {
  34707. const textures = this.textures;
  34708. function getTexture( name ) {
  34709. if ( textures[ name ] === undefined ) {
  34710. warn( 'MaterialLoader: Undefined texture', name );
  34711. }
  34712. return textures[ name ];
  34713. }
  34714. const material = this.createMaterialFromType( json.type );
  34715. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34716. if ( json.name !== undefined ) material.name = json.name;
  34717. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34718. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34719. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34720. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34721. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34722. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34723. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34724. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34725. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34726. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34727. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34728. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34729. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34730. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34731. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34732. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34733. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34734. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34735. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34736. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34737. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34738. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34739. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34740. if ( json.fog !== undefined ) material.fog = json.fog;
  34741. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34742. if ( json.blending !== undefined ) material.blending = json.blending;
  34743. if ( json.combine !== undefined ) material.combine = json.combine;
  34744. if ( json.side !== undefined ) material.side = json.side;
  34745. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34746. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34747. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34748. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34749. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34750. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34751. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34752. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34753. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34754. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34755. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34756. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34757. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34758. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34759. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34760. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34761. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34762. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34763. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34764. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34765. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34766. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34767. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34768. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34769. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34770. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34771. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34772. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34773. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34774. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34775. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34776. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34777. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34778. if ( json.scale !== undefined ) material.scale = json.scale;
  34779. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34780. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34781. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34782. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34783. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34784. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34785. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34786. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  34787. if ( json.visible !== undefined ) material.visible = json.visible;
  34788. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34789. if ( json.userData !== undefined ) material.userData = json.userData;
  34790. if ( json.vertexColors !== undefined ) {
  34791. if ( typeof json.vertexColors === 'number' ) {
  34792. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34793. } else {
  34794. material.vertexColors = json.vertexColors;
  34795. }
  34796. }
  34797. // Shader Material
  34798. if ( json.uniforms !== undefined ) {
  34799. for ( const name in json.uniforms ) {
  34800. const uniform = json.uniforms[ name ];
  34801. material.uniforms[ name ] = {};
  34802. switch ( uniform.type ) {
  34803. case 't':
  34804. material.uniforms[ name ].value = getTexture( uniform.value );
  34805. break;
  34806. case 'c':
  34807. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34808. break;
  34809. case 'v2':
  34810. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34811. break;
  34812. case 'v3':
  34813. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34814. break;
  34815. case 'v4':
  34816. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34817. break;
  34818. case 'm3':
  34819. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34820. break;
  34821. case 'm4':
  34822. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34823. break;
  34824. default:
  34825. material.uniforms[ name ].value = uniform.value;
  34826. }
  34827. }
  34828. }
  34829. if ( json.defines !== undefined ) material.defines = json.defines;
  34830. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34831. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34832. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34833. if ( json.extensions !== undefined ) {
  34834. for ( const key in json.extensions ) {
  34835. material.extensions[ key ] = json.extensions[ key ];
  34836. }
  34837. }
  34838. if ( json.lights !== undefined ) material.lights = json.lights;
  34839. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34840. // for PointsMaterial
  34841. if ( json.size !== undefined ) material.size = json.size;
  34842. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34843. // maps
  34844. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34845. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34846. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34847. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34848. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34849. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34850. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34851. if ( json.normalScale !== undefined ) {
  34852. let normalScale = json.normalScale;
  34853. if ( Array.isArray( normalScale ) === false ) {
  34854. // Blender exporter used to export a scalar. See #7459
  34855. normalScale = [ normalScale, normalScale ];
  34856. }
  34857. material.normalScale = new Vector2().fromArray( normalScale );
  34858. }
  34859. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34860. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34861. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34862. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34863. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34864. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34865. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34866. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34867. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34868. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34869. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34870. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34871. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34872. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34873. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34874. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34875. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34876. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34877. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34878. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34879. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34880. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34881. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34882. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34883. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34884. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34885. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34886. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34887. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34888. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34889. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34890. return material;
  34891. }
  34892. /**
  34893. * Textures are not embedded in the material JSON so they have
  34894. * to be injected before the loading process starts.
  34895. *
  34896. * @param {Object} value - A dictionary holding textures for material properties.
  34897. * @return {MaterialLoader} A reference to this material loader.
  34898. */
  34899. setTextures( value ) {
  34900. this.textures = value;
  34901. return this;
  34902. }
  34903. /**
  34904. * Creates a material for the given type.
  34905. *
  34906. * @param {string} type - The material type.
  34907. * @return {Material} The new material.
  34908. */
  34909. createMaterialFromType( type ) {
  34910. return MaterialLoader.createMaterialFromType( type );
  34911. }
  34912. /**
  34913. * Creates a material for the given type.
  34914. *
  34915. * @static
  34916. * @param {string} type - The material type.
  34917. * @return {Material} The new material.
  34918. */
  34919. static createMaterialFromType( type ) {
  34920. const materialLib = {
  34921. ShadowMaterial,
  34922. SpriteMaterial,
  34923. RawShaderMaterial,
  34924. ShaderMaterial,
  34925. PointsMaterial,
  34926. MeshPhysicalMaterial,
  34927. MeshStandardMaterial,
  34928. MeshPhongMaterial,
  34929. MeshToonMaterial,
  34930. MeshNormalMaterial,
  34931. MeshLambertMaterial,
  34932. MeshDepthMaterial,
  34933. MeshDistanceMaterial,
  34934. MeshBasicMaterial,
  34935. MeshMatcapMaterial,
  34936. LineDashedMaterial,
  34937. LineBasicMaterial,
  34938. Material
  34939. };
  34940. return new materialLib[ type ]();
  34941. }
  34942. }
  34943. /**
  34944. * A class with loader utility functions.
  34945. */
  34946. class LoaderUtils {
  34947. /**
  34948. * Extracts the base URL from the given URL.
  34949. *
  34950. * @param {string} url -The URL to extract the base URL from.
  34951. * @return {string} The extracted base URL.
  34952. */
  34953. static extractUrlBase( url ) {
  34954. const index = url.lastIndexOf( '/' );
  34955. if ( index === -1 ) return './';
  34956. return url.slice( 0, index + 1 );
  34957. }
  34958. /**
  34959. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34960. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34961. * string.
  34962. *
  34963. * @param {string} url -The URL to resolve.
  34964. * @param {string} path - The base path for relative URLs to be resolved against.
  34965. * @return {string} The resolved URL.
  34966. */
  34967. static resolveURL( url, path ) {
  34968. // Invalid URL
  34969. if ( typeof url !== 'string' || url === '' ) return '';
  34970. // Host Relative URL
  34971. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34972. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34973. }
  34974. // Absolute URL http://,https://,//
  34975. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34976. // Data URI
  34977. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34978. // Blob URL
  34979. if ( /^blob:.*$/i.test( url ) ) return url;
  34980. // Relative URL
  34981. return path + url;
  34982. }
  34983. }
  34984. /**
  34985. * An instanced version of a geometry.
  34986. */
  34987. class InstancedBufferGeometry extends BufferGeometry {
  34988. /**
  34989. * Constructs a new instanced buffer geometry.
  34990. */
  34991. constructor() {
  34992. super();
  34993. /**
  34994. * This flag can be used for type testing.
  34995. *
  34996. * @type {boolean}
  34997. * @readonly
  34998. * @default true
  34999. */
  35000. this.isInstancedBufferGeometry = true;
  35001. this.type = 'InstancedBufferGeometry';
  35002. /**
  35003. * The instance count.
  35004. *
  35005. * @type {number}
  35006. * @default Infinity
  35007. */
  35008. this.instanceCount = Infinity;
  35009. }
  35010. copy( source ) {
  35011. super.copy( source );
  35012. this.instanceCount = source.instanceCount;
  35013. return this;
  35014. }
  35015. toJSON() {
  35016. const data = super.toJSON();
  35017. data.instanceCount = this.instanceCount;
  35018. data.isInstancedBufferGeometry = true;
  35019. return data;
  35020. }
  35021. }
  35022. /**
  35023. * Class for loading geometries. The files are internally
  35024. * loaded via {@link FileLoader}.
  35025. *
  35026. * ```js
  35027. * const loader = new THREE.BufferGeometryLoader();
  35028. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  35029. *
  35030. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  35031. * const object = new THREE.Mesh( geometry, material );
  35032. * scene.add( object );
  35033. * ```
  35034. *
  35035. * @augments Loader
  35036. */
  35037. class BufferGeometryLoader extends Loader {
  35038. /**
  35039. * Constructs a new geometry loader.
  35040. *
  35041. * @param {LoadingManager} [manager] - The loading manager.
  35042. */
  35043. constructor( manager ) {
  35044. super( manager );
  35045. }
  35046. /**
  35047. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  35048. *
  35049. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35050. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  35051. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35052. * @param {onErrorCallback} onError - Executed when errors occur.
  35053. */
  35054. load( url, onLoad, onProgress, onError ) {
  35055. const scope = this;
  35056. const loader = new FileLoader( scope.manager );
  35057. loader.setPath( scope.path );
  35058. loader.setRequestHeader( scope.requestHeader );
  35059. loader.setWithCredentials( scope.withCredentials );
  35060. loader.load( url, function ( text ) {
  35061. try {
  35062. onLoad( scope.parse( JSON.parse( text ) ) );
  35063. } catch ( e ) {
  35064. if ( onError ) {
  35065. onError( e );
  35066. } else {
  35067. error( e );
  35068. }
  35069. scope.manager.itemError( url );
  35070. }
  35071. }, onProgress, onError );
  35072. }
  35073. /**
  35074. * Parses the given JSON object and returns a geometry.
  35075. *
  35076. * @param {Object} json - The serialized geometry.
  35077. * @return {BufferGeometry} The parsed geometry.
  35078. */
  35079. parse( json ) {
  35080. const interleavedBufferMap = {};
  35081. const arrayBufferMap = {};
  35082. function getInterleavedBuffer( json, uuid ) {
  35083. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  35084. const interleavedBuffers = json.interleavedBuffers;
  35085. const interleavedBuffer = interleavedBuffers[ uuid ];
  35086. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  35087. const array = getTypedArray( interleavedBuffer.type, buffer );
  35088. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  35089. ib.uuid = interleavedBuffer.uuid;
  35090. interleavedBufferMap[ uuid ] = ib;
  35091. return ib;
  35092. }
  35093. function getArrayBuffer( json, uuid ) {
  35094. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  35095. const arrayBuffers = json.arrayBuffers;
  35096. const arrayBuffer = arrayBuffers[ uuid ];
  35097. const ab = new Uint32Array( arrayBuffer ).buffer;
  35098. arrayBufferMap[ uuid ] = ab;
  35099. return ab;
  35100. }
  35101. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35102. const index = json.data.index;
  35103. if ( index !== undefined ) {
  35104. const typedArray = getTypedArray( index.type, index.array );
  35105. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35106. }
  35107. const attributes = json.data.attributes;
  35108. for ( const key in attributes ) {
  35109. const attribute = attributes[ key ];
  35110. let bufferAttribute;
  35111. if ( attribute.isInterleavedBufferAttribute ) {
  35112. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35113. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35114. } else {
  35115. const typedArray = getTypedArray( attribute.type, attribute.array );
  35116. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35117. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35118. }
  35119. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35120. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35121. geometry.setAttribute( key, bufferAttribute );
  35122. }
  35123. const morphAttributes = json.data.morphAttributes;
  35124. if ( morphAttributes ) {
  35125. for ( const key in morphAttributes ) {
  35126. const attributeArray = morphAttributes[ key ];
  35127. const array = [];
  35128. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35129. const attribute = attributeArray[ i ];
  35130. let bufferAttribute;
  35131. if ( attribute.isInterleavedBufferAttribute ) {
  35132. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35133. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35134. } else {
  35135. const typedArray = getTypedArray( attribute.type, attribute.array );
  35136. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35137. }
  35138. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35139. array.push( bufferAttribute );
  35140. }
  35141. geometry.morphAttributes[ key ] = array;
  35142. }
  35143. }
  35144. const morphTargetsRelative = json.data.morphTargetsRelative;
  35145. if ( morphTargetsRelative ) {
  35146. geometry.morphTargetsRelative = true;
  35147. }
  35148. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35149. if ( groups !== undefined ) {
  35150. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35151. const group = groups[ i ];
  35152. geometry.addGroup( group.start, group.count, group.materialIndex );
  35153. }
  35154. }
  35155. const boundingSphere = json.data.boundingSphere;
  35156. if ( boundingSphere !== undefined ) {
  35157. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35158. }
  35159. if ( json.name ) geometry.name = json.name;
  35160. if ( json.userData ) geometry.userData = json.userData;
  35161. return geometry;
  35162. }
  35163. }
  35164. /**
  35165. * A loader for loading a JSON resource in the [JSON Object/Scene format](https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4).
  35166. * The files are internally loaded via {@link FileLoader}.
  35167. *
  35168. * ```js
  35169. * const loader = new THREE.ObjectLoader();
  35170. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35171. * scene.add( obj );
  35172. *
  35173. * // Alternatively, to parse a previously loaded JSON structure
  35174. * const object = await loader.parseAsync( a_json_object );
  35175. * scene.add( object );
  35176. * ```
  35177. *
  35178. * @augments Loader
  35179. */
  35180. class ObjectLoader extends Loader {
  35181. /**
  35182. * Constructs a new object loader.
  35183. *
  35184. * @param {LoadingManager} [manager] - The loading manager.
  35185. */
  35186. constructor( manager ) {
  35187. super( manager );
  35188. }
  35189. /**
  35190. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35191. *
  35192. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35193. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35194. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35195. * @param {onErrorCallback} onError - Executed when errors occur.
  35196. */
  35197. load( url, onLoad, onProgress, onError ) {
  35198. const scope = this;
  35199. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35200. this.resourcePath = this.resourcePath || path;
  35201. const loader = new FileLoader( this.manager );
  35202. loader.setPath( this.path );
  35203. loader.setRequestHeader( this.requestHeader );
  35204. loader.setWithCredentials( this.withCredentials );
  35205. loader.load( url, function ( text ) {
  35206. let json = null;
  35207. try {
  35208. json = JSON.parse( text );
  35209. } catch ( error ) {
  35210. if ( onError !== undefined ) onError( error );
  35211. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  35212. return;
  35213. }
  35214. const metadata = json.metadata;
  35215. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35216. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35217. error( 'ObjectLoader: Can\'t load ' + url );
  35218. return;
  35219. }
  35220. scope.parse( json, onLoad );
  35221. }, onProgress, onError );
  35222. }
  35223. /**
  35224. * Async version of {@link ObjectLoader#load}.
  35225. *
  35226. * @async
  35227. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35228. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35229. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35230. */
  35231. async loadAsync( url, onProgress ) {
  35232. const scope = this;
  35233. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35234. this.resourcePath = this.resourcePath || path;
  35235. const loader = new FileLoader( this.manager );
  35236. loader.setPath( this.path );
  35237. loader.setRequestHeader( this.requestHeader );
  35238. loader.setWithCredentials( this.withCredentials );
  35239. const text = await loader.loadAsync( url, onProgress );
  35240. let json;
  35241. try {
  35242. json = JSON.parse( text );
  35243. } catch ( e ) {
  35244. throw new Error( 'ObjectLoader: Can\'t parse ' + url + '. ' + e.message );
  35245. }
  35246. const metadata = json.metadata;
  35247. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35248. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35249. }
  35250. return await scope.parseAsync( json );
  35251. }
  35252. /**
  35253. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35254. * but can also be used directly to parse a previously loaded JSON structure.
  35255. *
  35256. * @param {Object} json - The serialized 3D object.
  35257. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35258. * @return {Object3D} The parsed 3D object.
  35259. */
  35260. parse( json, onLoad ) {
  35261. const animations = this.parseAnimations( json.animations );
  35262. const shapes = this.parseShapes( json.shapes );
  35263. const geometries = this.parseGeometries( json.geometries, shapes );
  35264. const images = this.parseImages( json.images, function () {
  35265. if ( onLoad !== undefined ) onLoad( object );
  35266. } );
  35267. const textures = this.parseTextures( json.textures, images );
  35268. const materials = this.parseMaterials( json.materials, textures );
  35269. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35270. const skeletons = this.parseSkeletons( json.skeletons, object );
  35271. this.bindSkeletons( object, skeletons );
  35272. this.bindLightTargets( object );
  35273. //
  35274. if ( onLoad !== undefined ) {
  35275. let hasImages = false;
  35276. for ( const uuid in images ) {
  35277. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35278. hasImages = true;
  35279. break;
  35280. }
  35281. }
  35282. if ( hasImages === false ) onLoad( object );
  35283. }
  35284. return object;
  35285. }
  35286. /**
  35287. * Async version of {@link ObjectLoader#parse}.
  35288. *
  35289. * @param {Object} json - The serialized 3D object.
  35290. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35291. */
  35292. async parseAsync( json ) {
  35293. const animations = this.parseAnimations( json.animations );
  35294. const shapes = this.parseShapes( json.shapes );
  35295. const geometries = this.parseGeometries( json.geometries, shapes );
  35296. const images = await this.parseImagesAsync( json.images );
  35297. const textures = this.parseTextures( json.textures, images );
  35298. const materials = this.parseMaterials( json.materials, textures );
  35299. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35300. const skeletons = this.parseSkeletons( json.skeletons, object );
  35301. this.bindSkeletons( object, skeletons );
  35302. this.bindLightTargets( object );
  35303. return object;
  35304. }
  35305. // internals
  35306. parseShapes( json ) {
  35307. const shapes = {};
  35308. if ( json !== undefined ) {
  35309. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35310. const shape = new Shape().fromJSON( json[ i ] );
  35311. shapes[ shape.uuid ] = shape;
  35312. }
  35313. }
  35314. return shapes;
  35315. }
  35316. parseSkeletons( json, object ) {
  35317. const skeletons = {};
  35318. const bones = {};
  35319. // generate bone lookup table
  35320. object.traverse( function ( child ) {
  35321. if ( child.isBone ) bones[ child.uuid ] = child;
  35322. } );
  35323. // create skeletons
  35324. if ( json !== undefined ) {
  35325. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35326. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35327. skeletons[ skeleton.uuid ] = skeleton;
  35328. }
  35329. }
  35330. return skeletons;
  35331. }
  35332. parseGeometries( json, shapes ) {
  35333. const geometries = {};
  35334. if ( json !== undefined ) {
  35335. const bufferGeometryLoader = new BufferGeometryLoader();
  35336. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35337. let geometry;
  35338. const data = json[ i ];
  35339. switch ( data.type ) {
  35340. case 'BufferGeometry':
  35341. case 'InstancedBufferGeometry':
  35342. geometry = bufferGeometryLoader.parse( data );
  35343. break;
  35344. default:
  35345. if ( data.type in Geometries ) {
  35346. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35347. } else {
  35348. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35349. }
  35350. }
  35351. geometry.uuid = data.uuid;
  35352. if ( data.name !== undefined ) geometry.name = data.name;
  35353. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35354. geometries[ data.uuid ] = geometry;
  35355. }
  35356. }
  35357. return geometries;
  35358. }
  35359. parseMaterials( json, textures ) {
  35360. const cache = {}; // MultiMaterial
  35361. const materials = {};
  35362. if ( json !== undefined ) {
  35363. const loader = new MaterialLoader();
  35364. loader.setTextures( textures );
  35365. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35366. const data = json[ i ];
  35367. if ( cache[ data.uuid ] === undefined ) {
  35368. cache[ data.uuid ] = loader.parse( data );
  35369. }
  35370. materials[ data.uuid ] = cache[ data.uuid ];
  35371. }
  35372. }
  35373. return materials;
  35374. }
  35375. parseAnimations( json ) {
  35376. const animations = {};
  35377. if ( json !== undefined ) {
  35378. for ( let i = 0; i < json.length; i ++ ) {
  35379. const data = json[ i ];
  35380. const clip = AnimationClip.parse( data );
  35381. animations[ clip.uuid ] = clip;
  35382. }
  35383. }
  35384. return animations;
  35385. }
  35386. parseImages( json, onLoad ) {
  35387. const scope = this;
  35388. const images = {};
  35389. let loader;
  35390. function loadImage( url ) {
  35391. scope.manager.itemStart( url );
  35392. return loader.load( url, function () {
  35393. scope.manager.itemEnd( url );
  35394. }, undefined, function () {
  35395. scope.manager.itemError( url );
  35396. scope.manager.itemEnd( url );
  35397. } );
  35398. }
  35399. function deserializeImage( image ) {
  35400. if ( typeof image === 'string' ) {
  35401. const url = image;
  35402. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35403. return loadImage( path );
  35404. } else {
  35405. if ( image.data ) {
  35406. return {
  35407. data: getTypedArray( image.type, image.data ),
  35408. width: image.width,
  35409. height: image.height
  35410. };
  35411. } else {
  35412. return null;
  35413. }
  35414. }
  35415. }
  35416. if ( json !== undefined && json.length > 0 ) {
  35417. const manager = new LoadingManager( onLoad );
  35418. loader = new ImageLoader( manager );
  35419. loader.setCrossOrigin( this.crossOrigin );
  35420. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35421. const image = json[ i ];
  35422. const url = image.url;
  35423. if ( Array.isArray( url ) ) {
  35424. // load array of images e.g CubeTexture
  35425. const imageArray = [];
  35426. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35427. const currentUrl = url[ j ];
  35428. const deserializedImage = deserializeImage( currentUrl );
  35429. if ( deserializedImage !== null ) {
  35430. if ( deserializedImage instanceof HTMLImageElement ) {
  35431. imageArray.push( deserializedImage );
  35432. } else {
  35433. // special case: handle array of data textures for cube textures
  35434. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35435. }
  35436. }
  35437. }
  35438. images[ image.uuid ] = new Source( imageArray );
  35439. } else {
  35440. // load single image
  35441. const deserializedImage = deserializeImage( image.url );
  35442. images[ image.uuid ] = new Source( deserializedImage );
  35443. }
  35444. }
  35445. }
  35446. return images;
  35447. }
  35448. async parseImagesAsync( json ) {
  35449. const scope = this;
  35450. const images = {};
  35451. let loader;
  35452. async function deserializeImage( image ) {
  35453. if ( typeof image === 'string' ) {
  35454. const url = image;
  35455. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35456. return await loader.loadAsync( path );
  35457. } else {
  35458. if ( image.data ) {
  35459. return {
  35460. data: getTypedArray( image.type, image.data ),
  35461. width: image.width,
  35462. height: image.height
  35463. };
  35464. } else {
  35465. return null;
  35466. }
  35467. }
  35468. }
  35469. if ( json !== undefined && json.length > 0 ) {
  35470. loader = new ImageLoader( this.manager );
  35471. loader.setCrossOrigin( this.crossOrigin );
  35472. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35473. const image = json[ i ];
  35474. const url = image.url;
  35475. if ( Array.isArray( url ) ) {
  35476. // load array of images e.g CubeTexture
  35477. const imageArray = [];
  35478. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35479. const currentUrl = url[ j ];
  35480. const deserializedImage = await deserializeImage( currentUrl );
  35481. if ( deserializedImage !== null ) {
  35482. if ( deserializedImage instanceof HTMLImageElement ) {
  35483. imageArray.push( deserializedImage );
  35484. } else {
  35485. // special case: handle array of data textures for cube textures
  35486. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35487. }
  35488. }
  35489. }
  35490. images[ image.uuid ] = new Source( imageArray );
  35491. } else {
  35492. // load single image
  35493. const deserializedImage = await deserializeImage( image.url );
  35494. images[ image.uuid ] = new Source( deserializedImage );
  35495. }
  35496. }
  35497. }
  35498. return images;
  35499. }
  35500. parseTextures( json, images ) {
  35501. function parseConstant( value, type ) {
  35502. if ( typeof value === 'number' ) return value;
  35503. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35504. return type[ value ];
  35505. }
  35506. const textures = {};
  35507. if ( json !== undefined ) {
  35508. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35509. const data = json[ i ];
  35510. if ( data.image === undefined ) {
  35511. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35512. }
  35513. if ( images[ data.image ] === undefined ) {
  35514. warn( 'ObjectLoader: Undefined image', data.image );
  35515. }
  35516. const source = images[ data.image ];
  35517. const image = source.data;
  35518. let texture;
  35519. if ( Array.isArray( image ) ) {
  35520. texture = new CubeTexture();
  35521. if ( image.length === 6 ) texture.needsUpdate = true;
  35522. } else {
  35523. if ( image && image.data ) {
  35524. texture = new DataTexture();
  35525. } else {
  35526. texture = new Texture();
  35527. }
  35528. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35529. }
  35530. texture.source = source;
  35531. texture.uuid = data.uuid;
  35532. if ( data.name !== undefined ) texture.name = data.name;
  35533. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35534. if ( data.channel !== undefined ) texture.channel = data.channel;
  35535. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35536. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35537. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35538. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35539. if ( data.wrap !== undefined ) {
  35540. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35541. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35542. }
  35543. if ( data.format !== undefined ) texture.format = data.format;
  35544. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35545. if ( data.type !== undefined ) texture.type = data.type;
  35546. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35547. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35548. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35549. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35550. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35551. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35552. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35553. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35554. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35555. if ( data.userData !== undefined ) texture.userData = data.userData;
  35556. textures[ data.uuid ] = texture;
  35557. }
  35558. }
  35559. return textures;
  35560. }
  35561. parseObject( data, geometries, materials, textures, animations ) {
  35562. let object;
  35563. function getGeometry( name ) {
  35564. if ( geometries[ name ] === undefined ) {
  35565. warn( 'ObjectLoader: Undefined geometry', name );
  35566. }
  35567. return geometries[ name ];
  35568. }
  35569. function getMaterial( name ) {
  35570. if ( name === undefined ) return undefined;
  35571. if ( Array.isArray( name ) ) {
  35572. const array = [];
  35573. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35574. const uuid = name[ i ];
  35575. if ( materials[ uuid ] === undefined ) {
  35576. warn( 'ObjectLoader: Undefined material', uuid );
  35577. }
  35578. array.push( materials[ uuid ] );
  35579. }
  35580. return array;
  35581. }
  35582. if ( materials[ name ] === undefined ) {
  35583. warn( 'ObjectLoader: Undefined material', name );
  35584. }
  35585. return materials[ name ];
  35586. }
  35587. function getTexture( uuid ) {
  35588. if ( textures[ uuid ] === undefined ) {
  35589. warn( 'ObjectLoader: Undefined texture', uuid );
  35590. }
  35591. return textures[ uuid ];
  35592. }
  35593. let geometry, material;
  35594. switch ( data.type ) {
  35595. case 'Scene':
  35596. object = new Scene();
  35597. if ( data.background !== undefined ) {
  35598. if ( Number.isInteger( data.background ) ) {
  35599. object.background = new Color( data.background );
  35600. } else {
  35601. object.background = getTexture( data.background );
  35602. }
  35603. }
  35604. if ( data.environment !== undefined ) {
  35605. object.environment = getTexture( data.environment );
  35606. }
  35607. if ( data.fog !== undefined ) {
  35608. if ( data.fog.type === 'Fog' ) {
  35609. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35610. } else if ( data.fog.type === 'FogExp2' ) {
  35611. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35612. }
  35613. if ( data.fog.name !== '' ) {
  35614. object.fog.name = data.fog.name;
  35615. }
  35616. }
  35617. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35618. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35619. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35620. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35621. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35622. break;
  35623. case 'PerspectiveCamera':
  35624. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35625. if ( data.focus !== undefined ) object.focus = data.focus;
  35626. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35627. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35628. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35629. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35630. break;
  35631. case 'OrthographicCamera':
  35632. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35633. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35634. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35635. break;
  35636. case 'AmbientLight':
  35637. object = new AmbientLight( data.color, data.intensity );
  35638. break;
  35639. case 'DirectionalLight':
  35640. object = new DirectionalLight( data.color, data.intensity );
  35641. object.target = data.target || '';
  35642. break;
  35643. case 'PointLight':
  35644. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35645. break;
  35646. case 'RectAreaLight':
  35647. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35648. break;
  35649. case 'SpotLight':
  35650. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35651. object.target = data.target || '';
  35652. break;
  35653. case 'HemisphereLight':
  35654. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35655. break;
  35656. case 'LightProbe':
  35657. const sh = new SphericalHarmonics3().fromArray( data.sh );
  35658. object = new LightProbe( sh, data.intensity );
  35659. break;
  35660. case 'SkinnedMesh':
  35661. geometry = getGeometry( data.geometry );
  35662. material = getMaterial( data.material );
  35663. object = new SkinnedMesh( geometry, material );
  35664. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35665. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35666. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35667. break;
  35668. case 'Mesh':
  35669. geometry = getGeometry( data.geometry );
  35670. material = getMaterial( data.material );
  35671. object = new Mesh( geometry, material );
  35672. break;
  35673. case 'InstancedMesh':
  35674. geometry = getGeometry( data.geometry );
  35675. material = getMaterial( data.material );
  35676. const count = data.count;
  35677. const instanceMatrix = data.instanceMatrix;
  35678. const instanceColor = data.instanceColor;
  35679. object = new InstancedMesh( geometry, material, count );
  35680. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35681. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35682. break;
  35683. case 'BatchedMesh':
  35684. geometry = getGeometry( data.geometry );
  35685. material = getMaterial( data.material );
  35686. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35687. object.geometry = geometry;
  35688. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35689. object.sortObjects = data.sortObjects;
  35690. object._drawRanges = data.drawRanges;
  35691. object._reservedRanges = data.reservedRanges;
  35692. object._geometryInfo = data.geometryInfo.map( info => {
  35693. let box = null;
  35694. let sphere = null;
  35695. if ( info.boundingBox !== undefined ) {
  35696. box = new Box3().fromJSON( info.boundingBox );
  35697. }
  35698. if ( info.boundingSphere !== undefined ) {
  35699. sphere = new Sphere().fromJSON( info.boundingSphere );
  35700. }
  35701. return {
  35702. ...info,
  35703. boundingBox: box,
  35704. boundingSphere: sphere
  35705. };
  35706. } );
  35707. object._instanceInfo = data.instanceInfo;
  35708. object._availableInstanceIds = data._availableInstanceIds;
  35709. object._availableGeometryIds = data._availableGeometryIds;
  35710. object._nextIndexStart = data.nextIndexStart;
  35711. object._nextVertexStart = data.nextVertexStart;
  35712. object._geometryCount = data.geometryCount;
  35713. object._maxInstanceCount = data.maxInstanceCount;
  35714. object._maxVertexCount = data.maxVertexCount;
  35715. object._maxIndexCount = data.maxIndexCount;
  35716. object._geometryInitialized = data.geometryInitialized;
  35717. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35718. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35719. if ( data.colorsTexture !== undefined ) {
  35720. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35721. }
  35722. if ( data.boundingSphere !== undefined ) {
  35723. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35724. }
  35725. if ( data.boundingBox !== undefined ) {
  35726. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35727. }
  35728. break;
  35729. case 'LOD':
  35730. object = new LOD();
  35731. break;
  35732. case 'Line':
  35733. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35734. break;
  35735. case 'LineLoop':
  35736. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35737. break;
  35738. case 'LineSegments':
  35739. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35740. break;
  35741. case 'PointCloud':
  35742. case 'Points':
  35743. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35744. break;
  35745. case 'Sprite':
  35746. object = new Sprite( getMaterial( data.material ) );
  35747. break;
  35748. case 'Group':
  35749. object = new Group();
  35750. break;
  35751. case 'Bone':
  35752. object = new Bone();
  35753. break;
  35754. default:
  35755. object = new Object3D();
  35756. }
  35757. object.uuid = data.uuid;
  35758. if ( data.name !== undefined ) object.name = data.name;
  35759. if ( data.matrix !== undefined ) {
  35760. object.matrix.fromArray( data.matrix );
  35761. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35762. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35763. } else {
  35764. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35765. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35766. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35767. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35768. }
  35769. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35770. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  35771. if ( data.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, data.morphTargetDictionary );
  35772. if ( data.morphTargetInfluences !== undefined ) object.morphTargetInfluences = data.morphTargetInfluences.slice();
  35773. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35774. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35775. if ( data.shadow ) {
  35776. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35777. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35778. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35779. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35780. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35781. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35782. }
  35783. if ( data.visible !== undefined ) object.visible = data.visible;
  35784. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35785. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35786. if ( data.static !== undefined ) object.static = data.static;
  35787. if ( data.userData !== undefined ) object.userData = data.userData;
  35788. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35789. if ( data.children !== undefined ) {
  35790. const children = data.children;
  35791. for ( let i = 0; i < children.length; i ++ ) {
  35792. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35793. }
  35794. }
  35795. if ( data.animations !== undefined ) {
  35796. const objectAnimations = data.animations;
  35797. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35798. const uuid = objectAnimations[ i ];
  35799. object.animations.push( animations[ uuid ] );
  35800. }
  35801. }
  35802. if ( data.type === 'LOD' ) {
  35803. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35804. const levels = data.levels;
  35805. for ( let l = 0; l < levels.length; l ++ ) {
  35806. const level = levels[ l ];
  35807. const child = object.getObjectByProperty( 'uuid', level.object );
  35808. if ( child !== undefined ) {
  35809. object.addLevel( child, level.distance, level.hysteresis );
  35810. }
  35811. }
  35812. }
  35813. return object;
  35814. }
  35815. bindSkeletons( object, skeletons ) {
  35816. if ( Object.keys( skeletons ).length === 0 ) return;
  35817. object.traverse( function ( child ) {
  35818. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35819. const skeleton = skeletons[ child.skeleton ];
  35820. if ( skeleton === undefined ) {
  35821. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35822. } else {
  35823. child.bind( skeleton, child.bindMatrix );
  35824. }
  35825. }
  35826. } );
  35827. }
  35828. bindLightTargets( object ) {
  35829. object.traverse( function ( child ) {
  35830. if ( child.isDirectionalLight || child.isSpotLight ) {
  35831. const uuid = child.target;
  35832. const target = object.getObjectByProperty( 'uuid', uuid );
  35833. if ( target !== undefined ) {
  35834. child.target = target;
  35835. } else {
  35836. child.target = new Object3D();
  35837. }
  35838. }
  35839. } );
  35840. }
  35841. }
  35842. const TEXTURE_MAPPING = {
  35843. UVMapping: UVMapping,
  35844. CubeReflectionMapping: CubeReflectionMapping,
  35845. CubeRefractionMapping: CubeRefractionMapping,
  35846. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35847. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35848. CubeUVReflectionMapping: CubeUVReflectionMapping
  35849. };
  35850. const TEXTURE_WRAPPING = {
  35851. RepeatWrapping: RepeatWrapping,
  35852. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35853. MirroredRepeatWrapping: MirroredRepeatWrapping
  35854. };
  35855. const TEXTURE_FILTER = {
  35856. NearestFilter: NearestFilter,
  35857. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35858. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35859. LinearFilter: LinearFilter,
  35860. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35861. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35862. };
  35863. const _errorMap = new WeakMap();
  35864. /**
  35865. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  35866. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35867. * textures for rendering.
  35868. *
  35869. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35870. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  35871. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  35872. *
  35873. * To match the default behaviour of {@link Texture}, the following options are needed:
  35874. *
  35875. * ```js
  35876. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  35877. * ```
  35878. *
  35879. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  35880. *
  35881. * ```js
  35882. * const loader = new THREE.ImageBitmapLoader();
  35883. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35884. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35885. *
  35886. * const texture = new THREE.Texture( imageBitmap );
  35887. * texture.needsUpdate = true;
  35888. * ```
  35889. *
  35890. * @augments Loader
  35891. */
  35892. class ImageBitmapLoader extends Loader {
  35893. /**
  35894. * Constructs a new image bitmap loader.
  35895. *
  35896. * @param {LoadingManager} [manager] - The loading manager.
  35897. */
  35898. constructor( manager ) {
  35899. super( manager );
  35900. /**
  35901. * This flag can be used for type testing.
  35902. *
  35903. * @type {boolean}
  35904. * @readonly
  35905. * @default true
  35906. */
  35907. this.isImageBitmapLoader = true;
  35908. if ( typeof createImageBitmap === 'undefined' ) {
  35909. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  35910. }
  35911. if ( typeof fetch === 'undefined' ) {
  35912. warn( 'ImageBitmapLoader: fetch() not supported.' );
  35913. }
  35914. /**
  35915. * Represents the loader options.
  35916. *
  35917. * @type {Object}
  35918. * @default {premultiplyAlpha:'none'}
  35919. */
  35920. this.options = { premultiplyAlpha: 'none' };
  35921. /**
  35922. * Used for aborting requests.
  35923. *
  35924. * @private
  35925. * @type {AbortController}
  35926. */
  35927. this._abortController = new AbortController();
  35928. }
  35929. /**
  35930. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35931. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  35932. *
  35933. * @param {Object} options - The loader options to set.
  35934. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35935. */
  35936. setOptions( options ) {
  35937. this.options = options;
  35938. return this;
  35939. }
  35940. /**
  35941. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35942. *
  35943. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35944. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35945. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35946. * @param {onErrorCallback} onError - Executed when errors occur.
  35947. * @return {ImageBitmap|undefined} The image bitmap.
  35948. */
  35949. load( url, onLoad, onProgress, onError ) {
  35950. if ( url === undefined ) url = '';
  35951. if ( this.path !== undefined ) url = this.path + url;
  35952. url = this.manager.resolveURL( url );
  35953. const scope = this;
  35954. const cached = Cache.get( `image-bitmap:${url}` );
  35955. if ( cached !== undefined ) {
  35956. scope.manager.itemStart( url );
  35957. // If cached is a promise, wait for it to resolve
  35958. if ( cached.then ) {
  35959. cached.then( imageBitmap => {
  35960. // check if there is an error for the cached promise
  35961. if ( _errorMap.has( cached ) === true ) {
  35962. if ( onError ) onError( _errorMap.get( cached ) );
  35963. scope.manager.itemError( url );
  35964. scope.manager.itemEnd( url );
  35965. } else {
  35966. if ( onLoad ) onLoad( imageBitmap );
  35967. scope.manager.itemEnd( url );
  35968. return imageBitmap;
  35969. }
  35970. } );
  35971. return;
  35972. }
  35973. // If cached is not a promise (i.e., it's already an imageBitmap)
  35974. setTimeout( function () {
  35975. if ( onLoad ) onLoad( cached );
  35976. scope.manager.itemEnd( url );
  35977. }, 0 );
  35978. return cached;
  35979. }
  35980. const fetchOptions = {};
  35981. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35982. fetchOptions.headers = this.requestHeader;
  35983. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35984. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35985. return res.blob();
  35986. } ).then( function ( blob ) {
  35987. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35988. } ).then( function ( imageBitmap ) {
  35989. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35990. if ( onLoad ) onLoad( imageBitmap );
  35991. scope.manager.itemEnd( url );
  35992. return imageBitmap;
  35993. } ).catch( function ( e ) {
  35994. if ( onError ) onError( e );
  35995. _errorMap.set( promise, e );
  35996. Cache.remove( `image-bitmap:${url}` );
  35997. scope.manager.itemError( url );
  35998. scope.manager.itemEnd( url );
  35999. } );
  36000. Cache.add( `image-bitmap:${url}`, promise );
  36001. scope.manager.itemStart( url );
  36002. }
  36003. /**
  36004. * Aborts ongoing fetch requests.
  36005. *
  36006. * @return {ImageBitmapLoader} A reference to this instance.
  36007. */
  36008. abort() {
  36009. this._abortController.abort();
  36010. this._abortController = new AbortController();
  36011. return this;
  36012. }
  36013. }
  36014. let _context;
  36015. /**
  36016. * Manages the global audio context in the engine.
  36017. *
  36018. * @hideconstructor
  36019. */
  36020. class AudioContext {
  36021. /**
  36022. * Returns the global native audio context.
  36023. *
  36024. * @return {AudioContext} The native audio context.
  36025. */
  36026. static getContext() {
  36027. if ( _context === undefined ) {
  36028. _context = new ( window.AudioContext || window.webkitAudioContext )();
  36029. }
  36030. return _context;
  36031. }
  36032. /**
  36033. * Allows to set the global native audio context from outside.
  36034. *
  36035. * @param {AudioContext} value - The native context to set.
  36036. */
  36037. static setContext( value ) {
  36038. _context = value;
  36039. }
  36040. }
  36041. /**
  36042. * Class for loading audio buffers. Audios are internally
  36043. * loaded via {@link FileLoader}.
  36044. *
  36045. * ```js
  36046. * const audioListener = new THREE.AudioListener();
  36047. * const ambientSound = new THREE.Audio( audioListener );
  36048. *
  36049. * const loader = new THREE.AudioLoader();
  36050. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  36051. *
  36052. * ambientSound.setBuffer( audioBuffer );
  36053. * ambientSound.play();
  36054. * ```
  36055. *
  36056. * @augments Loader
  36057. */
  36058. class AudioLoader extends Loader {
  36059. /**
  36060. * Constructs a new audio loader.
  36061. *
  36062. * @param {LoadingManager} [manager] - The loading manager.
  36063. */
  36064. constructor( manager ) {
  36065. super( manager );
  36066. }
  36067. /**
  36068. * Starts loading from the given URL and passes the loaded audio buffer
  36069. * to the `onLoad()` callback.
  36070. *
  36071. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36072. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  36073. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36074. * @param {onErrorCallback} onError - Executed when errors occur.
  36075. */
  36076. load( url, onLoad, onProgress, onError ) {
  36077. const scope = this;
  36078. const loader = new FileLoader( this.manager );
  36079. loader.setResponseType( 'arraybuffer' );
  36080. loader.setPath( this.path );
  36081. loader.setRequestHeader( this.requestHeader );
  36082. loader.setWithCredentials( this.withCredentials );
  36083. loader.load( url, function ( buffer ) {
  36084. try {
  36085. // Create a copy of the buffer. The `decodeAudioData` method
  36086. // detaches the buffer when complete, preventing reuse.
  36087. const bufferCopy = buffer.slice( 0 );
  36088. const context = AudioContext.getContext();
  36089. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  36090. onLoad( audioBuffer );
  36091. } ).catch( handleError );
  36092. } catch ( e ) {
  36093. handleError( e );
  36094. }
  36095. }, onProgress, onError );
  36096. function handleError( e ) {
  36097. if ( onError ) {
  36098. onError( e );
  36099. } else {
  36100. error( e );
  36101. }
  36102. scope.manager.itemError( url );
  36103. }
  36104. }
  36105. }
  36106. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36107. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36108. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36109. /**
  36110. * A special type of camera that uses two perspective cameras with
  36111. * stereoscopic projection. Can be used for rendering stereo effects
  36112. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36113. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36114. */
  36115. class StereoCamera {
  36116. /**
  36117. * Constructs a new stereo camera.
  36118. */
  36119. constructor() {
  36120. /**
  36121. * The type property is used for detecting the object type
  36122. * in context of serialization/deserialization.
  36123. *
  36124. * @type {string}
  36125. * @readonly
  36126. */
  36127. this.type = 'StereoCamera';
  36128. /**
  36129. * The aspect.
  36130. *
  36131. * @type {number}
  36132. * @default 1
  36133. */
  36134. this.aspect = 1;
  36135. /**
  36136. * The eye separation which represents the distance
  36137. * between the left and right camera.
  36138. *
  36139. * @type {number}
  36140. * @default 0.064
  36141. */
  36142. this.eyeSep = 0.064;
  36143. /**
  36144. * The camera representing the left eye. This is added to layer `1` so objects to be
  36145. * rendered by the left camera must also be added to this layer.
  36146. *
  36147. * @type {PerspectiveCamera}
  36148. */
  36149. this.cameraL = new PerspectiveCamera();
  36150. this.cameraL.layers.enable( 1 );
  36151. this.cameraL.matrixAutoUpdate = false;
  36152. /**
  36153. * The camera representing the right eye. This is added to layer `2` so objects to be
  36154. * rendered by the right camera must also be added to this layer.
  36155. *
  36156. * @type {PerspectiveCamera}
  36157. */
  36158. this.cameraR = new PerspectiveCamera();
  36159. this.cameraR.layers.enable( 2 );
  36160. this.cameraR.matrixAutoUpdate = false;
  36161. this._cache = {
  36162. focus: null,
  36163. fov: null,
  36164. aspect: null,
  36165. near: null,
  36166. far: null,
  36167. zoom: null,
  36168. eyeSep: null
  36169. };
  36170. }
  36171. /**
  36172. * Updates the stereo camera based on the given perspective camera.
  36173. *
  36174. * @param {PerspectiveCamera} camera - The perspective camera.
  36175. */
  36176. update( camera ) {
  36177. const cache = this._cache;
  36178. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36179. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36180. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36181. if ( needsUpdate ) {
  36182. cache.focus = camera.focus;
  36183. cache.fov = camera.fov;
  36184. cache.aspect = camera.aspect * this.aspect;
  36185. cache.near = camera.near;
  36186. cache.far = camera.far;
  36187. cache.zoom = camera.zoom;
  36188. cache.eyeSep = this.eyeSep;
  36189. // Off-axis stereoscopic effect based on
  36190. // http://paulbourke.net/stereographics/stereorender/
  36191. _projectionMatrix.copy( camera.projectionMatrix );
  36192. const eyeSepHalf = cache.eyeSep / 2;
  36193. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36194. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36195. let xmin, xmax;
  36196. // translate xOffset
  36197. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36198. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36199. // for left eye
  36200. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36201. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36202. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36203. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36204. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36205. // for right eye
  36206. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36207. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36208. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36209. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36210. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36211. }
  36212. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36213. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36214. }
  36215. }
  36216. const fov = -90; // negative fov is not an error
  36217. const aspect = 1;
  36218. /**
  36219. * A special type of camera that is positioned in 3D space to render its surroundings into a
  36220. * cube render target. The render target can then be used as an environment map for rendering
  36221. * realtime reflections in your scene.
  36222. *
  36223. * ```js
  36224. * // Create cube render target
  36225. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  36226. *
  36227. * // Create cube camera
  36228. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  36229. * scene.add( cubeCamera );
  36230. *
  36231. * // Create car
  36232. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  36233. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  36234. * scene.add( car );
  36235. *
  36236. * // Update the render target cube
  36237. * car.visible = false;
  36238. * cubeCamera.position.copy( car.position );
  36239. * cubeCamera.update( renderer, scene );
  36240. *
  36241. * // Render the scene
  36242. * car.visible = true;
  36243. * renderer.render( scene, camera );
  36244. * ```
  36245. *
  36246. * @augments Object3D
  36247. */
  36248. class CubeCamera extends Object3D {
  36249. /**
  36250. * Constructs a new cube camera.
  36251. *
  36252. * @param {number} near - The camera's near plane.
  36253. * @param {number} far - The camera's far plane.
  36254. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  36255. */
  36256. constructor( near, far, renderTarget ) {
  36257. super();
  36258. this.type = 'CubeCamera';
  36259. /**
  36260. * A reference to the cube render target.
  36261. *
  36262. * @type {WebGLCubeRenderTarget}
  36263. */
  36264. this.renderTarget = renderTarget;
  36265. /**
  36266. * The current active coordinate system.
  36267. *
  36268. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  36269. * @default null
  36270. */
  36271. this.coordinateSystem = null;
  36272. /**
  36273. * The current active mipmap level
  36274. *
  36275. * @type {number}
  36276. * @default 0
  36277. */
  36278. this.activeMipmapLevel = 0;
  36279. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  36280. cameraPX.layers = this.layers;
  36281. this.add( cameraPX );
  36282. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  36283. cameraNX.layers = this.layers;
  36284. this.add( cameraNX );
  36285. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  36286. cameraPY.layers = this.layers;
  36287. this.add( cameraPY );
  36288. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  36289. cameraNY.layers = this.layers;
  36290. this.add( cameraNY );
  36291. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  36292. cameraPZ.layers = this.layers;
  36293. this.add( cameraPZ );
  36294. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  36295. cameraNZ.layers = this.layers;
  36296. this.add( cameraNZ );
  36297. }
  36298. /**
  36299. * Must be called when the coordinate system of the cube camera is changed.
  36300. */
  36301. updateCoordinateSystem() {
  36302. const coordinateSystem = this.coordinateSystem;
  36303. const cameras = this.children.concat();
  36304. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  36305. for ( const camera of cameras ) this.remove( camera );
  36306. if ( coordinateSystem === WebGLCoordinateSystem ) {
  36307. cameraPX.up.set( 0, 1, 0 );
  36308. cameraPX.lookAt( 1, 0, 0 );
  36309. cameraNX.up.set( 0, 1, 0 );
  36310. cameraNX.lookAt( -1, 0, 0 );
  36311. cameraPY.up.set( 0, 0, -1 );
  36312. cameraPY.lookAt( 0, 1, 0 );
  36313. cameraNY.up.set( 0, 0, 1 );
  36314. cameraNY.lookAt( 0, -1, 0 );
  36315. cameraPZ.up.set( 0, 1, 0 );
  36316. cameraPZ.lookAt( 0, 0, 1 );
  36317. cameraNZ.up.set( 0, 1, 0 );
  36318. cameraNZ.lookAt( 0, 0, -1 );
  36319. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  36320. cameraPX.up.set( 0, -1, 0 );
  36321. cameraPX.lookAt( -1, 0, 0 );
  36322. cameraNX.up.set( 0, -1, 0 );
  36323. cameraNX.lookAt( 1, 0, 0 );
  36324. cameraPY.up.set( 0, 0, 1 );
  36325. cameraPY.lookAt( 0, 1, 0 );
  36326. cameraNY.up.set( 0, 0, -1 );
  36327. cameraNY.lookAt( 0, -1, 0 );
  36328. cameraPZ.up.set( 0, -1, 0 );
  36329. cameraPZ.lookAt( 0, 0, 1 );
  36330. cameraNZ.up.set( 0, -1, 0 );
  36331. cameraNZ.lookAt( 0, 0, -1 );
  36332. } else {
  36333. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  36334. }
  36335. for ( const camera of cameras ) {
  36336. this.add( camera );
  36337. camera.updateMatrixWorld();
  36338. }
  36339. }
  36340. /**
  36341. * Calling this method will render the given scene with the given renderer
  36342. * into the cube render target of the camera.
  36343. *
  36344. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  36345. * @param {Scene} scene - The scene to render.
  36346. */
  36347. update( renderer, scene ) {
  36348. if ( this.parent === null ) this.updateMatrixWorld();
  36349. const { renderTarget, activeMipmapLevel } = this;
  36350. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  36351. this.coordinateSystem = renderer.coordinateSystem;
  36352. this.updateCoordinateSystem();
  36353. }
  36354. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  36355. const currentRenderTarget = renderer.getRenderTarget();
  36356. const currentActiveCubeFace = renderer.getActiveCubeFace();
  36357. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  36358. const currentXrEnabled = renderer.xr.enabled;
  36359. renderer.xr.enabled = false;
  36360. const generateMipmaps = renderTarget.texture.generateMipmaps;
  36361. renderTarget.texture.generateMipmaps = false;
  36362. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  36363. const reversedDepthBuffer = !! ( renderer.isWebGLRenderer && renderer.state.buffers.depth.getReversed() );
  36364. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  36365. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36366. renderer.render( scene, cameraPX );
  36367. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  36368. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36369. renderer.render( scene, cameraNX );
  36370. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  36371. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36372. renderer.render( scene, cameraPY );
  36373. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  36374. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36375. renderer.render( scene, cameraNY );
  36376. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  36377. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36378. renderer.render( scene, cameraPZ );
  36379. // mipmaps are generated during the last call of render()
  36380. // at this point, all sides of the cube render target are defined
  36381. renderTarget.texture.generateMipmaps = generateMipmaps;
  36382. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  36383. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36384. renderer.render( scene, cameraNZ );
  36385. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  36386. renderer.xr.enabled = currentXrEnabled;
  36387. renderTarget.texture.needsPMREMUpdate = true;
  36388. }
  36389. }
  36390. /**
  36391. * This type of camera can be used in order to efficiently render a scene with a
  36392. * predefined set of cameras. This is an important performance aspect for
  36393. * rendering VR scenes.
  36394. *
  36395. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36396. * to define for each sub camera the `viewport` property which determines the
  36397. * part of the viewport that is rendered with this camera.
  36398. *
  36399. * @augments PerspectiveCamera
  36400. */
  36401. class ArrayCamera extends PerspectiveCamera {
  36402. /**
  36403. * Constructs a new array camera.
  36404. *
  36405. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36406. */
  36407. constructor( array = [] ) {
  36408. super();
  36409. /**
  36410. * This flag can be used for type testing.
  36411. *
  36412. * @type {boolean}
  36413. * @readonly
  36414. * @default true
  36415. */
  36416. this.isArrayCamera = true;
  36417. /**
  36418. * Whether this camera is used with multiview rendering or not.
  36419. *
  36420. * @type {boolean}
  36421. * @readonly
  36422. * @default false
  36423. */
  36424. this.isMultiViewCamera = false;
  36425. /**
  36426. * An array of perspective sub cameras.
  36427. *
  36428. * @type {Array<PerspectiveCamera>}
  36429. */
  36430. this.cameras = array;
  36431. }
  36432. }
  36433. /**
  36434. * Class for keeping track of time.
  36435. *
  36436. * @deprecated since r183.
  36437. */
  36438. class Clock {
  36439. /**
  36440. * Constructs a new clock.
  36441. *
  36442. * @deprecated since 183.
  36443. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  36444. * `getDelta()` is called for the first time.
  36445. */
  36446. constructor( autoStart = true ) {
  36447. /**
  36448. * If set to `true`, the clock starts automatically when `getDelta()` is called
  36449. * for the first time.
  36450. *
  36451. * @type {boolean}
  36452. * @default true
  36453. */
  36454. this.autoStart = autoStart;
  36455. /**
  36456. * Holds the time at which the clock's `start()` method was last called.
  36457. *
  36458. * @type {number}
  36459. * @default 0
  36460. */
  36461. this.startTime = 0;
  36462. /**
  36463. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  36464. * `getDelta()` methods were last called.
  36465. *
  36466. * @type {number}
  36467. * @default 0
  36468. */
  36469. this.oldTime = 0;
  36470. /**
  36471. * Keeps track of the total time that the clock has been running.
  36472. *
  36473. * @type {number}
  36474. * @default 0
  36475. */
  36476. this.elapsedTime = 0;
  36477. /**
  36478. * Whether the clock is running or not.
  36479. *
  36480. * @type {boolean}
  36481. * @default true
  36482. */
  36483. this.running = false;
  36484. warn( 'THREE.Clock: This module has been deprecated. Please use THREE.Timer instead.' ); // @deprecated, r183
  36485. }
  36486. /**
  36487. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  36488. * called by the class.
  36489. */
  36490. start() {
  36491. this.startTime = performance.now();
  36492. this.oldTime = this.startTime;
  36493. this.elapsedTime = 0;
  36494. this.running = true;
  36495. }
  36496. /**
  36497. * Stops the clock.
  36498. */
  36499. stop() {
  36500. this.getElapsedTime();
  36501. this.running = false;
  36502. this.autoStart = false;
  36503. }
  36504. /**
  36505. * Returns the elapsed time in seconds.
  36506. *
  36507. * @return {number} The elapsed time.
  36508. */
  36509. getElapsedTime() {
  36510. this.getDelta();
  36511. return this.elapsedTime;
  36512. }
  36513. /**
  36514. * Returns the delta time in seconds.
  36515. *
  36516. * @return {number} The delta time.
  36517. */
  36518. getDelta() {
  36519. let diff = 0;
  36520. if ( this.autoStart && ! this.running ) {
  36521. this.start();
  36522. return 0;
  36523. }
  36524. if ( this.running ) {
  36525. const newTime = performance.now();
  36526. diff = ( newTime - this.oldTime ) / 1000;
  36527. this.oldTime = newTime;
  36528. this.elapsedTime += diff;
  36529. }
  36530. return diff;
  36531. }
  36532. }
  36533. const _position$1 = /*@__PURE__*/ new Vector3();
  36534. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36535. const _scale$1 = /*@__PURE__*/ new Vector3();
  36536. const _forward = /*@__PURE__*/ new Vector3();
  36537. const _up = /*@__PURE__*/ new Vector3();
  36538. /**
  36539. * The class represents a virtual listener of the all positional and non-positional audio effects
  36540. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36541. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36542. *
  36543. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36544. * camera represents the 3D transformation of the listener.
  36545. *
  36546. * @augments Object3D
  36547. */
  36548. class AudioListener extends Object3D {
  36549. /**
  36550. * Constructs a new audio listener.
  36551. */
  36552. constructor() {
  36553. super();
  36554. this.type = 'AudioListener';
  36555. /**
  36556. * The native audio context.
  36557. *
  36558. * @type {AudioContext}
  36559. * @readonly
  36560. */
  36561. this.context = AudioContext.getContext();
  36562. /**
  36563. * The gain node used for volume control.
  36564. *
  36565. * @type {GainNode}
  36566. * @readonly
  36567. */
  36568. this.gain = this.context.createGain();
  36569. this.gain.connect( this.context.destination );
  36570. /**
  36571. * An optional filter.
  36572. *
  36573. * Defined via {@link AudioListener#setFilter}.
  36574. *
  36575. * @type {?AudioNode}
  36576. * @default null
  36577. * @readonly
  36578. */
  36579. this.filter = null;
  36580. /**
  36581. * Time delta values required for `linearRampToValueAtTime()` usage.
  36582. *
  36583. * @type {number}
  36584. * @default 0
  36585. * @readonly
  36586. */
  36587. this.timeDelta = 0;
  36588. // private
  36589. this._clock = new Clock();
  36590. }
  36591. /**
  36592. * Returns the listener's input node.
  36593. *
  36594. * This method is used by other audio nodes to connect to this listener.
  36595. *
  36596. * @return {GainNode} The input node.
  36597. */
  36598. getInput() {
  36599. return this.gain;
  36600. }
  36601. /**
  36602. * Removes the current filter from this listener.
  36603. *
  36604. * @return {AudioListener} A reference to this listener.
  36605. */
  36606. removeFilter() {
  36607. if ( this.filter !== null ) {
  36608. this.gain.disconnect( this.filter );
  36609. this.filter.disconnect( this.context.destination );
  36610. this.gain.connect( this.context.destination );
  36611. this.filter = null;
  36612. }
  36613. return this;
  36614. }
  36615. /**
  36616. * Returns the current set filter.
  36617. *
  36618. * @return {?AudioNode} The filter.
  36619. */
  36620. getFilter() {
  36621. return this.filter;
  36622. }
  36623. /**
  36624. * Sets the given filter to this listener.
  36625. *
  36626. * @param {AudioNode} value - The filter to set.
  36627. * @return {AudioListener} A reference to this listener.
  36628. */
  36629. setFilter( value ) {
  36630. if ( this.filter !== null ) {
  36631. this.gain.disconnect( this.filter );
  36632. this.filter.disconnect( this.context.destination );
  36633. } else {
  36634. this.gain.disconnect( this.context.destination );
  36635. }
  36636. this.filter = value;
  36637. this.gain.connect( this.filter );
  36638. this.filter.connect( this.context.destination );
  36639. return this;
  36640. }
  36641. /**
  36642. * Returns the applications master volume.
  36643. *
  36644. * @return {number} The master volume.
  36645. */
  36646. getMasterVolume() {
  36647. return this.gain.gain.value;
  36648. }
  36649. /**
  36650. * Sets the applications master volume. This volume setting affects
  36651. * all audio nodes in the scene.
  36652. *
  36653. * @param {number} value - The master volume to set.
  36654. * @return {AudioListener} A reference to this listener.
  36655. */
  36656. setMasterVolume( value ) {
  36657. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36658. return this;
  36659. }
  36660. updateMatrixWorld( force ) {
  36661. super.updateMatrixWorld( force );
  36662. const listener = this.context.listener;
  36663. this.timeDelta = this._clock.getDelta();
  36664. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36665. // the initial forward and up directions must be orthogonal
  36666. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36667. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36668. if ( listener.positionX ) {
  36669. // code path for Chrome (see #14393)
  36670. const endTime = this.context.currentTime + this.timeDelta;
  36671. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36672. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36673. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36674. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36675. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36676. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36677. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36678. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36679. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36680. } else {
  36681. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36682. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36683. }
  36684. }
  36685. }
  36686. /**
  36687. * Represents a non-positional ( global ) audio object.
  36688. *
  36689. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36690. *
  36691. * ```js
  36692. * // create an AudioListener and add it to the camera
  36693. * const listener = new THREE.AudioListener();
  36694. * camera.add( listener );
  36695. *
  36696. * // create a global audio source
  36697. * const sound = new THREE.Audio( listener );
  36698. *
  36699. * // load a sound and set it as the Audio object's buffer
  36700. * const audioLoader = new THREE.AudioLoader();
  36701. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36702. * sound.setBuffer( buffer );
  36703. * sound.setLoop( true );
  36704. * sound.setVolume( 0.5 );
  36705. * sound.play();
  36706. * });
  36707. * ```
  36708. *
  36709. * @augments Object3D
  36710. */
  36711. class Audio extends Object3D {
  36712. /**
  36713. * Constructs a new audio.
  36714. *
  36715. * @param {AudioListener} listener - The global audio listener.
  36716. */
  36717. constructor( listener ) {
  36718. super();
  36719. this.type = 'Audio';
  36720. /**
  36721. * The global audio listener.
  36722. *
  36723. * @type {AudioListener}
  36724. * @readonly
  36725. */
  36726. this.listener = listener;
  36727. /**
  36728. * The audio context.
  36729. *
  36730. * @type {AudioContext}
  36731. * @readonly
  36732. */
  36733. this.context = listener.context;
  36734. /**
  36735. * The gain node used for volume control.
  36736. *
  36737. * @type {GainNode}
  36738. * @readonly
  36739. */
  36740. this.gain = this.context.createGain();
  36741. this.gain.connect( listener.getInput() );
  36742. /**
  36743. * Whether to start playback automatically or not.
  36744. *
  36745. * @type {boolean}
  36746. * @default false
  36747. */
  36748. this.autoplay = false;
  36749. /**
  36750. * A reference to an audio buffer.
  36751. *
  36752. * Defined via {@link Audio#setBuffer}.
  36753. *
  36754. * @type {?AudioBuffer}
  36755. * @default null
  36756. * @readonly
  36757. */
  36758. this.buffer = null;
  36759. /**
  36760. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36761. * +/- 1200 is an octave.
  36762. *
  36763. * Defined via {@link Audio#setDetune}.
  36764. *
  36765. * @type {number}
  36766. * @default 0
  36767. * @readonly
  36768. */
  36769. this.detune = 0;
  36770. /**
  36771. * Whether the audio should loop or not.
  36772. *
  36773. * Defined via {@link Audio#setLoop}.
  36774. *
  36775. * @type {boolean}
  36776. * @default false
  36777. * @readonly
  36778. */
  36779. this.loop = false;
  36780. /**
  36781. * Defines where in the audio buffer the replay should
  36782. * start, in seconds.
  36783. *
  36784. * @type {number}
  36785. * @default 0
  36786. */
  36787. this.loopStart = 0;
  36788. /**
  36789. * Defines where in the audio buffer the replay should
  36790. * stop, in seconds.
  36791. *
  36792. * @type {number}
  36793. * @default 0
  36794. */
  36795. this.loopEnd = 0;
  36796. /**
  36797. * An offset to the time within the audio buffer the playback
  36798. * should begin, in seconds.
  36799. *
  36800. * @type {number}
  36801. * @default 0
  36802. */
  36803. this.offset = 0;
  36804. /**
  36805. * Overrides the default duration of the audio.
  36806. *
  36807. * @type {undefined|number}
  36808. * @default undefined
  36809. */
  36810. this.duration = undefined;
  36811. /**
  36812. * The playback speed.
  36813. *
  36814. * Defined via {@link Audio#setPlaybackRate}.
  36815. *
  36816. * @type {number}
  36817. * @readonly
  36818. * @default 1
  36819. */
  36820. this.playbackRate = 1;
  36821. /**
  36822. * Indicates whether the audio is playing or not.
  36823. *
  36824. * This flag will be automatically set when using {@link Audio#play},
  36825. * {@link Audio#pause}, {@link Audio#stop}.
  36826. *
  36827. * @type {boolean}
  36828. * @readonly
  36829. * @default false
  36830. */
  36831. this.isPlaying = false;
  36832. /**
  36833. * Indicates whether the audio playback can be controlled
  36834. * with method like {@link Audio#play} or {@link Audio#pause}.
  36835. *
  36836. * This flag will be automatically set when audio sources are
  36837. * defined.
  36838. *
  36839. * @type {boolean}
  36840. * @readonly
  36841. * @default true
  36842. */
  36843. this.hasPlaybackControl = true;
  36844. /**
  36845. * Holds a reference to the current audio source.
  36846. *
  36847. * The property is automatically by one of the `set*()` methods.
  36848. *
  36849. * @type {?AudioNode}
  36850. * @readonly
  36851. * @default null
  36852. */
  36853. this.source = null;
  36854. /**
  36855. * Defines the source type.
  36856. *
  36857. * The property is automatically set by one of the `set*()` methods.
  36858. *
  36859. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36860. * @readonly
  36861. * @default 'empty'
  36862. */
  36863. this.sourceType = 'empty';
  36864. this._startedAt = 0;
  36865. this._progress = 0;
  36866. this._connected = false;
  36867. /**
  36868. * Can be used to apply a variety of low-order filters to create
  36869. * more complex sound effects e.g. via `BiquadFilterNode`.
  36870. *
  36871. * The property is automatically set by {@link Audio#setFilters}.
  36872. *
  36873. * @type {Array<AudioNode>}
  36874. * @readonly
  36875. */
  36876. this.filters = [];
  36877. }
  36878. /**
  36879. * Returns the output audio node.
  36880. *
  36881. * @return {GainNode} The output node.
  36882. */
  36883. getOutput() {
  36884. return this.gain;
  36885. }
  36886. /**
  36887. * Sets the given audio node as the source of this instance.
  36888. *
  36889. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36890. *
  36891. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36892. * @return {Audio} A reference to this instance.
  36893. */
  36894. setNodeSource( audioNode ) {
  36895. this.hasPlaybackControl = false;
  36896. this.sourceType = 'audioNode';
  36897. this.source = audioNode;
  36898. this.connect();
  36899. return this;
  36900. }
  36901. /**
  36902. * Sets the given media element as the source of this instance.
  36903. *
  36904. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36905. *
  36906. * @param {HTMLMediaElement} mediaElement - The media element.
  36907. * @return {Audio} A reference to this instance.
  36908. */
  36909. setMediaElementSource( mediaElement ) {
  36910. this.hasPlaybackControl = false;
  36911. this.sourceType = 'mediaNode';
  36912. this.source = this.context.createMediaElementSource( mediaElement );
  36913. this.connect();
  36914. return this;
  36915. }
  36916. /**
  36917. * Sets the given media stream as the source of this instance.
  36918. *
  36919. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36920. *
  36921. * @param {MediaStream} mediaStream - The media stream.
  36922. * @return {Audio} A reference to this instance.
  36923. */
  36924. setMediaStreamSource( mediaStream ) {
  36925. this.hasPlaybackControl = false;
  36926. this.sourceType = 'mediaStreamNode';
  36927. this.source = this.context.createMediaStreamSource( mediaStream );
  36928. this.connect();
  36929. return this;
  36930. }
  36931. /**
  36932. * Sets the given audio buffer as the source of this instance.
  36933. *
  36934. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36935. *
  36936. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36937. * @return {Audio} A reference to this instance.
  36938. */
  36939. setBuffer( audioBuffer ) {
  36940. this.buffer = audioBuffer;
  36941. this.sourceType = 'buffer';
  36942. if ( this.autoplay ) this.play();
  36943. return this;
  36944. }
  36945. /**
  36946. * Starts the playback of the audio.
  36947. *
  36948. * Can only be used with compatible audio sources that allow playback control.
  36949. *
  36950. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36951. * @return {Audio|undefined} A reference to this instance.
  36952. */
  36953. play( delay = 0 ) {
  36954. if ( this.isPlaying === true ) {
  36955. warn( 'Audio: Audio is already playing.' );
  36956. return;
  36957. }
  36958. if ( this.hasPlaybackControl === false ) {
  36959. warn( 'Audio: this Audio has no playback control.' );
  36960. return;
  36961. }
  36962. this._startedAt = this.context.currentTime + delay;
  36963. const source = this.context.createBufferSource();
  36964. source.buffer = this.buffer;
  36965. source.loop = this.loop;
  36966. source.loopStart = this.loopStart;
  36967. source.loopEnd = this.loopEnd;
  36968. source.onended = this.onEnded.bind( this );
  36969. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36970. this.isPlaying = true;
  36971. this.source = source;
  36972. this.setDetune( this.detune );
  36973. this.setPlaybackRate( this.playbackRate );
  36974. return this.connect();
  36975. }
  36976. /**
  36977. * Pauses the playback of the audio.
  36978. *
  36979. * Can only be used with compatible audio sources that allow playback control.
  36980. *
  36981. * @return {Audio|undefined} A reference to this instance.
  36982. */
  36983. pause() {
  36984. if ( this.hasPlaybackControl === false ) {
  36985. warn( 'Audio: this Audio has no playback control.' );
  36986. return;
  36987. }
  36988. if ( this.isPlaying === true ) {
  36989. // update current progress
  36990. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36991. if ( this.loop === true ) {
  36992. // ensure _progress does not exceed duration with looped audios
  36993. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36994. }
  36995. this.source.stop();
  36996. this.source.onended = null;
  36997. this.isPlaying = false;
  36998. }
  36999. return this;
  37000. }
  37001. /**
  37002. * Stops the playback of the audio.
  37003. *
  37004. * Can only be used with compatible audio sources that allow playback control.
  37005. *
  37006. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  37007. * @return {Audio|undefined} A reference to this instance.
  37008. */
  37009. stop( delay = 0 ) {
  37010. if ( this.hasPlaybackControl === false ) {
  37011. warn( 'Audio: this Audio has no playback control.' );
  37012. return;
  37013. }
  37014. this._progress = 0;
  37015. if ( this.source !== null ) {
  37016. this.source.stop( this.context.currentTime + delay );
  37017. this.source.onended = null;
  37018. }
  37019. this.isPlaying = false;
  37020. return this;
  37021. }
  37022. /**
  37023. * Connects to the audio source. This is used internally on
  37024. * initialisation and when setting / removing filters.
  37025. *
  37026. * @return {Audio} A reference to this instance.
  37027. */
  37028. connect() {
  37029. if ( this.filters.length > 0 ) {
  37030. this.source.connect( this.filters[ 0 ] );
  37031. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37032. this.filters[ i - 1 ].connect( this.filters[ i ] );
  37033. }
  37034. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  37035. } else {
  37036. this.source.connect( this.getOutput() );
  37037. }
  37038. this._connected = true;
  37039. return this;
  37040. }
  37041. /**
  37042. * Disconnects to the audio source. This is used internally on
  37043. * initialisation and when setting / removing filters.
  37044. *
  37045. * @return {Audio|undefined} A reference to this instance.
  37046. */
  37047. disconnect() {
  37048. if ( this._connected === false ) {
  37049. return;
  37050. }
  37051. if ( this.filters.length > 0 ) {
  37052. this.source.disconnect( this.filters[ 0 ] );
  37053. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37054. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  37055. }
  37056. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  37057. } else {
  37058. this.source.disconnect( this.getOutput() );
  37059. }
  37060. this._connected = false;
  37061. return this;
  37062. }
  37063. /**
  37064. * Returns the current set filters.
  37065. *
  37066. * @return {Array<AudioNode>} The list of filters.
  37067. */
  37068. getFilters() {
  37069. return this.filters;
  37070. }
  37071. /**
  37072. * Sets an array of filters and connects them with the audio source.
  37073. *
  37074. * @param {Array<AudioNode>} [value] - A list of filters.
  37075. * @return {Audio} A reference to this instance.
  37076. */
  37077. setFilters( value ) {
  37078. if ( ! value ) value = [];
  37079. if ( this._connected === true ) {
  37080. this.disconnect();
  37081. this.filters = value.slice();
  37082. this.connect();
  37083. } else {
  37084. this.filters = value.slice();
  37085. }
  37086. return this;
  37087. }
  37088. /**
  37089. * Defines the detuning of oscillation in cents.
  37090. *
  37091. * @param {number} value - The detuning of oscillation in cents.
  37092. * @return {Audio} A reference to this instance.
  37093. */
  37094. setDetune( value ) {
  37095. this.detune = value;
  37096. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  37097. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  37098. }
  37099. return this;
  37100. }
  37101. /**
  37102. * Returns the detuning of oscillation in cents.
  37103. *
  37104. * @return {number} The detuning of oscillation in cents.
  37105. */
  37106. getDetune() {
  37107. return this.detune;
  37108. }
  37109. /**
  37110. * Returns the first filter in the list of filters.
  37111. *
  37112. * @return {AudioNode|undefined} The first filter in the list of filters.
  37113. */
  37114. getFilter() {
  37115. return this.getFilters()[ 0 ];
  37116. }
  37117. /**
  37118. * Applies a single filter node to the audio.
  37119. *
  37120. * @param {AudioNode} [filter] - The filter to set.
  37121. * @return {Audio} A reference to this instance.
  37122. */
  37123. setFilter( filter ) {
  37124. return this.setFilters( filter ? [ filter ] : [] );
  37125. }
  37126. /**
  37127. * Sets the playback rate.
  37128. *
  37129. * Can only be used with compatible audio sources that allow playback control.
  37130. *
  37131. * @param {number} [value] - The playback rate to set.
  37132. * @return {Audio|undefined} A reference to this instance.
  37133. */
  37134. setPlaybackRate( value ) {
  37135. if ( this.hasPlaybackControl === false ) {
  37136. warn( 'Audio: this Audio has no playback control.' );
  37137. return;
  37138. }
  37139. this.playbackRate = value;
  37140. if ( this.isPlaying === true ) {
  37141. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  37142. }
  37143. return this;
  37144. }
  37145. /**
  37146. * Returns the current playback rate.
  37147. * @return {number} The playback rate.
  37148. */
  37149. getPlaybackRate() {
  37150. return this.playbackRate;
  37151. }
  37152. /**
  37153. * Automatically called when playback finished.
  37154. */
  37155. onEnded() {
  37156. this.isPlaying = false;
  37157. this._progress = 0;
  37158. }
  37159. /**
  37160. * Returns the loop flag.
  37161. *
  37162. * Can only be used with compatible audio sources that allow playback control.
  37163. *
  37164. * @return {boolean} Whether the audio should loop or not.
  37165. */
  37166. getLoop() {
  37167. if ( this.hasPlaybackControl === false ) {
  37168. warn( 'Audio: this Audio has no playback control.' );
  37169. return false;
  37170. }
  37171. return this.loop;
  37172. }
  37173. /**
  37174. * Sets the loop flag.
  37175. *
  37176. * Can only be used with compatible audio sources that allow playback control.
  37177. *
  37178. * @param {boolean} value - Whether the audio should loop or not.
  37179. * @return {Audio|undefined} A reference to this instance.
  37180. */
  37181. setLoop( value ) {
  37182. if ( this.hasPlaybackControl === false ) {
  37183. warn( 'Audio: this Audio has no playback control.' );
  37184. return;
  37185. }
  37186. this.loop = value;
  37187. if ( this.isPlaying === true ) {
  37188. this.source.loop = this.loop;
  37189. }
  37190. return this;
  37191. }
  37192. /**
  37193. * Sets the loop start value which defines where in the audio buffer the replay should
  37194. * start, in seconds.
  37195. *
  37196. * @param {number} value - The loop start value.
  37197. * @return {Audio} A reference to this instance.
  37198. */
  37199. setLoopStart( value ) {
  37200. this.loopStart = value;
  37201. return this;
  37202. }
  37203. /**
  37204. * Sets the loop end value which defines where in the audio buffer the replay should
  37205. * stop, in seconds.
  37206. *
  37207. * @param {number} value - The loop end value.
  37208. * @return {Audio} A reference to this instance.
  37209. */
  37210. setLoopEnd( value ) {
  37211. this.loopEnd = value;
  37212. return this;
  37213. }
  37214. /**
  37215. * Returns the volume.
  37216. *
  37217. * @return {number} The volume.
  37218. */
  37219. getVolume() {
  37220. return this.gain.gain.value;
  37221. }
  37222. /**
  37223. * Sets the volume.
  37224. *
  37225. * @param {number} value - The volume to set.
  37226. * @return {Audio} A reference to this instance.
  37227. */
  37228. setVolume( value ) {
  37229. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37230. return this;
  37231. }
  37232. copy( source, recursive ) {
  37233. super.copy( source, recursive );
  37234. if ( source.sourceType !== 'buffer' ) {
  37235. warn( 'Audio: Audio source type cannot be copied.' );
  37236. return this;
  37237. }
  37238. this.autoplay = source.autoplay;
  37239. this.buffer = source.buffer;
  37240. this.detune = source.detune;
  37241. this.loop = source.loop;
  37242. this.loopStart = source.loopStart;
  37243. this.loopEnd = source.loopEnd;
  37244. this.offset = source.offset;
  37245. this.duration = source.duration;
  37246. this.playbackRate = source.playbackRate;
  37247. this.hasPlaybackControl = source.hasPlaybackControl;
  37248. this.sourceType = source.sourceType;
  37249. this.filters = source.filters.slice();
  37250. return this;
  37251. }
  37252. clone( recursive ) {
  37253. return new this.constructor( this.listener ).copy( this, recursive );
  37254. }
  37255. }
  37256. const _position = /*@__PURE__*/ new Vector3();
  37257. const _quaternion = /*@__PURE__*/ new Quaternion();
  37258. const _scale = /*@__PURE__*/ new Vector3();
  37259. const _orientation = /*@__PURE__*/ new Vector3();
  37260. /**
  37261. * Represents a positional audio object.
  37262. *
  37263. * ```js
  37264. * // create an AudioListener and add it to the camera
  37265. * const listener = new THREE.AudioListener();
  37266. * camera.add( listener );
  37267. *
  37268. * // create the PositionalAudio object (passing in the listener)
  37269. * const sound = new THREE.PositionalAudio( listener );
  37270. *
  37271. * // load a sound and set it as the PositionalAudio object's buffer
  37272. * const audioLoader = new THREE.AudioLoader();
  37273. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  37274. * sound.setBuffer( buffer );
  37275. * sound.setRefDistance( 20 );
  37276. * sound.play();
  37277. * });
  37278. *
  37279. * // create an object for the sound to play from
  37280. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  37281. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  37282. * const mesh = new THREE.Mesh( sphere, material );
  37283. * scene.add( mesh );
  37284. *
  37285. * // finally add the sound to the mesh
  37286. * mesh.add( sound );
  37287. *
  37288. * @augments Audio
  37289. */
  37290. class PositionalAudio extends Audio {
  37291. /**
  37292. * Constructs a positional audio.
  37293. *
  37294. * @param {AudioListener} listener - The global audio listener.
  37295. */
  37296. constructor( listener ) {
  37297. super( listener );
  37298. /**
  37299. * The panner node represents the location, direction, and behavior of an audio
  37300. * source in 3D space.
  37301. *
  37302. * @type {PannerNode}
  37303. * @readonly
  37304. */
  37305. this.panner = this.context.createPanner();
  37306. this.panner.panningModel = 'HRTF';
  37307. this.panner.connect( this.gain );
  37308. }
  37309. connect() {
  37310. super.connect();
  37311. this.panner.connect( this.gain );
  37312. return this;
  37313. }
  37314. disconnect() {
  37315. super.disconnect();
  37316. this.panner.disconnect( this.gain );
  37317. return this;
  37318. }
  37319. getOutput() {
  37320. return this.panner;
  37321. }
  37322. /**
  37323. * Returns the current reference distance.
  37324. *
  37325. * @return {number} The reference distance.
  37326. */
  37327. getRefDistance() {
  37328. return this.panner.refDistance;
  37329. }
  37330. /**
  37331. * Defines the reference distance for reducing volume as the audio source moves
  37332. * further from the listener – i.e. the distance at which the volume reduction
  37333. * starts taking effect.
  37334. *
  37335. * @param {number} value - The reference distance to set.
  37336. * @return {PositionalAudio} A reference to this instance.
  37337. */
  37338. setRefDistance( value ) {
  37339. this.panner.refDistance = value;
  37340. return this;
  37341. }
  37342. /**
  37343. * Returns the current rolloff factor.
  37344. *
  37345. * @return {number} The rolloff factor.
  37346. */
  37347. getRolloffFactor() {
  37348. return this.panner.rolloffFactor;
  37349. }
  37350. /**
  37351. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37352. *
  37353. * @param {number} value - The rolloff factor.
  37354. * @return {PositionalAudio} A reference to this instance.
  37355. */
  37356. setRolloffFactor( value ) {
  37357. this.panner.rolloffFactor = value;
  37358. return this;
  37359. }
  37360. /**
  37361. * Returns the current distance model.
  37362. *
  37363. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37364. */
  37365. getDistanceModel() {
  37366. return this.panner.distanceModel;
  37367. }
  37368. /**
  37369. * Defines which algorithm to use to reduce the volume of the audio source
  37370. * as it moves away from the listener.
  37371. *
  37372. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37373. * for more details.
  37374. *
  37375. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37376. * @return {PositionalAudio} A reference to this instance.
  37377. */
  37378. setDistanceModel( value ) {
  37379. this.panner.distanceModel = value;
  37380. return this;
  37381. }
  37382. /**
  37383. * Returns the current max distance.
  37384. *
  37385. * @return {number} The max distance.
  37386. */
  37387. getMaxDistance() {
  37388. return this.panner.maxDistance;
  37389. }
  37390. /**
  37391. * Defines the maximum distance between the audio source and the listener,
  37392. * after which the volume is not reduced any further.
  37393. *
  37394. * This value is used only by the `linear` distance model.
  37395. *
  37396. * @param {number} value - The max distance.
  37397. * @return {PositionalAudio} A reference to this instance.
  37398. */
  37399. setMaxDistance( value ) {
  37400. this.panner.maxDistance = value;
  37401. return this;
  37402. }
  37403. /**
  37404. * Sets the directional cone in which the audio can be listened.
  37405. *
  37406. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37407. * @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.
  37408. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37409. * @return {PositionalAudio} A reference to this instance.
  37410. */
  37411. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37412. this.panner.coneInnerAngle = coneInnerAngle;
  37413. this.panner.coneOuterAngle = coneOuterAngle;
  37414. this.panner.coneOuterGain = coneOuterGain;
  37415. return this;
  37416. }
  37417. updateMatrixWorld( force ) {
  37418. super.updateMatrixWorld( force );
  37419. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37420. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37421. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37422. const panner = this.panner;
  37423. if ( panner.positionX ) {
  37424. // code path for Chrome and Firefox (see #14393)
  37425. const endTime = this.context.currentTime + this.listener.timeDelta;
  37426. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37427. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37428. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37429. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37430. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37431. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37432. } else {
  37433. panner.setPosition( _position.x, _position.y, _position.z );
  37434. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37435. }
  37436. }
  37437. }
  37438. /**
  37439. * This class can be used to analyse audio data.
  37440. *
  37441. * ```js
  37442. * // create an AudioListener and add it to the camera
  37443. * const listener = new THREE.AudioListener();
  37444. * camera.add( listener );
  37445. *
  37446. * // create an Audio source
  37447. * const sound = new THREE.Audio( listener );
  37448. *
  37449. * // load a sound and set it as the Audio object's buffer
  37450. * const audioLoader = new THREE.AudioLoader();
  37451. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37452. * sound.setBuffer( buffer );
  37453. * sound.setLoop(true);
  37454. * sound.setVolume(0.5);
  37455. * sound.play();
  37456. * });
  37457. *
  37458. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37459. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37460. *
  37461. * // get the average frequency of the sound
  37462. * const data = analyser.getAverageFrequency();
  37463. * ```
  37464. */
  37465. class AudioAnalyser {
  37466. /**
  37467. * Constructs a new audio analyzer.
  37468. *
  37469. * @param {Audio} audio - The audio to analyze.
  37470. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37471. */
  37472. constructor( audio, fftSize = 2048 ) {
  37473. /**
  37474. * The global audio listener.
  37475. *
  37476. * @type {AnalyserNode}
  37477. */
  37478. this.analyser = audio.context.createAnalyser();
  37479. this.analyser.fftSize = fftSize;
  37480. /**
  37481. * Holds the analyzed data.
  37482. *
  37483. * @type {Uint8Array}
  37484. */
  37485. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37486. audio.getOutput().connect( this.analyser );
  37487. }
  37488. /**
  37489. * Returns an array with frequency data of the audio.
  37490. *
  37491. * Each item in the array represents the decibel value for a specific frequency.
  37492. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37493. * For example, for 48000 sample rate, the last item of the array will represent
  37494. * the decibel value for 24000 Hz.
  37495. *
  37496. * @return {Uint8Array} The frequency data.
  37497. */
  37498. getFrequencyData() {
  37499. this.analyser.getByteFrequencyData( this.data );
  37500. return this.data;
  37501. }
  37502. /**
  37503. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37504. *
  37505. * @return {number} The average frequency.
  37506. */
  37507. getAverageFrequency() {
  37508. let value = 0;
  37509. const data = this.getFrequencyData();
  37510. for ( let i = 0; i < data.length; i ++ ) {
  37511. value += data[ i ];
  37512. }
  37513. return value / data.length;
  37514. }
  37515. }
  37516. /**
  37517. * Buffered scene graph property that allows weighted accumulation; used internally.
  37518. */
  37519. class PropertyMixer {
  37520. /**
  37521. * Constructs a new property mixer.
  37522. *
  37523. * @param {PropertyBinding} binding - The property binding.
  37524. * @param {string} typeName - The keyframe track type name.
  37525. * @param {number} valueSize - The keyframe track value size.
  37526. */
  37527. constructor( binding, typeName, valueSize ) {
  37528. /**
  37529. * The property binding.
  37530. *
  37531. * @type {PropertyBinding}
  37532. */
  37533. this.binding = binding;
  37534. /**
  37535. * The keyframe track value size.
  37536. *
  37537. * @type {number}
  37538. */
  37539. this.valueSize = valueSize;
  37540. let mixFunction,
  37541. mixFunctionAdditive,
  37542. setIdentity;
  37543. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37544. //
  37545. // interpolators can use .buffer as their .result
  37546. // the data then goes to 'incoming'
  37547. //
  37548. // 'accu0' and 'accu1' are used frame-interleaved for
  37549. // the cumulative result and are compared to detect
  37550. // changes
  37551. //
  37552. // 'orig' stores the original state of the property
  37553. //
  37554. // 'add' is used for additive cumulative results
  37555. //
  37556. // 'work' is optional and is only present for quaternion types. It is used
  37557. // to store intermediate quaternion multiplication results
  37558. switch ( typeName ) {
  37559. case 'quaternion':
  37560. mixFunction = this._slerp;
  37561. mixFunctionAdditive = this._slerpAdditive;
  37562. setIdentity = this._setAdditiveIdentityQuaternion;
  37563. this.buffer = new Float64Array( valueSize * 6 );
  37564. this._workIndex = 5;
  37565. break;
  37566. case 'string':
  37567. case 'bool':
  37568. mixFunction = this._select;
  37569. // Use the regular mix function and for additive on these types,
  37570. // additive is not relevant for non-numeric types
  37571. mixFunctionAdditive = this._select;
  37572. setIdentity = this._setAdditiveIdentityOther;
  37573. this.buffer = new Array( valueSize * 5 );
  37574. break;
  37575. default:
  37576. mixFunction = this._lerp;
  37577. mixFunctionAdditive = this._lerpAdditive;
  37578. setIdentity = this._setAdditiveIdentityNumeric;
  37579. this.buffer = new Float64Array( valueSize * 5 );
  37580. }
  37581. this._mixBufferRegion = mixFunction;
  37582. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37583. this._setIdentity = setIdentity;
  37584. this._origIndex = 3;
  37585. this._addIndex = 4;
  37586. /**
  37587. * Accumulated weight of the property binding.
  37588. *
  37589. * @type {number}
  37590. * @default 0
  37591. */
  37592. this.cumulativeWeight = 0;
  37593. /**
  37594. * Accumulated additive weight of the property binding.
  37595. *
  37596. * @type {number}
  37597. * @default 0
  37598. */
  37599. this.cumulativeWeightAdditive = 0;
  37600. /**
  37601. * Number of active keyframe tracks currently using this property binding.
  37602. *
  37603. * @type {number}
  37604. * @default 0
  37605. */
  37606. this.useCount = 0;
  37607. /**
  37608. * Number of keyframe tracks referencing this property binding.
  37609. *
  37610. * @type {number}
  37611. * @default 0
  37612. */
  37613. this.referenceCount = 0;
  37614. }
  37615. /**
  37616. * Accumulates data in the `incoming` region into `accu<i>`.
  37617. *
  37618. * @param {number} accuIndex - The accumulation index.
  37619. * @param {number} weight - The weight.
  37620. */
  37621. accumulate( accuIndex, weight ) {
  37622. // note: happily accumulating nothing when weight = 0, the caller knows
  37623. // the weight and shouldn't have made the call in the first place
  37624. const buffer = this.buffer,
  37625. stride = this.valueSize,
  37626. offset = accuIndex * stride + stride;
  37627. let currentWeight = this.cumulativeWeight;
  37628. if ( currentWeight === 0 ) {
  37629. // accuN := incoming * weight
  37630. for ( let i = 0; i !== stride; ++ i ) {
  37631. buffer[ offset + i ] = buffer[ i ];
  37632. }
  37633. currentWeight = weight;
  37634. } else {
  37635. // accuN := accuN + incoming * weight
  37636. currentWeight += weight;
  37637. const mix = weight / currentWeight;
  37638. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37639. }
  37640. this.cumulativeWeight = currentWeight;
  37641. }
  37642. /**
  37643. * Accumulates data in the `incoming` region into `add`.
  37644. *
  37645. * @param {number} weight - The weight.
  37646. */
  37647. accumulateAdditive( weight ) {
  37648. const buffer = this.buffer,
  37649. stride = this.valueSize,
  37650. offset = stride * this._addIndex;
  37651. if ( this.cumulativeWeightAdditive === 0 ) {
  37652. // add = identity
  37653. this._setIdentity();
  37654. }
  37655. // add := add + incoming * weight
  37656. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37657. this.cumulativeWeightAdditive += weight;
  37658. }
  37659. /**
  37660. * Applies the state of `accu<i>` to the binding when accus differ.
  37661. *
  37662. * @param {number} accuIndex - The accumulation index.
  37663. */
  37664. apply( accuIndex ) {
  37665. const stride = this.valueSize,
  37666. buffer = this.buffer,
  37667. offset = accuIndex * stride + stride,
  37668. weight = this.cumulativeWeight,
  37669. weightAdditive = this.cumulativeWeightAdditive,
  37670. binding = this.binding;
  37671. this.cumulativeWeight = 0;
  37672. this.cumulativeWeightAdditive = 0;
  37673. if ( weight < 1 ) {
  37674. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37675. const originalValueOffset = stride * this._origIndex;
  37676. this._mixBufferRegion(
  37677. buffer, offset, originalValueOffset, 1 - weight, stride );
  37678. }
  37679. if ( weightAdditive > 0 ) {
  37680. // accuN := accuN + additive accuN
  37681. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37682. }
  37683. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37684. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37685. // value has changed -> update scene graph
  37686. binding.setValue( buffer, offset );
  37687. break;
  37688. }
  37689. }
  37690. }
  37691. /**
  37692. * Remembers the state of the bound property and copy it to both accus.
  37693. */
  37694. saveOriginalState() {
  37695. const binding = this.binding;
  37696. const buffer = this.buffer,
  37697. stride = this.valueSize,
  37698. originalValueOffset = stride * this._origIndex;
  37699. binding.getValue( buffer, originalValueOffset );
  37700. // accu[0..1] := orig -- initially detect changes against the original
  37701. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37702. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37703. }
  37704. // Add to identity for additive
  37705. this._setIdentity();
  37706. this.cumulativeWeight = 0;
  37707. this.cumulativeWeightAdditive = 0;
  37708. }
  37709. /**
  37710. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37711. */
  37712. restoreOriginalState() {
  37713. const originalValueOffset = this.valueSize * 3;
  37714. this.binding.setValue( this.buffer, originalValueOffset );
  37715. }
  37716. // internals
  37717. _setAdditiveIdentityNumeric() {
  37718. const startIndex = this._addIndex * this.valueSize;
  37719. const endIndex = startIndex + this.valueSize;
  37720. for ( let i = startIndex; i < endIndex; i ++ ) {
  37721. this.buffer[ i ] = 0;
  37722. }
  37723. }
  37724. _setAdditiveIdentityQuaternion() {
  37725. this._setAdditiveIdentityNumeric();
  37726. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37727. }
  37728. _setAdditiveIdentityOther() {
  37729. const startIndex = this._origIndex * this.valueSize;
  37730. const targetIndex = this._addIndex * this.valueSize;
  37731. for ( let i = 0; i < this.valueSize; i ++ ) {
  37732. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37733. }
  37734. }
  37735. // mix functions
  37736. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37737. if ( t >= 0.5 ) {
  37738. for ( let i = 0; i !== stride; ++ i ) {
  37739. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37740. }
  37741. }
  37742. }
  37743. _slerp( buffer, dstOffset, srcOffset, t ) {
  37744. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37745. }
  37746. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37747. const workOffset = this._workIndex * stride;
  37748. // Store result in intermediate buffer offset
  37749. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37750. // Slerp to the intermediate result
  37751. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37752. }
  37753. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37754. const s = 1 - t;
  37755. for ( let i = 0; i !== stride; ++ i ) {
  37756. const j = dstOffset + i;
  37757. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37758. }
  37759. }
  37760. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37761. for ( let i = 0; i !== stride; ++ i ) {
  37762. const j = dstOffset + i;
  37763. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37764. }
  37765. }
  37766. }
  37767. // Characters [].:/ are reserved for track binding syntax.
  37768. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37769. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37770. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37771. // only latin characters, and the unicode \p{L} is not yet supported. So
  37772. // instead, we exclude reserved characters and match everything else.
  37773. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37774. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37775. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37776. // be matched to parse the rest of the track name.
  37777. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37778. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37779. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37780. // Object on target node, and accessor. May not contain reserved
  37781. // characters. Accessor may contain any character except closing bracket.
  37782. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37783. // Property and accessor. May not contain reserved characters. Accessor may
  37784. // contain any non-bracket characters.
  37785. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37786. const _trackRe = new RegExp( ''
  37787. + '^'
  37788. + _directoryRe
  37789. + _nodeRe
  37790. + _objectRe
  37791. + _propertyRe
  37792. + '$'
  37793. );
  37794. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37795. class Composite {
  37796. constructor( targetGroup, path, optionalParsedPath ) {
  37797. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37798. this._targetGroup = targetGroup;
  37799. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37800. }
  37801. getValue( array, offset ) {
  37802. this.bind(); // bind all binding
  37803. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37804. binding = this._bindings[ firstValidIndex ];
  37805. // and only call .getValue on the first
  37806. if ( binding !== undefined ) binding.getValue( array, offset );
  37807. }
  37808. setValue( array, offset ) {
  37809. const bindings = this._bindings;
  37810. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37811. bindings[ i ].setValue( array, offset );
  37812. }
  37813. }
  37814. bind() {
  37815. const bindings = this._bindings;
  37816. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37817. bindings[ i ].bind();
  37818. }
  37819. }
  37820. unbind() {
  37821. const bindings = this._bindings;
  37822. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37823. bindings[ i ].unbind();
  37824. }
  37825. }
  37826. }
  37827. // Note: This class uses a State pattern on a per-method basis:
  37828. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37829. // prototype version of these methods with one that represents
  37830. // the bound state. When the property is not found, the methods
  37831. // become no-ops.
  37832. /**
  37833. * This holds a reference to a real property in the scene graph; used internally.
  37834. */
  37835. class PropertyBinding {
  37836. /**
  37837. * Constructs a new property binding.
  37838. *
  37839. * @param {Object} rootNode - The root node.
  37840. * @param {string} path - The path.
  37841. * @param {?Object} [parsedPath] - The parsed path.
  37842. */
  37843. constructor( rootNode, path, parsedPath ) {
  37844. /**
  37845. * The object path to the animated property.
  37846. *
  37847. * @type {string}
  37848. */
  37849. this.path = path;
  37850. /**
  37851. * An object holding information about the path.
  37852. *
  37853. * @type {Object}
  37854. */
  37855. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37856. /**
  37857. * The object owns the animated property.
  37858. *
  37859. * @type {?Object}
  37860. */
  37861. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37862. /**
  37863. * The root node.
  37864. *
  37865. * @type {Object3D|Skeleton}
  37866. */
  37867. this.rootNode = rootNode;
  37868. // initial state of these methods that calls 'bind'
  37869. this.getValue = this._getValue_unbound;
  37870. this.setValue = this._setValue_unbound;
  37871. }
  37872. /**
  37873. * Factory method for creating a property binding from the given parameters.
  37874. *
  37875. * @static
  37876. * @param {Object} root - The root node.
  37877. * @param {string} path - The path.
  37878. * @param {?Object} [parsedPath] - The parsed path.
  37879. * @return {PropertyBinding|Composite} The created property binding or composite.
  37880. */
  37881. static create( root, path, parsedPath ) {
  37882. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37883. return new PropertyBinding( root, path, parsedPath );
  37884. } else {
  37885. return new PropertyBinding.Composite( root, path, parsedPath );
  37886. }
  37887. }
  37888. /**
  37889. * Replaces spaces with underscores and removes unsupported characters from
  37890. * node names, to ensure compatibility with parseTrackName().
  37891. *
  37892. * @param {string} name - Node name to be sanitized.
  37893. * @return {string} The sanitized node name.
  37894. */
  37895. static sanitizeNodeName( name ) {
  37896. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37897. }
  37898. /**
  37899. * Parses the given track name (an object path to an animated property) and
  37900. * returns an object with information about the path. Matches strings in the following forms:
  37901. *
  37902. * - nodeName.property
  37903. * - nodeName.property[accessor]
  37904. * - nodeName.material.property[accessor]
  37905. * - uuid.property[accessor]
  37906. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37907. * - parentName/nodeName.property
  37908. * - parentName/parentName/nodeName.property[index]
  37909. * - .bone[Armature.DEF_cog].position
  37910. * - scene:helium_balloon_model:helium_balloon_model.position
  37911. *
  37912. * @static
  37913. * @param {string} trackName - The track name to parse.
  37914. * @return {Object} The parsed track name as an object.
  37915. */
  37916. static parseTrackName( trackName ) {
  37917. const matches = _trackRe.exec( trackName );
  37918. if ( matches === null ) {
  37919. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37920. }
  37921. const results = {
  37922. // directoryName: matches[ 1 ], // (tschw) currently unused
  37923. nodeName: matches[ 2 ],
  37924. objectName: matches[ 3 ],
  37925. objectIndex: matches[ 4 ],
  37926. propertyName: matches[ 5 ], // required
  37927. propertyIndex: matches[ 6 ]
  37928. };
  37929. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37930. if ( lastDot !== undefined && lastDot !== -1 ) {
  37931. const objectName = results.nodeName.substring( lastDot + 1 );
  37932. // Object names must be checked against an allowlist. Otherwise, there
  37933. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37934. // 'bar' could be the objectName, or part of a nodeName (which can
  37935. // include '.' characters).
  37936. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37937. results.nodeName = results.nodeName.substring( 0, lastDot );
  37938. results.objectName = objectName;
  37939. }
  37940. }
  37941. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37942. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37943. }
  37944. return results;
  37945. }
  37946. /**
  37947. * Searches for a node in the hierarchy of the given root object by the given
  37948. * node name.
  37949. *
  37950. * @static
  37951. * @param {Object} root - The root object.
  37952. * @param {string|number} nodeName - The name of the node.
  37953. * @return {?Object} The found node. Returns `null` if no object was found.
  37954. */
  37955. static findNode( root, nodeName ) {
  37956. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37957. return root;
  37958. }
  37959. // search into skeleton bones.
  37960. if ( root.skeleton ) {
  37961. const bone = root.skeleton.getBoneByName( nodeName );
  37962. if ( bone !== undefined ) {
  37963. return bone;
  37964. }
  37965. }
  37966. // search into node subtree.
  37967. if ( root.children ) {
  37968. const searchNodeSubtree = function ( children ) {
  37969. for ( let i = 0; i < children.length; i ++ ) {
  37970. const childNode = children[ i ];
  37971. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37972. return childNode;
  37973. }
  37974. const result = searchNodeSubtree( childNode.children );
  37975. if ( result ) return result;
  37976. }
  37977. return null;
  37978. };
  37979. const subTreeNode = searchNodeSubtree( root.children );
  37980. if ( subTreeNode ) {
  37981. return subTreeNode;
  37982. }
  37983. }
  37984. return null;
  37985. }
  37986. // these are used to "bind" a nonexistent property
  37987. _getValue_unavailable() {}
  37988. _setValue_unavailable() {}
  37989. // Getters
  37990. _getValue_direct( buffer, offset ) {
  37991. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37992. }
  37993. _getValue_array( buffer, offset ) {
  37994. const source = this.resolvedProperty;
  37995. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37996. buffer[ offset ++ ] = source[ i ];
  37997. }
  37998. }
  37999. _getValue_arrayElement( buffer, offset ) {
  38000. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  38001. }
  38002. _getValue_toArray( buffer, offset ) {
  38003. this.resolvedProperty.toArray( buffer, offset );
  38004. }
  38005. // Direct
  38006. _setValue_direct( buffer, offset ) {
  38007. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38008. }
  38009. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  38010. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38011. this.targetObject.needsUpdate = true;
  38012. }
  38013. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38014. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38015. this.targetObject.matrixWorldNeedsUpdate = true;
  38016. }
  38017. // EntireArray
  38018. _setValue_array( buffer, offset ) {
  38019. const dest = this.resolvedProperty;
  38020. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38021. dest[ i ] = buffer[ offset ++ ];
  38022. }
  38023. }
  38024. _setValue_array_setNeedsUpdate( buffer, offset ) {
  38025. const dest = this.resolvedProperty;
  38026. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38027. dest[ i ] = buffer[ offset ++ ];
  38028. }
  38029. this.targetObject.needsUpdate = true;
  38030. }
  38031. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38032. const dest = this.resolvedProperty;
  38033. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38034. dest[ i ] = buffer[ offset ++ ];
  38035. }
  38036. this.targetObject.matrixWorldNeedsUpdate = true;
  38037. }
  38038. // ArrayElement
  38039. _setValue_arrayElement( buffer, offset ) {
  38040. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38041. }
  38042. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  38043. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38044. this.targetObject.needsUpdate = true;
  38045. }
  38046. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38047. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38048. this.targetObject.matrixWorldNeedsUpdate = true;
  38049. }
  38050. // HasToFromArray
  38051. _setValue_fromArray( buffer, offset ) {
  38052. this.resolvedProperty.fromArray( buffer, offset );
  38053. }
  38054. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  38055. this.resolvedProperty.fromArray( buffer, offset );
  38056. this.targetObject.needsUpdate = true;
  38057. }
  38058. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38059. this.resolvedProperty.fromArray( buffer, offset );
  38060. this.targetObject.matrixWorldNeedsUpdate = true;
  38061. }
  38062. _getValue_unbound( targetArray, offset ) {
  38063. this.bind();
  38064. this.getValue( targetArray, offset );
  38065. }
  38066. _setValue_unbound( sourceArray, offset ) {
  38067. this.bind();
  38068. this.setValue( sourceArray, offset );
  38069. }
  38070. /**
  38071. * Creates a getter / setter pair for the property tracked by this binding.
  38072. */
  38073. bind() {
  38074. let targetObject = this.node;
  38075. const parsedPath = this.parsedPath;
  38076. const objectName = parsedPath.objectName;
  38077. const propertyName = parsedPath.propertyName;
  38078. let propertyIndex = parsedPath.propertyIndex;
  38079. if ( ! targetObject ) {
  38080. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  38081. this.node = targetObject;
  38082. }
  38083. // set fail state so we can just 'return' on error
  38084. this.getValue = this._getValue_unavailable;
  38085. this.setValue = this._setValue_unavailable;
  38086. // ensure there is a value node
  38087. if ( ! targetObject ) {
  38088. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  38089. return;
  38090. }
  38091. if ( objectName ) {
  38092. let objectIndex = parsedPath.objectIndex;
  38093. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  38094. switch ( objectName ) {
  38095. case 'materials':
  38096. if ( ! targetObject.material ) {
  38097. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38098. return;
  38099. }
  38100. if ( ! targetObject.material.materials ) {
  38101. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  38102. return;
  38103. }
  38104. targetObject = targetObject.material.materials;
  38105. break;
  38106. case 'bones':
  38107. if ( ! targetObject.skeleton ) {
  38108. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  38109. return;
  38110. }
  38111. // potential future optimization: skip this if propertyIndex is already an integer
  38112. // and convert the integer string to a true integer.
  38113. targetObject = targetObject.skeleton.bones;
  38114. // support resolving morphTarget names into indices.
  38115. for ( let i = 0; i < targetObject.length; i ++ ) {
  38116. if ( targetObject[ i ].name === objectIndex ) {
  38117. objectIndex = i;
  38118. break;
  38119. }
  38120. }
  38121. break;
  38122. case 'map':
  38123. if ( 'map' in targetObject ) {
  38124. targetObject = targetObject.map;
  38125. break;
  38126. }
  38127. if ( ! targetObject.material ) {
  38128. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38129. return;
  38130. }
  38131. if ( ! targetObject.material.map ) {
  38132. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  38133. return;
  38134. }
  38135. targetObject = targetObject.material.map;
  38136. break;
  38137. default:
  38138. if ( targetObject[ objectName ] === undefined ) {
  38139. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  38140. return;
  38141. }
  38142. targetObject = targetObject[ objectName ];
  38143. }
  38144. if ( objectIndex !== undefined ) {
  38145. if ( targetObject[ objectIndex ] === undefined ) {
  38146. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  38147. return;
  38148. }
  38149. targetObject = targetObject[ objectIndex ];
  38150. }
  38151. }
  38152. // resolve property
  38153. const nodeProperty = targetObject[ propertyName ];
  38154. if ( nodeProperty === undefined ) {
  38155. const nodeName = parsedPath.nodeName;
  38156. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  38157. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  38158. return;
  38159. }
  38160. // determine versioning scheme
  38161. let versioning = this.Versioning.None;
  38162. this.targetObject = targetObject;
  38163. if ( targetObject.isMaterial === true ) {
  38164. versioning = this.Versioning.NeedsUpdate;
  38165. } else if ( targetObject.isObject3D === true ) {
  38166. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  38167. }
  38168. // determine how the property gets bound
  38169. let bindingType = this.BindingType.Direct;
  38170. if ( propertyIndex !== undefined ) {
  38171. // access a sub element of the property array (only primitives are supported right now)
  38172. if ( propertyName === 'morphTargetInfluences' ) {
  38173. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  38174. // support resolving morphTarget names into indices.
  38175. if ( ! targetObject.geometry ) {
  38176. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  38177. return;
  38178. }
  38179. if ( ! targetObject.geometry.morphAttributes ) {
  38180. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  38181. return;
  38182. }
  38183. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  38184. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  38185. }
  38186. }
  38187. bindingType = this.BindingType.ArrayElement;
  38188. this.resolvedProperty = nodeProperty;
  38189. this.propertyIndex = propertyIndex;
  38190. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  38191. // must use copy for Object3D.Euler/Quaternion
  38192. bindingType = this.BindingType.HasFromToArray;
  38193. this.resolvedProperty = nodeProperty;
  38194. } else if ( Array.isArray( nodeProperty ) ) {
  38195. bindingType = this.BindingType.EntireArray;
  38196. this.resolvedProperty = nodeProperty;
  38197. } else {
  38198. this.propertyName = propertyName;
  38199. }
  38200. // select getter / setter
  38201. this.getValue = this.GetterByBindingType[ bindingType ];
  38202. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  38203. }
  38204. /**
  38205. * Unbinds the property.
  38206. */
  38207. unbind() {
  38208. this.node = null;
  38209. // back to the prototype version of getValue / setValue
  38210. // note: avoiding to mutate the shape of 'this' via 'delete'
  38211. this.getValue = this._getValue_unbound;
  38212. this.setValue = this._setValue_unbound;
  38213. }
  38214. }
  38215. PropertyBinding.Composite = Composite;
  38216. PropertyBinding.prototype.BindingType = {
  38217. Direct: 0,
  38218. EntireArray: 1,
  38219. ArrayElement: 2,
  38220. HasFromToArray: 3
  38221. };
  38222. PropertyBinding.prototype.Versioning = {
  38223. None: 0,
  38224. NeedsUpdate: 1,
  38225. MatrixWorldNeedsUpdate: 2
  38226. };
  38227. PropertyBinding.prototype.GetterByBindingType = [
  38228. PropertyBinding.prototype._getValue_direct,
  38229. PropertyBinding.prototype._getValue_array,
  38230. PropertyBinding.prototype._getValue_arrayElement,
  38231. PropertyBinding.prototype._getValue_toArray,
  38232. ];
  38233. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  38234. [
  38235. // Direct
  38236. PropertyBinding.prototype._setValue_direct,
  38237. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  38238. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  38239. ], [
  38240. // EntireArray
  38241. PropertyBinding.prototype._setValue_array,
  38242. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  38243. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  38244. ], [
  38245. // ArrayElement
  38246. PropertyBinding.prototype._setValue_arrayElement,
  38247. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  38248. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  38249. ], [
  38250. // HasToFromArray
  38251. PropertyBinding.prototype._setValue_fromArray,
  38252. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  38253. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  38254. ]
  38255. ];
  38256. /**
  38257. * A group of objects that receives a shared animation state.
  38258. *
  38259. * Usage:
  38260. *
  38261. * - Add objects you would otherwise pass as 'root' to the
  38262. * constructor or the .clipAction method of AnimationMixer.
  38263. * - Instead pass this object as 'root'.
  38264. * - You can also add and remove objects later when the mixer is running.
  38265. *
  38266. * Note:
  38267. *
  38268. * - Objects of this class appear as one object to the mixer,
  38269. * so cache control of the individual objects must be done on the group.
  38270. *
  38271. * Limitation:
  38272. *
  38273. * - The animated properties must be compatible among the all objects in the group.
  38274. * - A single property can either be controlled through a target group or directly, but not both.
  38275. */
  38276. class AnimationObjectGroup {
  38277. /**
  38278. * Constructs a new animation group.
  38279. *
  38280. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  38281. */
  38282. constructor() {
  38283. /**
  38284. * This flag can be used for type testing.
  38285. *
  38286. * @type {boolean}
  38287. * @readonly
  38288. * @default true
  38289. */
  38290. this.isAnimationObjectGroup = true;
  38291. /**
  38292. * The UUID of the 3D object.
  38293. *
  38294. * @type {string}
  38295. * @readonly
  38296. */
  38297. this.uuid = generateUUID();
  38298. // cached objects followed by the active ones
  38299. this._objects = Array.prototype.slice.call( arguments );
  38300. this.nCachedObjects_ = 0; // threshold
  38301. // note: read by PropertyBinding.Composite
  38302. const indices = {};
  38303. this._indicesByUUID = indices; // for bookkeeping
  38304. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38305. indices[ arguments[ i ].uuid ] = i;
  38306. }
  38307. this._paths = []; // inside: string
  38308. this._parsedPaths = []; // inside: { we don't care, here }
  38309. this._bindings = []; // inside: Array< PropertyBinding >
  38310. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38311. const scope = this;
  38312. this.stats = {
  38313. objects: {
  38314. get total() {
  38315. return scope._objects.length;
  38316. },
  38317. get inUse() {
  38318. return this.total - scope.nCachedObjects_;
  38319. }
  38320. },
  38321. get bindingsPerObject() {
  38322. return scope._bindings.length;
  38323. }
  38324. };
  38325. }
  38326. /**
  38327. * Adds an arbitrary number of objects to this animation group.
  38328. *
  38329. * @param {...Object3D} arguments - The 3D objects to add.
  38330. */
  38331. add() {
  38332. const objects = this._objects,
  38333. indicesByUUID = this._indicesByUUID,
  38334. paths = this._paths,
  38335. parsedPaths = this._parsedPaths,
  38336. bindings = this._bindings,
  38337. nBindings = bindings.length;
  38338. let knownObject = undefined,
  38339. nObjects = objects.length,
  38340. nCachedObjects = this.nCachedObjects_;
  38341. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38342. const object = arguments[ i ],
  38343. uuid = object.uuid;
  38344. let index = indicesByUUID[ uuid ];
  38345. if ( index === undefined ) {
  38346. // unknown object -> add it to the ACTIVE region
  38347. index = nObjects ++;
  38348. indicesByUUID[ uuid ] = index;
  38349. objects.push( object );
  38350. // accounting is done, now do the same for all bindings
  38351. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38352. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38353. }
  38354. } else if ( index < nCachedObjects ) {
  38355. knownObject = objects[ index ];
  38356. // move existing object to the ACTIVE region
  38357. const firstActiveIndex = -- nCachedObjects,
  38358. lastCachedObject = objects[ firstActiveIndex ];
  38359. indicesByUUID[ lastCachedObject.uuid ] = index;
  38360. objects[ index ] = lastCachedObject;
  38361. indicesByUUID[ uuid ] = firstActiveIndex;
  38362. objects[ firstActiveIndex ] = object;
  38363. // accounting is done, now do the same for all bindings
  38364. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38365. const bindingsForPath = bindings[ j ],
  38366. lastCached = bindingsForPath[ firstActiveIndex ];
  38367. let binding = bindingsForPath[ index ];
  38368. bindingsForPath[ index ] = lastCached;
  38369. if ( binding === undefined ) {
  38370. // since we do not bother to create new bindings
  38371. // for objects that are cached, the binding may
  38372. // or may not exist
  38373. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38374. }
  38375. bindingsForPath[ firstActiveIndex ] = binding;
  38376. }
  38377. } else if ( objects[ index ] !== knownObject ) {
  38378. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38379. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38380. } // else the object is already where we want it to be
  38381. } // for arguments
  38382. this.nCachedObjects_ = nCachedObjects;
  38383. }
  38384. /**
  38385. * Removes an arbitrary number of objects to this animation group
  38386. *
  38387. * @param {...Object3D} arguments - The 3D objects to remove.
  38388. */
  38389. remove() {
  38390. const objects = this._objects,
  38391. indicesByUUID = this._indicesByUUID,
  38392. bindings = this._bindings,
  38393. nBindings = bindings.length;
  38394. let nCachedObjects = this.nCachedObjects_;
  38395. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38396. const object = arguments[ i ],
  38397. uuid = object.uuid,
  38398. index = indicesByUUID[ uuid ];
  38399. if ( index !== undefined && index >= nCachedObjects ) {
  38400. // move existing object into the CACHED region
  38401. const lastCachedIndex = nCachedObjects ++,
  38402. firstActiveObject = objects[ lastCachedIndex ];
  38403. indicesByUUID[ firstActiveObject.uuid ] = index;
  38404. objects[ index ] = firstActiveObject;
  38405. indicesByUUID[ uuid ] = lastCachedIndex;
  38406. objects[ lastCachedIndex ] = object;
  38407. // accounting is done, now do the same for all bindings
  38408. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38409. const bindingsForPath = bindings[ j ],
  38410. firstActive = bindingsForPath[ lastCachedIndex ],
  38411. binding = bindingsForPath[ index ];
  38412. bindingsForPath[ index ] = firstActive;
  38413. bindingsForPath[ lastCachedIndex ] = binding;
  38414. }
  38415. }
  38416. } // for arguments
  38417. this.nCachedObjects_ = nCachedObjects;
  38418. }
  38419. /**
  38420. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38421. *
  38422. * @param {...Object3D} arguments - The 3D objects to uncache.
  38423. */
  38424. uncache() {
  38425. const objects = this._objects,
  38426. indicesByUUID = this._indicesByUUID,
  38427. bindings = this._bindings,
  38428. nBindings = bindings.length;
  38429. let nCachedObjects = this.nCachedObjects_,
  38430. nObjects = objects.length;
  38431. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38432. const object = arguments[ i ],
  38433. uuid = object.uuid,
  38434. index = indicesByUUID[ uuid ];
  38435. if ( index !== undefined ) {
  38436. delete indicesByUUID[ uuid ];
  38437. if ( index < nCachedObjects ) {
  38438. // object is cached, shrink the CACHED region
  38439. const firstActiveIndex = -- nCachedObjects,
  38440. lastCachedObject = objects[ firstActiveIndex ],
  38441. lastIndex = -- nObjects,
  38442. lastObject = objects[ lastIndex ];
  38443. // last cached object takes this object's place
  38444. indicesByUUID[ lastCachedObject.uuid ] = index;
  38445. objects[ index ] = lastCachedObject;
  38446. // last object goes to the activated slot and pop
  38447. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38448. objects[ firstActiveIndex ] = lastObject;
  38449. objects.pop();
  38450. // accounting is done, now do the same for all bindings
  38451. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38452. const bindingsForPath = bindings[ j ],
  38453. lastCached = bindingsForPath[ firstActiveIndex ],
  38454. last = bindingsForPath[ lastIndex ];
  38455. bindingsForPath[ index ] = lastCached;
  38456. bindingsForPath[ firstActiveIndex ] = last;
  38457. bindingsForPath.pop();
  38458. }
  38459. } else {
  38460. // object is active, just swap with the last and pop
  38461. const lastIndex = -- nObjects,
  38462. lastObject = objects[ lastIndex ];
  38463. if ( lastIndex > 0 ) {
  38464. indicesByUUID[ lastObject.uuid ] = index;
  38465. }
  38466. objects[ index ] = lastObject;
  38467. objects.pop();
  38468. // accounting is done, now do the same for all bindings
  38469. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38470. const bindingsForPath = bindings[ j ];
  38471. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38472. bindingsForPath.pop();
  38473. }
  38474. } // cached or active
  38475. } // if object is known
  38476. } // for arguments
  38477. this.nCachedObjects_ = nCachedObjects;
  38478. }
  38479. // Internal interface used by befriended PropertyBinding.Composite:
  38480. subscribe_( path, parsedPath ) {
  38481. // returns an array of bindings for the given path that is changed
  38482. // according to the contained objects in the group
  38483. const indicesByPath = this._bindingsIndicesByPath;
  38484. let index = indicesByPath[ path ];
  38485. const bindings = this._bindings;
  38486. if ( index !== undefined ) return bindings[ index ];
  38487. const paths = this._paths,
  38488. parsedPaths = this._parsedPaths,
  38489. objects = this._objects,
  38490. nObjects = objects.length,
  38491. nCachedObjects = this.nCachedObjects_,
  38492. bindingsForPath = new Array( nObjects );
  38493. index = bindings.length;
  38494. indicesByPath[ path ] = index;
  38495. paths.push( path );
  38496. parsedPaths.push( parsedPath );
  38497. bindings.push( bindingsForPath );
  38498. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38499. const object = objects[ i ];
  38500. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38501. }
  38502. return bindingsForPath;
  38503. }
  38504. unsubscribe_( path ) {
  38505. // tells the group to forget about a property path and no longer
  38506. // update the array previously obtained with 'subscribe_'
  38507. const indicesByPath = this._bindingsIndicesByPath,
  38508. index = indicesByPath[ path ];
  38509. if ( index !== undefined ) {
  38510. const paths = this._paths,
  38511. parsedPaths = this._parsedPaths,
  38512. bindings = this._bindings,
  38513. lastBindingsIndex = bindings.length - 1,
  38514. lastBindings = bindings[ lastBindingsIndex ],
  38515. lastBindingsPath = path[ lastBindingsIndex ];
  38516. indicesByPath[ lastBindingsPath ] = index;
  38517. bindings[ index ] = lastBindings;
  38518. bindings.pop();
  38519. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38520. parsedPaths.pop();
  38521. paths[ index ] = paths[ lastBindingsIndex ];
  38522. paths.pop();
  38523. }
  38524. }
  38525. }
  38526. /**
  38527. * An instance of `AnimationAction` schedules the playback of an animation which is
  38528. * stored in {@link AnimationClip}.
  38529. */
  38530. class AnimationAction {
  38531. /**
  38532. * Constructs a new animation action.
  38533. *
  38534. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38535. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38536. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38537. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38538. */
  38539. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38540. this._mixer = mixer;
  38541. this._clip = clip;
  38542. this._localRoot = localRoot;
  38543. /**
  38544. * Defines how the animation is blended/combined when two or more animations
  38545. * are simultaneously played.
  38546. *
  38547. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38548. */
  38549. this.blendMode = blendMode;
  38550. const tracks = clip.tracks,
  38551. nTracks = tracks.length,
  38552. interpolants = new Array( nTracks );
  38553. const interpolantSettings = {
  38554. endingStart: ZeroCurvatureEnding,
  38555. endingEnd: ZeroCurvatureEnding
  38556. };
  38557. for ( let i = 0; i !== nTracks; ++ i ) {
  38558. const interpolant = tracks[ i ].createInterpolant( null );
  38559. interpolants[ i ] = interpolant;
  38560. interpolant.settings = interpolantSettings;
  38561. }
  38562. this._interpolantSettings = interpolantSettings;
  38563. this._interpolants = interpolants; // bound by the mixer
  38564. // inside: PropertyMixer (managed by the mixer)
  38565. this._propertyBindings = new Array( nTracks );
  38566. this._cacheIndex = null; // for the memory manager
  38567. this._byClipCacheIndex = null; // for the memory manager
  38568. this._timeScaleInterpolant = null;
  38569. this._weightInterpolant = null;
  38570. /**
  38571. * The loop mode, set via {@link AnimationAction#setLoop}.
  38572. *
  38573. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38574. * @default LoopRepeat
  38575. */
  38576. this.loop = LoopRepeat;
  38577. this._loopCount = -1;
  38578. // global mixer time when the action is to be started
  38579. // it's set back to 'null' upon start of the action
  38580. this._startTime = null;
  38581. /**
  38582. * The local time of this action (in seconds, starting with `0`).
  38583. *
  38584. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38585. * loop state).
  38586. *
  38587. * @type {number}
  38588. * @default Infinity
  38589. */
  38590. this.time = 0;
  38591. /**
  38592. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38593. * animation to pause. Negative values cause the animation to play backwards.
  38594. *
  38595. * @type {number}
  38596. * @default 1
  38597. */
  38598. this.timeScale = 1;
  38599. this._effectiveTimeScale = 1;
  38600. /**
  38601. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38602. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38603. * several actions.
  38604. *
  38605. * @type {number}
  38606. * @default 1
  38607. */
  38608. this.weight = 1;
  38609. this._effectiveWeight = 1;
  38610. /**
  38611. * The number of repetitions of the performed clip over the course of this action.
  38612. * Can be set via {@link AnimationAction#setLoop}.
  38613. *
  38614. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38615. * `THREE:LoopOnce`.
  38616. *
  38617. * @type {number}
  38618. * @default Infinity
  38619. */
  38620. this.repetitions = Infinity;
  38621. /**
  38622. * If set to `true`, the playback of the action is paused.
  38623. *
  38624. * @type {boolean}
  38625. * @default false
  38626. */
  38627. this.paused = false;
  38628. /**
  38629. * If set to `false`, the action is disabled so it has no impact.
  38630. *
  38631. * When the action is re-enabled, the animation continues from its current
  38632. * time (setting `enabled` to `false` doesn't reset the action).
  38633. *
  38634. * @type {boolean}
  38635. * @default true
  38636. */
  38637. this.enabled = true;
  38638. /**
  38639. * If set to true the animation will automatically be paused on its last frame.
  38640. *
  38641. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38642. * to `false` when the last loop of the action has finished, so that this action has
  38643. * no further impact.
  38644. *
  38645. * Note: This member has no impact if the action is interrupted (it
  38646. * has only an effect if its last loop has really finished).
  38647. *
  38648. * @type {boolean}
  38649. * @default false
  38650. */
  38651. this.clampWhenFinished = false;
  38652. /**
  38653. * Enables smooth interpolation without separate clips for start, loop and end.
  38654. *
  38655. * @type {boolean}
  38656. * @default true
  38657. */
  38658. this.zeroSlopeAtStart = true;
  38659. /**
  38660. * Enables smooth interpolation without separate clips for start, loop and end.
  38661. *
  38662. * @type {boolean}
  38663. * @default true
  38664. */
  38665. this.zeroSlopeAtEnd = true;
  38666. }
  38667. /**
  38668. * Starts the playback of the animation.
  38669. *
  38670. * @return {AnimationAction} A reference to this animation action.
  38671. */
  38672. play() {
  38673. this._mixer._activateAction( this );
  38674. return this;
  38675. }
  38676. /**
  38677. * Stops the playback of the animation.
  38678. *
  38679. * @return {AnimationAction} A reference to this animation action.
  38680. */
  38681. stop() {
  38682. this._mixer._deactivateAction( this );
  38683. return this.reset();
  38684. }
  38685. /**
  38686. * Resets the playback of the animation.
  38687. *
  38688. * @return {AnimationAction} A reference to this animation action.
  38689. */
  38690. reset() {
  38691. this.paused = false;
  38692. this.enabled = true;
  38693. this.time = 0; // restart clip
  38694. this._loopCount = -1;// forget previous loops
  38695. this._startTime = null;// forget scheduling
  38696. return this.stopFading().stopWarping();
  38697. }
  38698. /**
  38699. * Returns `true` if the animation is running.
  38700. *
  38701. * @return {boolean} Whether the animation is running or not.
  38702. */
  38703. isRunning() {
  38704. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38705. this._startTime === null && this._mixer._isActiveAction( this );
  38706. }
  38707. /**
  38708. * Returns `true` when {@link AnimationAction#play} has been called.
  38709. *
  38710. * @return {boolean} Whether the animation is scheduled or not.
  38711. */
  38712. isScheduled() {
  38713. return this._mixer._isActiveAction( this );
  38714. }
  38715. /**
  38716. * Defines the time when the animation should start.
  38717. *
  38718. * @param {number} time - The start time in seconds.
  38719. * @return {AnimationAction} A reference to this animation action.
  38720. */
  38721. startAt( time ) {
  38722. this._startTime = time;
  38723. return this;
  38724. }
  38725. /**
  38726. * Configures the loop settings for this action.
  38727. *
  38728. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38729. * @param {number} repetitions - The number of repetitions.
  38730. * @return {AnimationAction} A reference to this animation action.
  38731. */
  38732. setLoop( mode, repetitions ) {
  38733. this.loop = mode;
  38734. this.repetitions = repetitions;
  38735. return this;
  38736. }
  38737. /**
  38738. * Sets the effective weight of this action.
  38739. *
  38740. * An action has no effect and thus an effective weight of zero when the
  38741. * action is disabled.
  38742. *
  38743. * @param {number} weight - The weight to set.
  38744. * @return {AnimationAction} A reference to this animation action.
  38745. */
  38746. setEffectiveWeight( weight ) {
  38747. this.weight = weight;
  38748. // note: same logic as when updated at runtime
  38749. this._effectiveWeight = this.enabled ? weight : 0;
  38750. return this.stopFading();
  38751. }
  38752. /**
  38753. * Returns the effective weight of this action.
  38754. *
  38755. * @return {number} The effective weight.
  38756. */
  38757. getEffectiveWeight() {
  38758. return this._effectiveWeight;
  38759. }
  38760. /**
  38761. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38762. * within the passed time interval.
  38763. *
  38764. * @param {number} duration - The duration of the fade.
  38765. * @return {AnimationAction} A reference to this animation action.
  38766. */
  38767. fadeIn( duration ) {
  38768. return this._scheduleFading( duration, 0, 1 );
  38769. }
  38770. /**
  38771. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38772. * within the passed time interval.
  38773. *
  38774. * @param {number} duration - The duration of the fade.
  38775. * @return {AnimationAction} A reference to this animation action.
  38776. */
  38777. fadeOut( duration ) {
  38778. return this._scheduleFading( duration, 1, 0 );
  38779. }
  38780. /**
  38781. * Causes this action to fade in and the given action to fade out,
  38782. * within the passed time interval.
  38783. *
  38784. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38785. * @param {number} duration - The duration of the fade.
  38786. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38787. * @return {AnimationAction} A reference to this animation action.
  38788. */
  38789. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38790. fadeOutAction.fadeOut( duration );
  38791. this.fadeIn( duration );
  38792. if ( warp === true ) {
  38793. const fadeInDuration = this._clip.duration,
  38794. fadeOutDuration = fadeOutAction._clip.duration,
  38795. startEndRatio = fadeOutDuration / fadeInDuration,
  38796. endStartRatio = fadeInDuration / fadeOutDuration;
  38797. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38798. this.warp( endStartRatio, 1.0, duration );
  38799. }
  38800. return this;
  38801. }
  38802. /**
  38803. * Causes this action to fade out and the given action to fade in,
  38804. * within the passed time interval.
  38805. *
  38806. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38807. * @param {number} duration - The duration of the fade.
  38808. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38809. * @return {AnimationAction} A reference to this animation action.
  38810. */
  38811. crossFadeTo( fadeInAction, duration, warp = false ) {
  38812. return fadeInAction.crossFadeFrom( this, duration, warp );
  38813. }
  38814. /**
  38815. * Stops any fading which is applied to this action.
  38816. *
  38817. * @return {AnimationAction} A reference to this animation action.
  38818. */
  38819. stopFading() {
  38820. const weightInterpolant = this._weightInterpolant;
  38821. if ( weightInterpolant !== null ) {
  38822. this._weightInterpolant = null;
  38823. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38824. }
  38825. return this;
  38826. }
  38827. /**
  38828. * Sets the effective time scale of this action.
  38829. *
  38830. * An action has no effect and thus an effective time scale of zero when the
  38831. * action is paused.
  38832. *
  38833. * @param {number} timeScale - The time scale to set.
  38834. * @return {AnimationAction} A reference to this animation action.
  38835. */
  38836. setEffectiveTimeScale( timeScale ) {
  38837. this.timeScale = timeScale;
  38838. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38839. return this.stopWarping();
  38840. }
  38841. /**
  38842. * Returns the effective time scale of this action.
  38843. *
  38844. * @return {number} The effective time scale.
  38845. */
  38846. getEffectiveTimeScale() {
  38847. return this._effectiveTimeScale;
  38848. }
  38849. /**
  38850. * Sets the duration for a single loop of this action.
  38851. *
  38852. * @param {number} duration - The duration to set.
  38853. * @return {AnimationAction} A reference to this animation action.
  38854. */
  38855. setDuration( duration ) {
  38856. this.timeScale = this._clip.duration / duration;
  38857. return this.stopWarping();
  38858. }
  38859. /**
  38860. * Synchronizes this action with the passed other action.
  38861. *
  38862. * @param {AnimationAction} action - The action to sync with.
  38863. * @return {AnimationAction} A reference to this animation action.
  38864. */
  38865. syncWith( action ) {
  38866. this.time = action.time;
  38867. this.timeScale = action.timeScale;
  38868. return this.stopWarping();
  38869. }
  38870. /**
  38871. * Decelerates this animation's speed to `0` within the passed time interval.
  38872. *
  38873. * @param {number} duration - The duration.
  38874. * @return {AnimationAction} A reference to this animation action.
  38875. */
  38876. halt( duration ) {
  38877. return this.warp( this._effectiveTimeScale, 0, duration );
  38878. }
  38879. /**
  38880. * Changes the playback speed, within the passed time interval, by modifying
  38881. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38882. * `endTimeScale`.
  38883. *
  38884. * @param {number} startTimeScale - The start time scale.
  38885. * @param {number} endTimeScale - The end time scale.
  38886. * @param {number} duration - The duration.
  38887. * @return {AnimationAction} A reference to this animation action.
  38888. */
  38889. warp( startTimeScale, endTimeScale, duration ) {
  38890. const mixer = this._mixer,
  38891. now = mixer.time,
  38892. timeScale = this.timeScale;
  38893. let interpolant = this._timeScaleInterpolant;
  38894. if ( interpolant === null ) {
  38895. interpolant = mixer._lendControlInterpolant();
  38896. this._timeScaleInterpolant = interpolant;
  38897. }
  38898. const times = interpolant.parameterPositions,
  38899. values = interpolant.sampleValues;
  38900. times[ 0 ] = now;
  38901. times[ 1 ] = now + duration;
  38902. values[ 0 ] = startTimeScale / timeScale;
  38903. values[ 1 ] = endTimeScale / timeScale;
  38904. return this;
  38905. }
  38906. /**
  38907. * Stops any scheduled warping which is applied to this action.
  38908. *
  38909. * @return {AnimationAction} A reference to this animation action.
  38910. */
  38911. stopWarping() {
  38912. const timeScaleInterpolant = this._timeScaleInterpolant;
  38913. if ( timeScaleInterpolant !== null ) {
  38914. this._timeScaleInterpolant = null;
  38915. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38916. }
  38917. return this;
  38918. }
  38919. /**
  38920. * Returns the animation mixer of this animation action.
  38921. *
  38922. * @return {AnimationMixer} The animation mixer.
  38923. */
  38924. getMixer() {
  38925. return this._mixer;
  38926. }
  38927. /**
  38928. * Returns the animation clip of this animation action.
  38929. *
  38930. * @return {AnimationClip} The animation clip.
  38931. */
  38932. getClip() {
  38933. return this._clip;
  38934. }
  38935. /**
  38936. * Returns the root object of this animation action.
  38937. *
  38938. * @return {Object3D} The root object.
  38939. */
  38940. getRoot() {
  38941. return this._localRoot || this._mixer._root;
  38942. }
  38943. // Internal
  38944. _update( time, deltaTime, timeDirection, accuIndex ) {
  38945. // called by the mixer
  38946. if ( ! this.enabled ) {
  38947. // call ._updateWeight() to update ._effectiveWeight
  38948. this._updateWeight( time );
  38949. return;
  38950. }
  38951. const startTime = this._startTime;
  38952. if ( startTime !== null ) {
  38953. // check for scheduled start of action
  38954. const timeRunning = ( time - startTime ) * timeDirection;
  38955. if ( timeRunning < 0 || timeDirection === 0 ) {
  38956. deltaTime = 0;
  38957. } else {
  38958. this._startTime = null; // unschedule
  38959. deltaTime = timeDirection * timeRunning;
  38960. }
  38961. }
  38962. // apply time scale and advance time
  38963. deltaTime *= this._updateTimeScale( time );
  38964. const clipTime = this._updateTime( deltaTime );
  38965. // note: _updateTime may disable the action resulting in
  38966. // an effective weight of 0
  38967. const weight = this._updateWeight( time );
  38968. if ( weight > 0 ) {
  38969. const interpolants = this._interpolants;
  38970. const propertyMixers = this._propertyBindings;
  38971. switch ( this.blendMode ) {
  38972. case AdditiveAnimationBlendMode:
  38973. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38974. interpolants[ j ].evaluate( clipTime );
  38975. propertyMixers[ j ].accumulateAdditive( weight );
  38976. }
  38977. break;
  38978. case NormalAnimationBlendMode:
  38979. default:
  38980. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38981. interpolants[ j ].evaluate( clipTime );
  38982. propertyMixers[ j ].accumulate( accuIndex, weight );
  38983. }
  38984. }
  38985. }
  38986. }
  38987. _updateWeight( time ) {
  38988. let weight = 0;
  38989. if ( this.enabled ) {
  38990. weight = this.weight;
  38991. const interpolant = this._weightInterpolant;
  38992. if ( interpolant !== null ) {
  38993. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38994. weight *= interpolantValue;
  38995. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38996. this.stopFading();
  38997. if ( interpolantValue === 0 ) {
  38998. // faded out, disable
  38999. this.enabled = false;
  39000. }
  39001. }
  39002. }
  39003. }
  39004. this._effectiveWeight = weight;
  39005. return weight;
  39006. }
  39007. _updateTimeScale( time ) {
  39008. let timeScale = 0;
  39009. if ( ! this.paused ) {
  39010. timeScale = this.timeScale;
  39011. const interpolant = this._timeScaleInterpolant;
  39012. if ( interpolant !== null ) {
  39013. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39014. timeScale *= interpolantValue;
  39015. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39016. this.stopWarping();
  39017. if ( timeScale === 0 ) {
  39018. // motion has halted, pause
  39019. this.paused = true;
  39020. } else {
  39021. // warp done - apply final time scale
  39022. this.timeScale = timeScale;
  39023. }
  39024. }
  39025. }
  39026. }
  39027. this._effectiveTimeScale = timeScale;
  39028. return timeScale;
  39029. }
  39030. _updateTime( deltaTime ) {
  39031. const duration = this._clip.duration;
  39032. const loop = this.loop;
  39033. let time = this.time + deltaTime;
  39034. let loopCount = this._loopCount;
  39035. const pingPong = ( loop === LoopPingPong );
  39036. if ( deltaTime === 0 ) {
  39037. if ( loopCount === -1 ) return time;
  39038. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  39039. }
  39040. if ( loop === LoopOnce ) {
  39041. if ( loopCount === -1 ) {
  39042. // just started
  39043. this._loopCount = 0;
  39044. this._setEndings( true, true, false );
  39045. }
  39046. handle_stop: {
  39047. if ( time >= duration ) {
  39048. time = duration;
  39049. } else if ( time < 0 ) {
  39050. time = 0;
  39051. } else {
  39052. this.time = time;
  39053. break handle_stop;
  39054. }
  39055. if ( this.clampWhenFinished ) this.paused = true;
  39056. else this.enabled = false;
  39057. this.time = time;
  39058. this._mixer.dispatchEvent( {
  39059. type: 'finished', action: this,
  39060. direction: deltaTime < 0 ? -1 : 1
  39061. } );
  39062. }
  39063. } else { // repetitive Repeat or PingPong
  39064. if ( loopCount === -1 ) {
  39065. // just started
  39066. if ( deltaTime >= 0 ) {
  39067. loopCount = 0;
  39068. this._setEndings( true, this.repetitions === 0, pingPong );
  39069. } else {
  39070. // when looping in reverse direction, the initial
  39071. // transition through zero counts as a repetition,
  39072. // so leave loopCount at -1
  39073. this._setEndings( this.repetitions === 0, true, pingPong );
  39074. }
  39075. }
  39076. if ( time >= duration || time < 0 ) {
  39077. // wrap around
  39078. const loopDelta = Math.floor( time / duration ); // signed
  39079. time -= duration * loopDelta;
  39080. loopCount += Math.abs( loopDelta );
  39081. const pending = this.repetitions - loopCount;
  39082. if ( pending <= 0 ) {
  39083. // have to stop (switch state, clamp time, fire event)
  39084. if ( this.clampWhenFinished ) this.paused = true;
  39085. else this.enabled = false;
  39086. time = deltaTime > 0 ? duration : 0;
  39087. this.time = time;
  39088. this._mixer.dispatchEvent( {
  39089. type: 'finished', action: this,
  39090. direction: deltaTime > 0 ? 1 : -1
  39091. } );
  39092. } else {
  39093. // keep running
  39094. if ( pending === 1 ) {
  39095. // entering the last round
  39096. const atStart = deltaTime < 0;
  39097. this._setEndings( atStart, ! atStart, pingPong );
  39098. } else {
  39099. this._setEndings( false, false, pingPong );
  39100. }
  39101. this._loopCount = loopCount;
  39102. this.time = time;
  39103. this._mixer.dispatchEvent( {
  39104. type: 'loop', action: this, loopDelta: loopDelta
  39105. } );
  39106. }
  39107. } else {
  39108. this.time = time;
  39109. }
  39110. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  39111. // invert time for the "pong round"
  39112. return duration - time;
  39113. }
  39114. }
  39115. return time;
  39116. }
  39117. _setEndings( atStart, atEnd, pingPong ) {
  39118. const settings = this._interpolantSettings;
  39119. if ( pingPong ) {
  39120. settings.endingStart = ZeroSlopeEnding;
  39121. settings.endingEnd = ZeroSlopeEnding;
  39122. } else {
  39123. // assuming for LoopOnce atStart == atEnd == true
  39124. if ( atStart ) {
  39125. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39126. } else {
  39127. settings.endingStart = WrapAroundEnding;
  39128. }
  39129. if ( atEnd ) {
  39130. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39131. } else {
  39132. settings.endingEnd = WrapAroundEnding;
  39133. }
  39134. }
  39135. }
  39136. _scheduleFading( duration, weightNow, weightThen ) {
  39137. const mixer = this._mixer, now = mixer.time;
  39138. let interpolant = this._weightInterpolant;
  39139. if ( interpolant === null ) {
  39140. interpolant = mixer._lendControlInterpolant();
  39141. this._weightInterpolant = interpolant;
  39142. }
  39143. const times = interpolant.parameterPositions,
  39144. values = interpolant.sampleValues;
  39145. times[ 0 ] = now;
  39146. values[ 0 ] = weightNow;
  39147. times[ 1 ] = now + duration;
  39148. values[ 1 ] = weightThen;
  39149. return this;
  39150. }
  39151. }
  39152. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  39153. /**
  39154. * `AnimationMixer` is a player for animations on a particular object in
  39155. * the scene. When multiple objects in the scene are animated independently,
  39156. * one `AnimationMixer` may be used for each object.
  39157. */
  39158. class AnimationMixer extends EventDispatcher {
  39159. /**
  39160. * Constructs a new animation mixer.
  39161. *
  39162. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  39163. */
  39164. constructor( root ) {
  39165. super();
  39166. this._root = root;
  39167. this._initMemoryManager();
  39168. this._accuIndex = 0;
  39169. /**
  39170. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  39171. *
  39172. * @type {number}
  39173. * @default 0
  39174. */
  39175. this.time = 0;
  39176. /**
  39177. * A scaling factor for the global time.
  39178. *
  39179. * Note: Setting this member to `0` and later back to `1` is a
  39180. * possibility to pause/unpause all actions that are controlled by this
  39181. * mixer.
  39182. *
  39183. * @type {number}
  39184. * @default 1
  39185. */
  39186. this.timeScale = 1.0;
  39187. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  39188. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  39189. }
  39190. }
  39191. _bindAction( action, prototypeAction ) {
  39192. const root = action._localRoot || this._root,
  39193. tracks = action._clip.tracks,
  39194. nTracks = tracks.length,
  39195. bindings = action._propertyBindings,
  39196. interpolants = action._interpolants,
  39197. rootUuid = root.uuid,
  39198. bindingsByRoot = this._bindingsByRootAndName;
  39199. let bindingsByName = bindingsByRoot[ rootUuid ];
  39200. if ( bindingsByName === undefined ) {
  39201. bindingsByName = {};
  39202. bindingsByRoot[ rootUuid ] = bindingsByName;
  39203. }
  39204. for ( let i = 0; i !== nTracks; ++ i ) {
  39205. const track = tracks[ i ],
  39206. trackName = track.name;
  39207. let binding = bindingsByName[ trackName ];
  39208. if ( binding !== undefined ) {
  39209. ++ binding.referenceCount;
  39210. bindings[ i ] = binding;
  39211. } else {
  39212. binding = bindings[ i ];
  39213. if ( binding !== undefined ) {
  39214. // existing binding, make sure the cache knows
  39215. if ( binding._cacheIndex === null ) {
  39216. ++ binding.referenceCount;
  39217. this._addInactiveBinding( binding, rootUuid, trackName );
  39218. }
  39219. continue;
  39220. }
  39221. const path = prototypeAction && prototypeAction.
  39222. _propertyBindings[ i ].binding.parsedPath;
  39223. binding = new PropertyMixer(
  39224. PropertyBinding.create( root, trackName, path ),
  39225. track.ValueTypeName, track.getValueSize() );
  39226. ++ binding.referenceCount;
  39227. this._addInactiveBinding( binding, rootUuid, trackName );
  39228. bindings[ i ] = binding;
  39229. }
  39230. interpolants[ i ].resultBuffer = binding.buffer;
  39231. }
  39232. }
  39233. _activateAction( action ) {
  39234. if ( ! this._isActiveAction( action ) ) {
  39235. if ( action._cacheIndex === null ) {
  39236. // this action has been forgotten by the cache, but the user
  39237. // appears to be still using it -> rebind
  39238. const rootUuid = ( action._localRoot || this._root ).uuid,
  39239. clipUuid = action._clip.uuid,
  39240. actionsForClip = this._actionsByClip[ clipUuid ];
  39241. this._bindAction( action,
  39242. actionsForClip && actionsForClip.knownActions[ 0 ] );
  39243. this._addInactiveAction( action, clipUuid, rootUuid );
  39244. }
  39245. const bindings = action._propertyBindings;
  39246. // increment reference counts / sort out state
  39247. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39248. const binding = bindings[ i ];
  39249. if ( binding.useCount ++ === 0 ) {
  39250. this._lendBinding( binding );
  39251. binding.saveOriginalState();
  39252. }
  39253. }
  39254. this._lendAction( action );
  39255. }
  39256. }
  39257. _deactivateAction( action ) {
  39258. if ( this._isActiveAction( action ) ) {
  39259. const bindings = action._propertyBindings;
  39260. // decrement reference counts / sort out state
  39261. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39262. const binding = bindings[ i ];
  39263. if ( -- binding.useCount === 0 ) {
  39264. binding.restoreOriginalState();
  39265. this._takeBackBinding( binding );
  39266. }
  39267. }
  39268. this._takeBackAction( action );
  39269. }
  39270. }
  39271. // Memory manager
  39272. _initMemoryManager() {
  39273. this._actions = []; // 'nActiveActions' followed by inactive ones
  39274. this._nActiveActions = 0;
  39275. this._actionsByClip = {};
  39276. // inside:
  39277. // {
  39278. // knownActions: Array< AnimationAction > - used as prototypes
  39279. // actionByRoot: AnimationAction - lookup
  39280. // }
  39281. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  39282. this._nActiveBindings = 0;
  39283. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39284. this._controlInterpolants = []; // same game as above
  39285. this._nActiveControlInterpolants = 0;
  39286. const scope = this;
  39287. this.stats = {
  39288. actions: {
  39289. get total() {
  39290. return scope._actions.length;
  39291. },
  39292. get inUse() {
  39293. return scope._nActiveActions;
  39294. }
  39295. },
  39296. bindings: {
  39297. get total() {
  39298. return scope._bindings.length;
  39299. },
  39300. get inUse() {
  39301. return scope._nActiveBindings;
  39302. }
  39303. },
  39304. controlInterpolants: {
  39305. get total() {
  39306. return scope._controlInterpolants.length;
  39307. },
  39308. get inUse() {
  39309. return scope._nActiveControlInterpolants;
  39310. }
  39311. }
  39312. };
  39313. }
  39314. // Memory management for AnimationAction objects
  39315. _isActiveAction( action ) {
  39316. const index = action._cacheIndex;
  39317. return index !== null && index < this._nActiveActions;
  39318. }
  39319. _addInactiveAction( action, clipUuid, rootUuid ) {
  39320. const actions = this._actions,
  39321. actionsByClip = this._actionsByClip;
  39322. let actionsForClip = actionsByClip[ clipUuid ];
  39323. if ( actionsForClip === undefined ) {
  39324. actionsForClip = {
  39325. knownActions: [ action ],
  39326. actionByRoot: {}
  39327. };
  39328. action._byClipCacheIndex = 0;
  39329. actionsByClip[ clipUuid ] = actionsForClip;
  39330. } else {
  39331. const knownActions = actionsForClip.knownActions;
  39332. action._byClipCacheIndex = knownActions.length;
  39333. knownActions.push( action );
  39334. }
  39335. action._cacheIndex = actions.length;
  39336. actions.push( action );
  39337. actionsForClip.actionByRoot[ rootUuid ] = action;
  39338. }
  39339. _removeInactiveAction( action ) {
  39340. const actions = this._actions,
  39341. lastInactiveAction = actions[ actions.length - 1 ],
  39342. cacheIndex = action._cacheIndex;
  39343. lastInactiveAction._cacheIndex = cacheIndex;
  39344. actions[ cacheIndex ] = lastInactiveAction;
  39345. actions.pop();
  39346. action._cacheIndex = null;
  39347. const clipUuid = action._clip.uuid,
  39348. actionsByClip = this._actionsByClip,
  39349. actionsForClip = actionsByClip[ clipUuid ],
  39350. knownActionsForClip = actionsForClip.knownActions,
  39351. lastKnownAction =
  39352. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39353. byClipCacheIndex = action._byClipCacheIndex;
  39354. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39355. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39356. knownActionsForClip.pop();
  39357. action._byClipCacheIndex = null;
  39358. const actionByRoot = actionsForClip.actionByRoot,
  39359. rootUuid = ( action._localRoot || this._root ).uuid;
  39360. delete actionByRoot[ rootUuid ];
  39361. if ( knownActionsForClip.length === 0 ) {
  39362. delete actionsByClip[ clipUuid ];
  39363. }
  39364. this._removeInactiveBindingsForAction( action );
  39365. }
  39366. _removeInactiveBindingsForAction( action ) {
  39367. const bindings = action._propertyBindings;
  39368. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39369. const binding = bindings[ i ];
  39370. if ( -- binding.referenceCount === 0 ) {
  39371. this._removeInactiveBinding( binding );
  39372. }
  39373. }
  39374. }
  39375. _lendAction( action ) {
  39376. // [ active actions | inactive actions ]
  39377. // [ active actions >| inactive actions ]
  39378. // s a
  39379. // <-swap->
  39380. // a s
  39381. const actions = this._actions,
  39382. prevIndex = action._cacheIndex,
  39383. lastActiveIndex = this._nActiveActions ++,
  39384. firstInactiveAction = actions[ lastActiveIndex ];
  39385. action._cacheIndex = lastActiveIndex;
  39386. actions[ lastActiveIndex ] = action;
  39387. firstInactiveAction._cacheIndex = prevIndex;
  39388. actions[ prevIndex ] = firstInactiveAction;
  39389. }
  39390. _takeBackAction( action ) {
  39391. // [ active actions | inactive actions ]
  39392. // [ active actions |< inactive actions ]
  39393. // a s
  39394. // <-swap->
  39395. // s a
  39396. const actions = this._actions,
  39397. prevIndex = action._cacheIndex,
  39398. firstInactiveIndex = -- this._nActiveActions,
  39399. lastActiveAction = actions[ firstInactiveIndex ];
  39400. action._cacheIndex = firstInactiveIndex;
  39401. actions[ firstInactiveIndex ] = action;
  39402. lastActiveAction._cacheIndex = prevIndex;
  39403. actions[ prevIndex ] = lastActiveAction;
  39404. }
  39405. // Memory management for PropertyMixer objects
  39406. _addInactiveBinding( binding, rootUuid, trackName ) {
  39407. const bindingsByRoot = this._bindingsByRootAndName,
  39408. bindings = this._bindings;
  39409. let bindingByName = bindingsByRoot[ rootUuid ];
  39410. if ( bindingByName === undefined ) {
  39411. bindingByName = {};
  39412. bindingsByRoot[ rootUuid ] = bindingByName;
  39413. }
  39414. bindingByName[ trackName ] = binding;
  39415. binding._cacheIndex = bindings.length;
  39416. bindings.push( binding );
  39417. }
  39418. _removeInactiveBinding( binding ) {
  39419. const bindings = this._bindings,
  39420. propBinding = binding.binding,
  39421. rootUuid = propBinding.rootNode.uuid,
  39422. trackName = propBinding.path,
  39423. bindingsByRoot = this._bindingsByRootAndName,
  39424. bindingByName = bindingsByRoot[ rootUuid ],
  39425. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39426. cacheIndex = binding._cacheIndex;
  39427. lastInactiveBinding._cacheIndex = cacheIndex;
  39428. bindings[ cacheIndex ] = lastInactiveBinding;
  39429. bindings.pop();
  39430. delete bindingByName[ trackName ];
  39431. if ( Object.keys( bindingByName ).length === 0 ) {
  39432. delete bindingsByRoot[ rootUuid ];
  39433. }
  39434. }
  39435. _lendBinding( binding ) {
  39436. const bindings = this._bindings,
  39437. prevIndex = binding._cacheIndex,
  39438. lastActiveIndex = this._nActiveBindings ++,
  39439. firstInactiveBinding = bindings[ lastActiveIndex ];
  39440. binding._cacheIndex = lastActiveIndex;
  39441. bindings[ lastActiveIndex ] = binding;
  39442. firstInactiveBinding._cacheIndex = prevIndex;
  39443. bindings[ prevIndex ] = firstInactiveBinding;
  39444. }
  39445. _takeBackBinding( binding ) {
  39446. const bindings = this._bindings,
  39447. prevIndex = binding._cacheIndex,
  39448. firstInactiveIndex = -- this._nActiveBindings,
  39449. lastActiveBinding = bindings[ firstInactiveIndex ];
  39450. binding._cacheIndex = firstInactiveIndex;
  39451. bindings[ firstInactiveIndex ] = binding;
  39452. lastActiveBinding._cacheIndex = prevIndex;
  39453. bindings[ prevIndex ] = lastActiveBinding;
  39454. }
  39455. // Memory management of Interpolants for weight and time scale
  39456. _lendControlInterpolant() {
  39457. const interpolants = this._controlInterpolants,
  39458. lastActiveIndex = this._nActiveControlInterpolants ++;
  39459. let interpolant = interpolants[ lastActiveIndex ];
  39460. if ( interpolant === undefined ) {
  39461. interpolant = new LinearInterpolant(
  39462. new Float32Array( 2 ), new Float32Array( 2 ),
  39463. 1, _controlInterpolantsResultBuffer );
  39464. interpolant.__cacheIndex = lastActiveIndex;
  39465. interpolants[ lastActiveIndex ] = interpolant;
  39466. }
  39467. return interpolant;
  39468. }
  39469. _takeBackControlInterpolant( interpolant ) {
  39470. const interpolants = this._controlInterpolants,
  39471. prevIndex = interpolant.__cacheIndex,
  39472. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39473. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39474. interpolant.__cacheIndex = firstInactiveIndex;
  39475. interpolants[ firstInactiveIndex ] = interpolant;
  39476. lastActiveInterpolant.__cacheIndex = prevIndex;
  39477. interpolants[ prevIndex ] = lastActiveInterpolant;
  39478. }
  39479. /**
  39480. * Returns an instance of {@link AnimationAction} for the passed clip.
  39481. *
  39482. * If an action fitting the clip and root parameters doesn't yet exist, it
  39483. * will be created by this method. Calling this method several times with the
  39484. * same clip and root parameters always returns the same action.
  39485. *
  39486. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39487. * @param {Object3D} [optionalRoot] - An alternative root object.
  39488. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39489. * @return {?AnimationAction} The animation action.
  39490. */
  39491. clipAction( clip, optionalRoot, blendMode ) {
  39492. const root = optionalRoot || this._root,
  39493. rootUuid = root.uuid;
  39494. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39495. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39496. const actionsForClip = this._actionsByClip[ clipUuid ];
  39497. let prototypeAction = null;
  39498. if ( blendMode === undefined ) {
  39499. if ( clipObject !== null ) {
  39500. blendMode = clipObject.blendMode;
  39501. } else {
  39502. blendMode = NormalAnimationBlendMode;
  39503. }
  39504. }
  39505. if ( actionsForClip !== undefined ) {
  39506. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39507. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39508. return existingAction;
  39509. }
  39510. // we know the clip, so we don't have to parse all
  39511. // the bindings again but can just copy
  39512. prototypeAction = actionsForClip.knownActions[ 0 ];
  39513. // also, take the clip from the prototype action
  39514. if ( clipObject === null )
  39515. clipObject = prototypeAction._clip;
  39516. }
  39517. // clip must be known when specified via string
  39518. if ( clipObject === null ) return null;
  39519. // allocate all resources required to run it
  39520. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39521. this._bindAction( newAction, prototypeAction );
  39522. // and make the action known to the memory manager
  39523. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39524. return newAction;
  39525. }
  39526. /**
  39527. * Returns an existing animation action for the passed clip.
  39528. *
  39529. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39530. * @param {Object3D} [optionalRoot] - An alternative root object.
  39531. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39532. */
  39533. existingAction( clip, optionalRoot ) {
  39534. const root = optionalRoot || this._root,
  39535. rootUuid = root.uuid,
  39536. clipObject = typeof clip === 'string' ?
  39537. AnimationClip.findByName( root, clip ) : clip,
  39538. clipUuid = clipObject ? clipObject.uuid : clip,
  39539. actionsForClip = this._actionsByClip[ clipUuid ];
  39540. if ( actionsForClip !== undefined ) {
  39541. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39542. }
  39543. return null;
  39544. }
  39545. /**
  39546. * Deactivates all previously scheduled actions on this mixer.
  39547. *
  39548. * @return {AnimationMixer} A reference to this animation mixer.
  39549. */
  39550. stopAllAction() {
  39551. const actions = this._actions,
  39552. nActions = this._nActiveActions;
  39553. for ( let i = nActions - 1; i >= 0; -- i ) {
  39554. actions[ i ].stop();
  39555. }
  39556. return this;
  39557. }
  39558. /**
  39559. * Advances the global mixer time and updates the animation.
  39560. *
  39561. * This is usually done in the render loop by passing the delta
  39562. * time from {@link Clock} or {@link Timer}.
  39563. *
  39564. * @param {number} deltaTime - The delta time in seconds.
  39565. * @return {AnimationMixer} A reference to this animation mixer.
  39566. */
  39567. update( deltaTime ) {
  39568. deltaTime *= this.timeScale;
  39569. const actions = this._actions,
  39570. nActions = this._nActiveActions,
  39571. time = this.time += deltaTime,
  39572. timeDirection = Math.sign( deltaTime ),
  39573. accuIndex = this._accuIndex ^= 1;
  39574. // run active actions
  39575. for ( let i = 0; i !== nActions; ++ i ) {
  39576. const action = actions[ i ];
  39577. action._update( time, deltaTime, timeDirection, accuIndex );
  39578. }
  39579. // update scene graph
  39580. const bindings = this._bindings,
  39581. nBindings = this._nActiveBindings;
  39582. for ( let i = 0; i !== nBindings; ++ i ) {
  39583. bindings[ i ].apply( accuIndex );
  39584. }
  39585. return this;
  39586. }
  39587. /**
  39588. * Sets the global mixer to a specific time and updates the animation accordingly.
  39589. *
  39590. * This is useful when you need to jump to an exact time in an animation. The
  39591. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39592. *
  39593. * @param {number} time - The time to set in seconds.
  39594. * @return {AnimationMixer} A reference to this animation mixer.
  39595. */
  39596. setTime( time ) {
  39597. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39598. for ( let i = 0; i < this._actions.length; i ++ ) {
  39599. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39600. }
  39601. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39602. }
  39603. /**
  39604. * Returns this mixer's root object.
  39605. *
  39606. * @return {Object3D} The mixer's root object.
  39607. */
  39608. getRoot() {
  39609. return this._root;
  39610. }
  39611. /**
  39612. * Deallocates all memory resources for a clip. Before using this method make
  39613. * sure to call {@link AnimationAction#stop} for all related actions.
  39614. *
  39615. * @param {AnimationClip} clip - The clip to uncache.
  39616. */
  39617. uncacheClip( clip ) {
  39618. const actions = this._actions,
  39619. clipUuid = clip.uuid,
  39620. actionsByClip = this._actionsByClip,
  39621. actionsForClip = actionsByClip[ clipUuid ];
  39622. if ( actionsForClip !== undefined ) {
  39623. // note: just calling _removeInactiveAction would mess up the
  39624. // iteration state and also require updating the state we can
  39625. // just throw away
  39626. const actionsToRemove = actionsForClip.knownActions;
  39627. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39628. const action = actionsToRemove[ i ];
  39629. this._deactivateAction( action );
  39630. const cacheIndex = action._cacheIndex,
  39631. lastInactiveAction = actions[ actions.length - 1 ];
  39632. action._cacheIndex = null;
  39633. action._byClipCacheIndex = null;
  39634. lastInactiveAction._cacheIndex = cacheIndex;
  39635. actions[ cacheIndex ] = lastInactiveAction;
  39636. actions.pop();
  39637. this._removeInactiveBindingsForAction( action );
  39638. }
  39639. delete actionsByClip[ clipUuid ];
  39640. }
  39641. }
  39642. /**
  39643. * Deallocates all memory resources for a root object. Before using this
  39644. * method make sure to call {@link AnimationAction#stop} for all related
  39645. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39646. * mixer operates on a single root.
  39647. *
  39648. * @param {Object3D} root - The root object to uncache.
  39649. */
  39650. uncacheRoot( root ) {
  39651. const rootUuid = root.uuid,
  39652. actionsByClip = this._actionsByClip;
  39653. for ( const clipUuid in actionsByClip ) {
  39654. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39655. action = actionByRoot[ rootUuid ];
  39656. if ( action !== undefined ) {
  39657. this._deactivateAction( action );
  39658. this._removeInactiveAction( action );
  39659. }
  39660. }
  39661. const bindingsByRoot = this._bindingsByRootAndName,
  39662. bindingByName = bindingsByRoot[ rootUuid ];
  39663. if ( bindingByName !== undefined ) {
  39664. for ( const trackName in bindingByName ) {
  39665. const binding = bindingByName[ trackName ];
  39666. binding.restoreOriginalState();
  39667. this._removeInactiveBinding( binding );
  39668. }
  39669. }
  39670. }
  39671. /**
  39672. * Deallocates all memory resources for an action. The action is identified by the
  39673. * given clip and an optional root object. Before using this method make
  39674. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39675. *
  39676. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39677. * @param {Object3D} [optionalRoot] - An alternative root object.
  39678. */
  39679. uncacheAction( clip, optionalRoot ) {
  39680. const action = this.existingAction( clip, optionalRoot );
  39681. if ( action !== null ) {
  39682. this._deactivateAction( action );
  39683. this._removeInactiveAction( action );
  39684. }
  39685. }
  39686. }
  39687. /**
  39688. * Represents a 3D render target.
  39689. *
  39690. * @augments RenderTarget
  39691. */
  39692. class RenderTarget3D extends RenderTarget {
  39693. /**
  39694. * Constructs a new 3D render target.
  39695. *
  39696. * @param {number} [width=1] - The width of the render target.
  39697. * @param {number} [height=1] - The height of the render target.
  39698. * @param {number} [depth=1] - The height of the render target.
  39699. * @param {RenderTarget~Options} [options] - The configuration object.
  39700. */
  39701. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39702. super( width, height, options );
  39703. /**
  39704. * This flag can be used for type testing.
  39705. *
  39706. * @type {boolean}
  39707. * @readonly
  39708. * @default true
  39709. */
  39710. this.isRenderTarget3D = true;
  39711. this.depth = depth;
  39712. /**
  39713. * Overwritten with a different texture type.
  39714. *
  39715. * @type {Data3DTexture}
  39716. */
  39717. this.texture = new Data3DTexture( null, width, height, depth );
  39718. this._setTextureOptions( options );
  39719. this.texture.isRenderTargetTexture = true;
  39720. }
  39721. }
  39722. /**
  39723. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39724. *
  39725. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39726. * ```js
  39727. * uniforms: {
  39728. * time: { value: 1.0 },
  39729. * resolution: new Uniform( new Vector2() )
  39730. * };
  39731. * ```
  39732. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39733. * in {@link WebGLRenderer}.
  39734. */
  39735. class Uniform {
  39736. /**
  39737. * Constructs a new uniform.
  39738. *
  39739. * @param {any} value - The uniform value.
  39740. */
  39741. constructor( value ) {
  39742. /**
  39743. * The uniform value.
  39744. *
  39745. * @type {any}
  39746. */
  39747. this.value = value;
  39748. }
  39749. /**
  39750. * Returns a new uniform with copied values from this instance.
  39751. * If the value has a `clone()` method, the value is cloned as well.
  39752. *
  39753. * @return {Uniform} A clone of this instance.
  39754. */
  39755. clone() {
  39756. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39757. }
  39758. }
  39759. let _id = 0;
  39760. /**
  39761. * A class for managing multiple uniforms in a single group. The renderer will process
  39762. * such a definition as a single UBO.
  39763. *
  39764. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39765. * in {@link WebGLRenderer}.
  39766. *
  39767. * @augments EventDispatcher
  39768. */
  39769. class UniformsGroup extends EventDispatcher {
  39770. /**
  39771. * Constructs a new uniforms group.
  39772. */
  39773. constructor() {
  39774. super();
  39775. /**
  39776. * This flag can be used for type testing.
  39777. *
  39778. * @type {boolean}
  39779. * @readonly
  39780. * @default true
  39781. */
  39782. this.isUniformsGroup = true;
  39783. /**
  39784. * The ID of the 3D object.
  39785. *
  39786. * @name UniformsGroup#id
  39787. * @type {number}
  39788. * @readonly
  39789. */
  39790. Object.defineProperty( this, 'id', { value: _id ++ } );
  39791. /**
  39792. * The name of the uniforms group.
  39793. *
  39794. * @type {string}
  39795. */
  39796. this.name = '';
  39797. /**
  39798. * The buffer usage.
  39799. *
  39800. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39801. * @default StaticDrawUsage
  39802. */
  39803. this.usage = StaticDrawUsage;
  39804. /**
  39805. * An array holding the uniforms.
  39806. *
  39807. * @type {Array<Uniform>}
  39808. */
  39809. this.uniforms = [];
  39810. }
  39811. /**
  39812. * Adds the given uniform to this uniforms group.
  39813. *
  39814. * @param {Uniform} uniform - The uniform to add.
  39815. * @return {UniformsGroup} A reference to this uniforms group.
  39816. */
  39817. add( uniform ) {
  39818. this.uniforms.push( uniform );
  39819. return this;
  39820. }
  39821. /**
  39822. * Removes the given uniform from this uniforms group.
  39823. *
  39824. * @param {Uniform} uniform - The uniform to remove.
  39825. * @return {UniformsGroup} A reference to this uniforms group.
  39826. */
  39827. remove( uniform ) {
  39828. const index = this.uniforms.indexOf( uniform );
  39829. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39830. return this;
  39831. }
  39832. /**
  39833. * Sets the name of this uniforms group.
  39834. *
  39835. * @param {string} name - The name to set.
  39836. * @return {UniformsGroup} A reference to this uniforms group.
  39837. */
  39838. setName( name ) {
  39839. this.name = name;
  39840. return this;
  39841. }
  39842. /**
  39843. * Sets the usage of this uniforms group.
  39844. *
  39845. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39846. * @return {UniformsGroup} A reference to this uniforms group.
  39847. */
  39848. setUsage( value ) {
  39849. this.usage = value;
  39850. return this;
  39851. }
  39852. /**
  39853. * Frees the GPU-related resources allocated by this instance. Call this
  39854. * method whenever this instance is no longer used in your app.
  39855. *
  39856. * @fires Texture#dispose
  39857. */
  39858. dispose() {
  39859. this.dispatchEvent( { type: 'dispose' } );
  39860. }
  39861. /**
  39862. * Copies the values of the given uniforms group to this instance.
  39863. *
  39864. * @param {UniformsGroup} source - The uniforms group to copy.
  39865. * @return {UniformsGroup} A reference to this uniforms group.
  39866. */
  39867. copy( source ) {
  39868. this.name = source.name;
  39869. this.usage = source.usage;
  39870. const uniformsSource = source.uniforms;
  39871. this.uniforms.length = 0;
  39872. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39873. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39874. for ( let j = 0; j < uniforms.length; j ++ ) {
  39875. this.uniforms.push( uniforms[ j ].clone() );
  39876. }
  39877. }
  39878. return this;
  39879. }
  39880. /**
  39881. * Returns a new uniforms group with copied values from this instance.
  39882. *
  39883. * @return {UniformsGroup} A clone of this instance.
  39884. */
  39885. clone() {
  39886. return new this.constructor().copy( this );
  39887. }
  39888. }
  39889. /**
  39890. * An instanced version of an interleaved buffer.
  39891. *
  39892. * @augments InterleavedBuffer
  39893. */
  39894. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39895. /**
  39896. * Constructs a new instanced interleaved buffer.
  39897. *
  39898. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39899. * @param {number} stride - The number of typed-array elements per vertex.
  39900. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39901. */
  39902. constructor( array, stride, meshPerAttribute = 1 ) {
  39903. super( array, stride );
  39904. /**
  39905. * This flag can be used for type testing.
  39906. *
  39907. * @type {boolean}
  39908. * @readonly
  39909. * @default true
  39910. */
  39911. this.isInstancedInterleavedBuffer = true;
  39912. /**
  39913. * Defines how often a value of this buffer attribute should be repeated,
  39914. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39915. *
  39916. * @type {number}
  39917. * @default 1
  39918. */
  39919. this.meshPerAttribute = meshPerAttribute;
  39920. }
  39921. copy( source ) {
  39922. super.copy( source );
  39923. this.meshPerAttribute = source.meshPerAttribute;
  39924. return this;
  39925. }
  39926. clone( data ) {
  39927. const ib = super.clone( data );
  39928. ib.meshPerAttribute = this.meshPerAttribute;
  39929. return ib;
  39930. }
  39931. toJSON( data ) {
  39932. const json = super.toJSON( data );
  39933. json.isInstancedInterleavedBuffer = true;
  39934. json.meshPerAttribute = this.meshPerAttribute;
  39935. return json;
  39936. }
  39937. }
  39938. /**
  39939. * An alternative version of a buffer attribute with more control over the VBO.
  39940. *
  39941. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39942. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39943. *
  39944. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39945. * or even produces the VBOs in question.
  39946. *
  39947. * Notice that this class can only be used with {@link WebGLRenderer}.
  39948. */
  39949. class GLBufferAttribute {
  39950. /**
  39951. * Constructs a new GL buffer attribute.
  39952. *
  39953. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39954. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39955. * @param {number} itemSize - The item size.
  39956. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39957. * @param {number} count - The expected number of vertices in VBO.
  39958. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39959. */
  39960. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39961. /**
  39962. * This flag can be used for type testing.
  39963. *
  39964. * @type {boolean}
  39965. * @readonly
  39966. * @default true
  39967. */
  39968. this.isGLBufferAttribute = true;
  39969. /**
  39970. * The name of the buffer attribute.
  39971. *
  39972. * @type {string}
  39973. */
  39974. this.name = '';
  39975. /**
  39976. * The native WebGL buffer.
  39977. *
  39978. * @type {WebGLBuffer}
  39979. */
  39980. this.buffer = buffer;
  39981. /**
  39982. * The native data type.
  39983. *
  39984. * @type {number}
  39985. */
  39986. this.type = type;
  39987. /**
  39988. * The item size, see {@link BufferAttribute#itemSize}.
  39989. *
  39990. * @type {number}
  39991. */
  39992. this.itemSize = itemSize;
  39993. /**
  39994. * The corresponding size (in bytes) for the given `type` parameter.
  39995. *
  39996. * @type {number}
  39997. */
  39998. this.elementSize = elementSize;
  39999. /**
  40000. * The expected number of vertices in VBO.
  40001. *
  40002. * @type {number}
  40003. */
  40004. this.count = count;
  40005. /**
  40006. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  40007. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  40008. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  40009. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  40010. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  40011. *
  40012. * @type {boolean}
  40013. */
  40014. this.normalized = normalized;
  40015. /**
  40016. * A version number, incremented every time the `needsUpdate` is set to `true`.
  40017. *
  40018. * @type {number}
  40019. */
  40020. this.version = 0;
  40021. }
  40022. /**
  40023. * Flag to indicate that this attribute has changed and should be re-sent to
  40024. * the GPU. Set this to `true` when you modify the value of the array.
  40025. *
  40026. * @type {number}
  40027. * @default false
  40028. * @param {boolean} value
  40029. */
  40030. set needsUpdate( value ) {
  40031. if ( value === true ) this.version ++;
  40032. }
  40033. /**
  40034. * Sets the given native WebGL buffer.
  40035. *
  40036. * @param {WebGLBuffer} buffer - The buffer to set.
  40037. * @return {BufferAttribute} A reference to this instance.
  40038. */
  40039. setBuffer( buffer ) {
  40040. this.buffer = buffer;
  40041. return this;
  40042. }
  40043. /**
  40044. * Sets the given native data type and element size.
  40045. *
  40046. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40047. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40048. * @return {BufferAttribute} A reference to this instance.
  40049. */
  40050. setType( type, elementSize ) {
  40051. this.type = type;
  40052. this.elementSize = elementSize;
  40053. return this;
  40054. }
  40055. /**
  40056. * Sets the item size.
  40057. *
  40058. * @param {number} itemSize - The item size.
  40059. * @return {BufferAttribute} A reference to this instance.
  40060. */
  40061. setItemSize( itemSize ) {
  40062. this.itemSize = itemSize;
  40063. return this;
  40064. }
  40065. /**
  40066. * Sets the count (the expected number of vertices in VBO).
  40067. *
  40068. * @param {number} count - The count.
  40069. * @return {BufferAttribute} A reference to this instance.
  40070. */
  40071. setCount( count ) {
  40072. this.count = count;
  40073. return this;
  40074. }
  40075. }
  40076. const _matrix = /*@__PURE__*/ new Matrix4();
  40077. /**
  40078. * This class is designed to assist with raycasting. Raycasting is used for
  40079. * mouse picking (working out what objects in the 3d space the mouse is over)
  40080. * amongst other things.
  40081. */
  40082. class Raycaster {
  40083. /**
  40084. * Constructs a new raycaster.
  40085. *
  40086. * @param {Vector3} origin - The origin vector where the ray casts from.
  40087. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40088. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  40089. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  40090. */
  40091. constructor( origin, direction, near = 0, far = Infinity ) {
  40092. /**
  40093. * The ray used for raycasting.
  40094. *
  40095. * @type {Ray}
  40096. */
  40097. this.ray = new Ray( origin, direction );
  40098. /**
  40099. * All results returned are further away than near. Near can't be negative.
  40100. *
  40101. * @type {number}
  40102. * @default 0
  40103. */
  40104. this.near = near;
  40105. /**
  40106. * All results returned are closer than far. Far can't be lower than near.
  40107. *
  40108. * @type {number}
  40109. * @default Infinity
  40110. */
  40111. this.far = far;
  40112. /**
  40113. * The camera to use when raycasting against view-dependent objects such as
  40114. * billboarded objects like sprites. This field can be set manually or
  40115. * is set when calling `setFromCamera()`.
  40116. *
  40117. * @type {?Camera}
  40118. * @default null
  40119. */
  40120. this.camera = null;
  40121. /**
  40122. * Allows to selectively ignore 3D objects when performing intersection tests.
  40123. * The following code example ensures that only 3D objects on layer `1` will be
  40124. * honored by raycaster.
  40125. * ```js
  40126. * raycaster.layers.set( 1 );
  40127. * object.layers.enable( 1 );
  40128. * ```
  40129. *
  40130. * @type {Layers}
  40131. */
  40132. this.layers = new Layers();
  40133. /**
  40134. * A parameter object that configures the raycasting. It has the structure:
  40135. *
  40136. * ```
  40137. * {
  40138. * Mesh: {},
  40139. * Line: { threshold: 1 },
  40140. * LOD: {},
  40141. * Points: { threshold: 1 },
  40142. * Sprite: {}
  40143. * }
  40144. * ```
  40145. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  40146. *
  40147. * @type {Object}
  40148. */
  40149. this.params = {
  40150. Mesh: {},
  40151. Line: { threshold: 1 },
  40152. LOD: {},
  40153. Points: { threshold: 1 },
  40154. Sprite: {}
  40155. };
  40156. }
  40157. /**
  40158. * Updates the ray with a new origin and direction by copying the values from the arguments.
  40159. *
  40160. * @param {Vector3} origin - The origin vector where the ray casts from.
  40161. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40162. */
  40163. set( origin, direction ) {
  40164. // direction is assumed to be normalized (for accurate distance calculations)
  40165. this.ray.set( origin, direction );
  40166. }
  40167. /**
  40168. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  40169. *
  40170. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  40171. * X and Y components should be between `-1` and `1`.
  40172. * @param {Camera} camera - The camera from which the ray should originate.
  40173. */
  40174. setFromCamera( coords, camera ) {
  40175. if ( camera.isPerspectiveCamera ) {
  40176. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  40177. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  40178. this.camera = camera;
  40179. } else if ( camera.isOrthographicCamera ) {
  40180. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  40181. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  40182. this.camera = camera;
  40183. } else {
  40184. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  40185. }
  40186. }
  40187. /**
  40188. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  40189. *
  40190. * @param {WebXRController} controller - The controller to copy the position and direction from.
  40191. * @return {Raycaster} A reference to this raycaster.
  40192. */
  40193. setFromXRController( controller ) {
  40194. _matrix.identity().extractRotation( controller.matrixWorld );
  40195. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  40196. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  40197. return this;
  40198. }
  40199. /**
  40200. * The intersection point of a raycaster intersection test.
  40201. * @typedef {Object} Raycaster~Intersection
  40202. * @property {number} distance - The distance from the ray's origin to the intersection point.
  40203. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  40204. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  40205. * @property {Vector3} point - The intersection point, in world coordinates.
  40206. * @property {Object} face - The face that has been intersected.
  40207. * @property {number} faceIndex - The face index.
  40208. * @property {Object3D} object - The 3D object that has been intersected.
  40209. * @property {Vector2} uv - U,V coordinates at point of intersection.
  40210. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  40211. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  40212. * @property {number} instanceId - The index number of the instance where the ray
  40213. * intersects the {@link InstancedMesh}.
  40214. */
  40215. /**
  40216. * Checks all intersection between the ray and the object with or without the
  40217. * descendants. Intersections are returned sorted by distance, closest first.
  40218. *
  40219. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  40220. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  40221. * differently to ray casting than lines or points.
  40222. *
  40223. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  40224. * to be detected; intersections of the ray passing through the back of a face will not
  40225. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  40226. * to `THREE.DoubleSide`.
  40227. *
  40228. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  40229. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40230. * Otherwise it only checks intersection with the object.
  40231. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40232. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40233. */
  40234. intersectObject( object, recursive = true, intersects = [] ) {
  40235. intersect( object, this, intersects, recursive );
  40236. intersects.sort( ascSort );
  40237. return intersects;
  40238. }
  40239. /**
  40240. * Checks all intersection between the ray and the objects with or without
  40241. * the descendants. Intersections are returned sorted by distance, closest first.
  40242. *
  40243. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  40244. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40245. * Otherwise it only checks intersection with the object.
  40246. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40247. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40248. */
  40249. intersectObjects( objects, recursive = true, intersects = [] ) {
  40250. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  40251. intersect( objects[ i ], this, intersects, recursive );
  40252. }
  40253. intersects.sort( ascSort );
  40254. return intersects;
  40255. }
  40256. }
  40257. function ascSort( a, b ) {
  40258. return a.distance - b.distance;
  40259. }
  40260. function intersect( object, raycaster, intersects, recursive ) {
  40261. let propagate = true;
  40262. if ( object.layers.test( raycaster.layers ) ) {
  40263. const result = object.raycast( raycaster, intersects );
  40264. if ( result === false ) propagate = false;
  40265. }
  40266. if ( propagate === true && recursive === true ) {
  40267. const children = object.children;
  40268. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40269. intersect( children[ i ], raycaster, intersects, true );
  40270. }
  40271. }
  40272. }
  40273. /**
  40274. * This class is an alternative to {@link Clock} with a different API design and behavior.
  40275. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  40276. *
  40277. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  40278. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  40279. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  40280. * is inactive (e.g. tab switched or browser hidden).
  40281. *
  40282. * ```js
  40283. * const timer = new Timer();
  40284. * timer.connect( document ); // use Page Visibility API
  40285. * ```
  40286. */
  40287. class Timer {
  40288. /**
  40289. * Constructs a new timer.
  40290. */
  40291. constructor() {
  40292. this._previousTime = 0;
  40293. this._currentTime = 0;
  40294. this._startTime = performance.now();
  40295. this._delta = 0;
  40296. this._elapsed = 0;
  40297. this._timescale = 1;
  40298. this._document = null;
  40299. this._pageVisibilityHandler = null;
  40300. }
  40301. /**
  40302. * Connect the timer to the given document.Calling this method is not mandatory to
  40303. * use the timer but enables the usage of the Page Visibility API to avoid large time
  40304. * delta values.
  40305. *
  40306. * @param {Document} document - The document.
  40307. */
  40308. connect( document ) {
  40309. this._document = document;
  40310. // use Page Visibility API to avoid large time delta values
  40311. if ( document.hidden !== undefined ) {
  40312. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  40313. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  40314. }
  40315. }
  40316. /**
  40317. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  40318. */
  40319. disconnect() {
  40320. if ( this._pageVisibilityHandler !== null ) {
  40321. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  40322. this._pageVisibilityHandler = null;
  40323. }
  40324. this._document = null;
  40325. }
  40326. /**
  40327. * Returns the time delta in seconds.
  40328. *
  40329. * @return {number} The time delta in second.
  40330. */
  40331. getDelta() {
  40332. return this._delta / 1000;
  40333. }
  40334. /**
  40335. * Returns the elapsed time in seconds.
  40336. *
  40337. * @return {number} The elapsed time in second.
  40338. */
  40339. getElapsed() {
  40340. return this._elapsed / 1000;
  40341. }
  40342. /**
  40343. * Returns the timescale.
  40344. *
  40345. * @return {number} The timescale.
  40346. */
  40347. getTimescale() {
  40348. return this._timescale;
  40349. }
  40350. /**
  40351. * Sets the given timescale which scale the time delta computation
  40352. * in `update()`.
  40353. *
  40354. * @param {number} timescale - The timescale to set.
  40355. * @return {Timer} A reference to this timer.
  40356. */
  40357. setTimescale( timescale ) {
  40358. this._timescale = timescale;
  40359. return this;
  40360. }
  40361. /**
  40362. * Resets the time computation for the current simulation step.
  40363. *
  40364. * @return {Timer} A reference to this timer.
  40365. */
  40366. reset() {
  40367. this._currentTime = performance.now() - this._startTime;
  40368. return this;
  40369. }
  40370. /**
  40371. * Can be used to free all internal resources. Usually called when
  40372. * the timer instance isn't required anymore.
  40373. */
  40374. dispose() {
  40375. this.disconnect();
  40376. }
  40377. /**
  40378. * Updates the internal state of the timer. This method should be called
  40379. * once per simulation step and before you perform queries against the timer
  40380. * (e.g. via `getDelta()`).
  40381. *
  40382. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  40383. * from the `requestAnimationFrame` callback argument. If not provided, the current
  40384. * time will be determined with `performance.now`.
  40385. * @return {Timer} A reference to this timer.
  40386. */
  40387. update( timestamp ) {
  40388. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  40389. this._delta = 0;
  40390. } else {
  40391. this._previousTime = this._currentTime;
  40392. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  40393. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  40394. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  40395. }
  40396. return this;
  40397. }
  40398. }
  40399. function handleVisibilityChange() {
  40400. if ( this._document.hidden === false ) this.reset();
  40401. }
  40402. /**
  40403. * This class can be used to represent points in 3D space as
  40404. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40405. */
  40406. class Spherical {
  40407. /**
  40408. * Constructs a new spherical.
  40409. *
  40410. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40411. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40412. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40413. */
  40414. constructor( radius = 1, phi = 0, theta = 0 ) {
  40415. /**
  40416. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40417. *
  40418. * @type {number}
  40419. * @default 1
  40420. */
  40421. this.radius = radius;
  40422. /**
  40423. * The polar angle in radians from the y (up) axis.
  40424. *
  40425. * @type {number}
  40426. * @default 0
  40427. */
  40428. this.phi = phi;
  40429. /**
  40430. * The equator/azimuthal angle in radians around the y (up) axis.
  40431. *
  40432. * @type {number}
  40433. * @default 0
  40434. */
  40435. this.theta = theta;
  40436. }
  40437. /**
  40438. * Sets the spherical components by copying the given values.
  40439. *
  40440. * @param {number} radius - The radius.
  40441. * @param {number} phi - The polar angle.
  40442. * @param {number} theta - The azimuthal angle.
  40443. * @return {Spherical} A reference to this spherical.
  40444. */
  40445. set( radius, phi, theta ) {
  40446. this.radius = radius;
  40447. this.phi = phi;
  40448. this.theta = theta;
  40449. return this;
  40450. }
  40451. /**
  40452. * Copies the values of the given spherical to this instance.
  40453. *
  40454. * @param {Spherical} other - The spherical to copy.
  40455. * @return {Spherical} A reference to this spherical.
  40456. */
  40457. copy( other ) {
  40458. this.radius = other.radius;
  40459. this.phi = other.phi;
  40460. this.theta = other.theta;
  40461. return this;
  40462. }
  40463. /**
  40464. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40465. * `0.000001`.
  40466. *
  40467. * @return {Spherical} A reference to this spherical.
  40468. */
  40469. makeSafe() {
  40470. const EPS = 0.000001;
  40471. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40472. return this;
  40473. }
  40474. /**
  40475. * Sets the spherical components from the given vector which is assumed to hold
  40476. * Cartesian coordinates.
  40477. *
  40478. * @param {Vector3} v - The vector to set.
  40479. * @return {Spherical} A reference to this spherical.
  40480. */
  40481. setFromVector3( v ) {
  40482. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40483. }
  40484. /**
  40485. * Sets the spherical components from the given Cartesian coordinates.
  40486. *
  40487. * @param {number} x - The x value.
  40488. * @param {number} y - The y value.
  40489. * @param {number} z - The z value.
  40490. * @return {Spherical} A reference to this spherical.
  40491. */
  40492. setFromCartesianCoords( x, y, z ) {
  40493. this.radius = Math.sqrt( x * x + y * y + z * z );
  40494. if ( this.radius === 0 ) {
  40495. this.theta = 0;
  40496. this.phi = 0;
  40497. } else {
  40498. this.theta = Math.atan2( x, z );
  40499. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40500. }
  40501. return this;
  40502. }
  40503. /**
  40504. * Returns a new spherical with copied values from this instance.
  40505. *
  40506. * @return {Spherical} A clone of this instance.
  40507. */
  40508. clone() {
  40509. return new this.constructor().copy( this );
  40510. }
  40511. }
  40512. /**
  40513. * This class can be used to represent points in 3D space as
  40514. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40515. */
  40516. class Cylindrical {
  40517. /**
  40518. * Constructs a new cylindrical.
  40519. *
  40520. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40521. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40522. * @param {number} [y=0] - The height above the x-z plane.
  40523. */
  40524. constructor( radius = 1, theta = 0, y = 0 ) {
  40525. /**
  40526. * The distance from the origin to a point in the x-z plane.
  40527. *
  40528. * @type {number}
  40529. * @default 1
  40530. */
  40531. this.radius = radius;
  40532. /**
  40533. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40534. *
  40535. * @type {number}
  40536. * @default 0
  40537. */
  40538. this.theta = theta;
  40539. /**
  40540. * The height above the x-z plane.
  40541. *
  40542. * @type {number}
  40543. * @default 0
  40544. */
  40545. this.y = y;
  40546. }
  40547. /**
  40548. * Sets the cylindrical components by copying the given values.
  40549. *
  40550. * @param {number} radius - The radius.
  40551. * @param {number} theta - The theta angle.
  40552. * @param {number} y - The height value.
  40553. * @return {Cylindrical} A reference to this cylindrical.
  40554. */
  40555. set( radius, theta, y ) {
  40556. this.radius = radius;
  40557. this.theta = theta;
  40558. this.y = y;
  40559. return this;
  40560. }
  40561. /**
  40562. * Copies the values of the given cylindrical to this instance.
  40563. *
  40564. * @param {Cylindrical} other - The cylindrical to copy.
  40565. * @return {Cylindrical} A reference to this cylindrical.
  40566. */
  40567. copy( other ) {
  40568. this.radius = other.radius;
  40569. this.theta = other.theta;
  40570. this.y = other.y;
  40571. return this;
  40572. }
  40573. /**
  40574. * Sets the cylindrical components from the given vector which is assumed to hold
  40575. * Cartesian coordinates.
  40576. *
  40577. * @param {Vector3} v - The vector to set.
  40578. * @return {Cylindrical} A reference to this cylindrical.
  40579. */
  40580. setFromVector3( v ) {
  40581. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40582. }
  40583. /**
  40584. * Sets the cylindrical components from the given Cartesian coordinates.
  40585. *
  40586. * @param {number} x - The x value.
  40587. * @param {number} y - The x value.
  40588. * @param {number} z - The x value.
  40589. * @return {Cylindrical} A reference to this cylindrical.
  40590. */
  40591. setFromCartesianCoords( x, y, z ) {
  40592. this.radius = Math.sqrt( x * x + z * z );
  40593. this.theta = Math.atan2( x, z );
  40594. this.y = y;
  40595. return this;
  40596. }
  40597. /**
  40598. * Returns a new cylindrical with copied values from this instance.
  40599. *
  40600. * @return {Cylindrical} A clone of this instance.
  40601. */
  40602. clone() {
  40603. return new this.constructor().copy( this );
  40604. }
  40605. }
  40606. /**
  40607. * Represents a 2x2 matrix.
  40608. *
  40609. * A Note on Row-Major and Column-Major Ordering:
  40610. *
  40611. * The constructor and {@link Matrix2#set} method take arguments in
  40612. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40613. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40614. * This means that calling:
  40615. * ```js
  40616. * const m = new THREE.Matrix2();
  40617. * m.set( 11, 12,
  40618. * 21, 22 );
  40619. * ```
  40620. * will result in the elements array containing:
  40621. * ```js
  40622. * m.elements = [ 11, 21,
  40623. * 12, 22 ];
  40624. * ```
  40625. * and internally all calculations are performed using column-major ordering.
  40626. * However, as the actual ordering makes no difference mathematically and
  40627. * most people are used to thinking about matrices in row-major order, the
  40628. * three.js documentation shows matrices in row-major order. Just bear in
  40629. * mind that if you are reading the source code, you'll have to take the
  40630. * transpose of any matrices outlined here to make sense of the calculations.
  40631. */
  40632. class Matrix2 {
  40633. /**
  40634. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40635. * in row-major order. If no arguments are provided, the constructor
  40636. * initializes the matrix as an identity matrix.
  40637. *
  40638. * @param {number} [n11] - 1-1 matrix element.
  40639. * @param {number} [n12] - 1-2 matrix element.
  40640. * @param {number} [n21] - 2-1 matrix element.
  40641. * @param {number} [n22] - 2-2 matrix element.
  40642. */
  40643. constructor( n11, n12, n21, n22 ) {
  40644. /**
  40645. * This flag can be used for type testing.
  40646. *
  40647. * @type {boolean}
  40648. * @readonly
  40649. * @default true
  40650. */
  40651. Matrix2.prototype.isMatrix2 = true;
  40652. /**
  40653. * A column-major list of matrix values.
  40654. *
  40655. * @type {Array<number>}
  40656. */
  40657. this.elements = [
  40658. 1, 0,
  40659. 0, 1,
  40660. ];
  40661. if ( n11 !== undefined ) {
  40662. this.set( n11, n12, n21, n22 );
  40663. }
  40664. }
  40665. /**
  40666. * Sets this matrix to the 2x2 identity matrix.
  40667. *
  40668. * @return {Matrix2} A reference to this matrix.
  40669. */
  40670. identity() {
  40671. this.set(
  40672. 1, 0,
  40673. 0, 1,
  40674. );
  40675. return this;
  40676. }
  40677. /**
  40678. * Sets the elements of the matrix from the given array.
  40679. *
  40680. * @param {Array<number>} array - The matrix elements in column-major order.
  40681. * @param {number} [offset=0] - Index of the first element in the array.
  40682. * @return {Matrix2} A reference to this matrix.
  40683. */
  40684. fromArray( array, offset = 0 ) {
  40685. for ( let i = 0; i < 4; i ++ ) {
  40686. this.elements[ i ] = array[ i + offset ];
  40687. }
  40688. return this;
  40689. }
  40690. /**
  40691. * Sets the elements of the matrix.The arguments are supposed to be
  40692. * in row-major order.
  40693. *
  40694. * @param {number} n11 - 1-1 matrix element.
  40695. * @param {number} n12 - 1-2 matrix element.
  40696. * @param {number} n21 - 2-1 matrix element.
  40697. * @param {number} n22 - 2-2 matrix element.
  40698. * @return {Matrix2} A reference to this matrix.
  40699. */
  40700. set( n11, n12, n21, n22 ) {
  40701. const te = this.elements;
  40702. te[ 0 ] = n11; te[ 2 ] = n12;
  40703. te[ 1 ] = n21; te[ 3 ] = n22;
  40704. return this;
  40705. }
  40706. }
  40707. const _vector$4 = /*@__PURE__*/ new Vector2();
  40708. /**
  40709. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40710. */
  40711. class Box2 {
  40712. /**
  40713. * Constructs a new bounding box.
  40714. *
  40715. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40716. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40717. */
  40718. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40719. /**
  40720. * This flag can be used for type testing.
  40721. *
  40722. * @type {boolean}
  40723. * @readonly
  40724. * @default true
  40725. */
  40726. this.isBox2 = true;
  40727. /**
  40728. * The lower boundary of the box.
  40729. *
  40730. * @type {Vector2}
  40731. */
  40732. this.min = min;
  40733. /**
  40734. * The upper boundary of the box.
  40735. *
  40736. * @type {Vector2}
  40737. */
  40738. this.max = max;
  40739. }
  40740. /**
  40741. * Sets the lower and upper boundaries of this box.
  40742. * Please note that this method only copies the values from the given objects.
  40743. *
  40744. * @param {Vector2} min - The lower boundary of the box.
  40745. * @param {Vector2} max - The upper boundary of the box.
  40746. * @return {Box2} A reference to this bounding box.
  40747. */
  40748. set( min, max ) {
  40749. this.min.copy( min );
  40750. this.max.copy( max );
  40751. return this;
  40752. }
  40753. /**
  40754. * Sets the upper and lower bounds of this box so it encloses the position data
  40755. * in the given array.
  40756. *
  40757. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40758. * @return {Box2} A reference to this bounding box.
  40759. */
  40760. setFromPoints( points ) {
  40761. this.makeEmpty();
  40762. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40763. this.expandByPoint( points[ i ] );
  40764. }
  40765. return this;
  40766. }
  40767. /**
  40768. * Centers this box on the given center vector and sets this box's width, height and
  40769. * depth to the given size values.
  40770. *
  40771. * @param {Vector2} center - The center of the box.
  40772. * @param {Vector2} size - The x and y dimensions of the box.
  40773. * @return {Box2} A reference to this bounding box.
  40774. */
  40775. setFromCenterAndSize( center, size ) {
  40776. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40777. this.min.copy( center ).sub( halfSize );
  40778. this.max.copy( center ).add( halfSize );
  40779. return this;
  40780. }
  40781. /**
  40782. * Returns a new box with copied values from this instance.
  40783. *
  40784. * @return {Box2} A clone of this instance.
  40785. */
  40786. clone() {
  40787. return new this.constructor().copy( this );
  40788. }
  40789. /**
  40790. * Copies the values of the given box to this instance.
  40791. *
  40792. * @param {Box2} box - The box to copy.
  40793. * @return {Box2} A reference to this bounding box.
  40794. */
  40795. copy( box ) {
  40796. this.min.copy( box.min );
  40797. this.max.copy( box.max );
  40798. return this;
  40799. }
  40800. /**
  40801. * Makes this box empty which means in encloses a zero space in 2D.
  40802. *
  40803. * @return {Box2} A reference to this bounding box.
  40804. */
  40805. makeEmpty() {
  40806. this.min.x = this.min.y = + Infinity;
  40807. this.max.x = this.max.y = - Infinity;
  40808. return this;
  40809. }
  40810. /**
  40811. * Returns true if this box includes zero points within its bounds.
  40812. * Note that a box with equal lower and upper bounds still includes one
  40813. * point, the one both bounds share.
  40814. *
  40815. * @return {boolean} Whether this box is empty or not.
  40816. */
  40817. isEmpty() {
  40818. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40819. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40820. }
  40821. /**
  40822. * Returns the center point of this box.
  40823. *
  40824. * @param {Vector2} target - The target vector that is used to store the method's result.
  40825. * @return {Vector2} The center point.
  40826. */
  40827. getCenter( target ) {
  40828. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40829. }
  40830. /**
  40831. * Returns the dimensions of this box.
  40832. *
  40833. * @param {Vector2} target - The target vector that is used to store the method's result.
  40834. * @return {Vector2} The size.
  40835. */
  40836. getSize( target ) {
  40837. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40838. }
  40839. /**
  40840. * Expands the boundaries of this box to include the given point.
  40841. *
  40842. * @param {Vector2} point - The point that should be included by the bounding box.
  40843. * @return {Box2} A reference to this bounding box.
  40844. */
  40845. expandByPoint( point ) {
  40846. this.min.min( point );
  40847. this.max.max( point );
  40848. return this;
  40849. }
  40850. /**
  40851. * Expands this box equilaterally by the given vector. The width of this
  40852. * box will be expanded by the x component of the vector in both
  40853. * directions. The height of this box will be expanded by the y component of
  40854. * the vector in both directions.
  40855. *
  40856. * @param {Vector2} vector - The vector that should expand the bounding box.
  40857. * @return {Box2} A reference to this bounding box.
  40858. */
  40859. expandByVector( vector ) {
  40860. this.min.sub( vector );
  40861. this.max.add( vector );
  40862. return this;
  40863. }
  40864. /**
  40865. * Expands each dimension of the box by the given scalar. If negative, the
  40866. * dimensions of the box will be contracted.
  40867. *
  40868. * @param {number} scalar - The scalar value that should expand the bounding box.
  40869. * @return {Box2} A reference to this bounding box.
  40870. */
  40871. expandByScalar( scalar ) {
  40872. this.min.addScalar( - scalar );
  40873. this.max.addScalar( scalar );
  40874. return this;
  40875. }
  40876. /**
  40877. * Returns `true` if the given point lies within or on the boundaries of this box.
  40878. *
  40879. * @param {Vector2} point - The point to test.
  40880. * @return {boolean} Whether the bounding box contains the given point or not.
  40881. */
  40882. containsPoint( point ) {
  40883. return point.x >= this.min.x && point.x <= this.max.x &&
  40884. point.y >= this.min.y && point.y <= this.max.y;
  40885. }
  40886. /**
  40887. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40888. * If this box and the given one are identical, this function also returns `true`.
  40889. *
  40890. * @param {Box2} box - The bounding box to test.
  40891. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40892. */
  40893. containsBox( box ) {
  40894. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40895. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40896. }
  40897. /**
  40898. * Returns a point as a proportion of this box's width and height.
  40899. *
  40900. * @param {Vector2} point - A point in 2D space.
  40901. * @param {Vector2} target - The target vector that is used to store the method's result.
  40902. * @return {Vector2} A point as a proportion of this box's width and height.
  40903. */
  40904. getParameter( point, target ) {
  40905. // This can potentially have a divide by zero if the box
  40906. // has a size dimension of 0.
  40907. return target.set(
  40908. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40909. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40910. );
  40911. }
  40912. /**
  40913. * Returns `true` if the given bounding box intersects with this bounding box.
  40914. *
  40915. * @param {Box2} box - The bounding box to test.
  40916. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40917. */
  40918. intersectsBox( box ) {
  40919. // using 4 splitting planes to rule out intersections
  40920. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40921. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40922. }
  40923. /**
  40924. * Clamps the given point within the bounds of this box.
  40925. *
  40926. * @param {Vector2} point - The point to clamp.
  40927. * @param {Vector2} target - The target vector that is used to store the method's result.
  40928. * @return {Vector2} The clamped point.
  40929. */
  40930. clampPoint( point, target ) {
  40931. return target.copy( point ).clamp( this.min, this.max );
  40932. }
  40933. /**
  40934. * Returns the euclidean distance from any edge of this box to the specified point. If
  40935. * the given point lies inside of this box, the distance will be `0`.
  40936. *
  40937. * @param {Vector2} point - The point to compute the distance to.
  40938. * @return {number} The euclidean distance.
  40939. */
  40940. distanceToPoint( point ) {
  40941. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40942. }
  40943. /**
  40944. * Computes the intersection of this bounding box and the given one, setting the upper
  40945. * bound of this box to the lesser of the two boxes' upper bounds and the
  40946. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40947. * there's no overlap, makes this box empty.
  40948. *
  40949. * @param {Box2} box - The bounding box to intersect with.
  40950. * @return {Box2} A reference to this bounding box.
  40951. */
  40952. intersect( box ) {
  40953. this.min.max( box.min );
  40954. this.max.min( box.max );
  40955. if ( this.isEmpty() ) this.makeEmpty();
  40956. return this;
  40957. }
  40958. /**
  40959. * Computes the union of this box and another and the given one, setting the upper
  40960. * bound of this box to the greater of the two boxes' upper bounds and the
  40961. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40962. *
  40963. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40964. * @return {Box2} A reference to this bounding box.
  40965. */
  40966. union( box ) {
  40967. this.min.min( box.min );
  40968. this.max.max( box.max );
  40969. return this;
  40970. }
  40971. /**
  40972. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40973. * effectively moving it in 2D space.
  40974. *
  40975. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40976. * @return {Box2} A reference to this bounding box.
  40977. */
  40978. translate( offset ) {
  40979. this.min.add( offset );
  40980. this.max.add( offset );
  40981. return this;
  40982. }
  40983. /**
  40984. * Returns `true` if this bounding box is equal with the given one.
  40985. *
  40986. * @param {Box2} box - The box to test for equality.
  40987. * @return {boolean} Whether this bounding box is equal with the given one.
  40988. */
  40989. equals( box ) {
  40990. return box.min.equals( this.min ) && box.max.equals( this.max );
  40991. }
  40992. }
  40993. const _startP = /*@__PURE__*/ new Vector3();
  40994. const _startEnd = /*@__PURE__*/ new Vector3();
  40995. const _d1 = /*@__PURE__*/ new Vector3();
  40996. const _d2 = /*@__PURE__*/ new Vector3();
  40997. const _r = /*@__PURE__*/ new Vector3();
  40998. const _c1 = /*@__PURE__*/ new Vector3();
  40999. const _c2 = /*@__PURE__*/ new Vector3();
  41000. /**
  41001. * An analytical line segment in 3D space represented by a start and end point.
  41002. */
  41003. class Line3 {
  41004. /**
  41005. * Constructs a new line segment.
  41006. *
  41007. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  41008. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  41009. */
  41010. constructor( start = new Vector3(), end = new Vector3() ) {
  41011. /**
  41012. * Start of the line segment.
  41013. *
  41014. * @type {Vector3}
  41015. */
  41016. this.start = start;
  41017. /**
  41018. * End of the line segment.
  41019. *
  41020. * @type {Vector3}
  41021. */
  41022. this.end = end;
  41023. }
  41024. /**
  41025. * Sets the start and end values by copying the given vectors.
  41026. *
  41027. * @param {Vector3} start - The start point.
  41028. * @param {Vector3} end - The end point.
  41029. * @return {Line3} A reference to this line segment.
  41030. */
  41031. set( start, end ) {
  41032. this.start.copy( start );
  41033. this.end.copy( end );
  41034. return this;
  41035. }
  41036. /**
  41037. * Copies the values of the given line segment to this instance.
  41038. *
  41039. * @param {Line3} line - The line segment to copy.
  41040. * @return {Line3} A reference to this line segment.
  41041. */
  41042. copy( line ) {
  41043. this.start.copy( line.start );
  41044. this.end.copy( line.end );
  41045. return this;
  41046. }
  41047. /**
  41048. * Returns the center of the line segment.
  41049. *
  41050. * @param {Vector3} target - The target vector that is used to store the method's result.
  41051. * @return {Vector3} The center point.
  41052. */
  41053. getCenter( target ) {
  41054. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  41055. }
  41056. /**
  41057. * Returns the delta vector of the line segment's start and end point.
  41058. *
  41059. * @param {Vector3} target - The target vector that is used to store the method's result.
  41060. * @return {Vector3} The delta vector.
  41061. */
  41062. delta( target ) {
  41063. return target.subVectors( this.end, this.start );
  41064. }
  41065. /**
  41066. * Returns the squared Euclidean distance between the line' start and end point.
  41067. *
  41068. * @return {number} The squared Euclidean distance.
  41069. */
  41070. distanceSq() {
  41071. return this.start.distanceToSquared( this.end );
  41072. }
  41073. /**
  41074. * Returns the Euclidean distance between the line' start and end point.
  41075. *
  41076. * @return {number} The Euclidean distance.
  41077. */
  41078. distance() {
  41079. return this.start.distanceTo( this.end );
  41080. }
  41081. /**
  41082. * Returns a vector at a certain position along the line segment.
  41083. *
  41084. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  41085. * @param {Vector3} target - The target vector that is used to store the method's result.
  41086. * @return {Vector3} The delta vector.
  41087. */
  41088. at( t, target ) {
  41089. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41090. }
  41091. /**
  41092. * Returns a point parameter based on the closest point as projected on the line segment.
  41093. *
  41094. * @param {Vector3} point - The point for which to return a point parameter.
  41095. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41096. * @return {number} The point parameter.
  41097. */
  41098. closestPointToPointParameter( point, clampToLine ) {
  41099. _startP.subVectors( point, this.start );
  41100. _startEnd.subVectors( this.end, this.start );
  41101. const startEnd2 = _startEnd.dot( _startEnd );
  41102. const startEnd_startP = _startEnd.dot( _startP );
  41103. let t = startEnd_startP / startEnd2;
  41104. if ( clampToLine ) {
  41105. t = clamp( t, 0, 1 );
  41106. }
  41107. return t;
  41108. }
  41109. /**
  41110. * Returns the closest point on the line for a given point.
  41111. *
  41112. * @param {Vector3} point - The point to compute the closest point on the line for.
  41113. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41114. * @param {Vector3} target - The target vector that is used to store the method's result.
  41115. * @return {Vector3} The closest point on the line.
  41116. */
  41117. closestPointToPoint( point, clampToLine, target ) {
  41118. const t = this.closestPointToPointParameter( point, clampToLine );
  41119. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41120. }
  41121. /**
  41122. * Returns the closest squared distance between this line segment and the given one.
  41123. *
  41124. * @param {Line3} line - The line segment to compute the closest squared distance to.
  41125. * @param {Vector3} [c1] - The closest point on this line segment.
  41126. * @param {Vector3} [c2] - The closest point on the given line segment.
  41127. * @return {number} The squared distance between this line segment and the given one.
  41128. */
  41129. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  41130. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  41131. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  41132. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  41133. // distance between between S1(s) and S2(t)
  41134. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  41135. let s, t;
  41136. const p1 = this.start;
  41137. const p2 = line.start;
  41138. const q1 = this.end;
  41139. const q2 = line.end;
  41140. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  41141. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  41142. _r.subVectors( p1, p2 );
  41143. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  41144. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  41145. const f = _d2.dot( _r );
  41146. // Check if either or both segments degenerate into points
  41147. if ( a <= EPSILON && e <= EPSILON ) {
  41148. // Both segments degenerate into points
  41149. c1.copy( p1 );
  41150. c2.copy( p2 );
  41151. c1.sub( c2 );
  41152. return c1.dot( c1 );
  41153. }
  41154. if ( a <= EPSILON ) {
  41155. // First segment degenerates into a point
  41156. s = 0;
  41157. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  41158. t = clamp( t, 0, 1 );
  41159. } else {
  41160. const c = _d1.dot( _r );
  41161. if ( e <= EPSILON ) {
  41162. // Second segment degenerates into a point
  41163. t = 0;
  41164. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  41165. } else {
  41166. // The general nondegenerate case starts here
  41167. const b = _d1.dot( _d2 );
  41168. const denom = a * e - b * b; // Always nonnegative
  41169. // If segments not parallel, compute closest point on L1 to L2 and
  41170. // clamp to segment S1. Else pick arbitrary s (here 0)
  41171. if ( denom !== 0 ) {
  41172. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  41173. } else {
  41174. s = 0;
  41175. }
  41176. // Compute point on L2 closest to S1(s) using
  41177. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  41178. t = ( b * s + f ) / e;
  41179. // If t in [0,1] done. Else clamp t, recompute s for the new value
  41180. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  41181. // and clamp s to [0, 1]
  41182. if ( t < 0 ) {
  41183. t = 0.;
  41184. s = clamp( - c / a, 0, 1 );
  41185. } else if ( t > 1 ) {
  41186. t = 1;
  41187. s = clamp( ( b - c ) / a, 0, 1 );
  41188. }
  41189. }
  41190. }
  41191. c1.copy( p1 ).addScaledVector( _d1, s );
  41192. c2.copy( p2 ).addScaledVector( _d2, t );
  41193. return c1.distanceToSquared( c2 );
  41194. }
  41195. /**
  41196. * Applies a 4x4 transformation matrix to this line segment.
  41197. *
  41198. * @param {Matrix4} matrix - The transformation matrix.
  41199. * @return {Line3} A reference to this line segment.
  41200. */
  41201. applyMatrix4( matrix ) {
  41202. this.start.applyMatrix4( matrix );
  41203. this.end.applyMatrix4( matrix );
  41204. return this;
  41205. }
  41206. /**
  41207. * Returns `true` if this line segment is equal with the given one.
  41208. *
  41209. * @param {Line3} line - The line segment to test for equality.
  41210. * @return {boolean} Whether this line segment is equal with the given one.
  41211. */
  41212. equals( line ) {
  41213. return line.start.equals( this.start ) && line.end.equals( this.end );
  41214. }
  41215. /**
  41216. * Returns a new line segment with copied values from this instance.
  41217. *
  41218. * @return {Line3} A clone of this instance.
  41219. */
  41220. clone() {
  41221. return new this.constructor().copy( this );
  41222. }
  41223. }
  41224. const _vector$3 = /*@__PURE__*/ new Vector3();
  41225. /**
  41226. * This displays a cone shaped helper object for a {@link SpotLight}.
  41227. *
  41228. * When the spot light or its target are transformed or light properties are
  41229. * changed, it's necessary to call the `update()` method of the respective helper.
  41230. *
  41231. * ```js
  41232. * const spotLight = new THREE.SpotLight( 0xffffff );
  41233. * spotLight.position.set( 10, 10, 10 );
  41234. * scene.add( spotLight );
  41235. *
  41236. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  41237. * scene.add( spotLightHelper );
  41238. * ```
  41239. *
  41240. * @augments Object3D
  41241. */
  41242. class SpotLightHelper extends Object3D {
  41243. /**
  41244. * Constructs a new spot light helper.
  41245. *
  41246. * @param {HemisphereLight} light - The light to be visualized.
  41247. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41248. * the color of the light.
  41249. */
  41250. constructor( light, color ) {
  41251. super();
  41252. /**
  41253. * The light being visualized.
  41254. *
  41255. * @type {SpotLight}
  41256. */
  41257. this.light = light;
  41258. this.matrixAutoUpdate = false;
  41259. /**
  41260. * The color parameter passed in the constructor.
  41261. * If not set, the helper will take the color of the light.
  41262. *
  41263. * @type {number|Color|string}
  41264. */
  41265. this.color = color;
  41266. this.type = 'SpotLightHelper';
  41267. const geometry = new BufferGeometry();
  41268. const positions = [
  41269. 0, 0, 0, 0, 0, 1,
  41270. 0, 0, 0, 1, 0, 1,
  41271. 0, 0, 0, -1, 0, 1,
  41272. 0, 0, 0, 0, 1, 1,
  41273. 0, 0, 0, 0, -1, 1
  41274. ];
  41275. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  41276. const p1 = ( i / l ) * Math.PI * 2;
  41277. const p2 = ( j / l ) * Math.PI * 2;
  41278. positions.push(
  41279. Math.cos( p1 ), Math.sin( p1 ), 1,
  41280. Math.cos( p2 ), Math.sin( p2 ), 1
  41281. );
  41282. }
  41283. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41284. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41285. this.cone = new LineSegments( geometry, material );
  41286. this.add( this.cone );
  41287. this.update();
  41288. }
  41289. /**
  41290. * Frees the GPU-related resources allocated by this instance. Call this
  41291. * method whenever this instance is no longer used in your app.
  41292. */
  41293. dispose() {
  41294. this.cone.geometry.dispose();
  41295. this.cone.material.dispose();
  41296. }
  41297. /**
  41298. * Updates the helper to match the position and direction of the
  41299. * light being visualized.
  41300. */
  41301. update() {
  41302. this.light.updateWorldMatrix( true, false );
  41303. this.light.target.updateWorldMatrix( true, false );
  41304. // update the local matrix based on the parent and light target transforms
  41305. if ( this.parent ) {
  41306. this.parent.updateWorldMatrix( true );
  41307. this.matrix
  41308. .copy( this.parent.matrixWorld )
  41309. .invert()
  41310. .multiply( this.light.matrixWorld );
  41311. } else {
  41312. this.matrix.copy( this.light.matrixWorld );
  41313. }
  41314. this.matrixWorld.copy( this.light.matrixWorld );
  41315. const coneLength = this.light.distance ? this.light.distance : 1000;
  41316. const coneWidth = coneLength * Math.tan( this.light.angle );
  41317. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41318. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41319. this.cone.lookAt( _vector$3 );
  41320. if ( this.color !== undefined ) {
  41321. this.cone.material.color.set( this.color );
  41322. } else {
  41323. this.cone.material.color.copy( this.light.color );
  41324. }
  41325. }
  41326. }
  41327. const _vector$2 = /*@__PURE__*/ new Vector3();
  41328. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41329. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41330. /**
  41331. * A helper object to assist with visualizing a {@link Skeleton}.
  41332. *
  41333. * ```js
  41334. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41335. * scene.add( helper );
  41336. * ```
  41337. *
  41338. * @augments LineSegments
  41339. */
  41340. class SkeletonHelper extends LineSegments {
  41341. /**
  41342. * Constructs a new skeleton helper.
  41343. *
  41344. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41345. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41346. */
  41347. constructor( object ) {
  41348. const bones = getBoneList( object );
  41349. const geometry = new BufferGeometry();
  41350. const vertices = [];
  41351. const colors = [];
  41352. for ( let i = 0; i < bones.length; i ++ ) {
  41353. const bone = bones[ i ];
  41354. if ( bone.parent && bone.parent.isBone ) {
  41355. vertices.push( 0, 0, 0 );
  41356. vertices.push( 0, 0, 0 );
  41357. colors.push( 0, 0, 0 );
  41358. colors.push( 0, 0, 0 );
  41359. }
  41360. }
  41361. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41362. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41363. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41364. super( geometry, material );
  41365. /**
  41366. * This flag can be used for type testing.
  41367. *
  41368. * @type {boolean}
  41369. * @readonly
  41370. * @default true
  41371. */
  41372. this.isSkeletonHelper = true;
  41373. this.type = 'SkeletonHelper';
  41374. /**
  41375. * The object being visualized.
  41376. *
  41377. * @type {Object3D}
  41378. */
  41379. this.root = object;
  41380. /**
  41381. * The list of bones that the helper visualizes.
  41382. *
  41383. * @type {Array<Bone>}
  41384. */
  41385. this.bones = bones;
  41386. this.matrix = object.matrixWorld;
  41387. this.matrixAutoUpdate = false;
  41388. // colors
  41389. const color1 = new Color( 0x0000ff );
  41390. const color2 = new Color( 0x00ff00 );
  41391. this.setColors( color1, color2 );
  41392. }
  41393. updateMatrixWorld( force ) {
  41394. const bones = this.bones;
  41395. const geometry = this.geometry;
  41396. const position = geometry.getAttribute( 'position' );
  41397. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41398. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41399. const bone = bones[ i ];
  41400. if ( bone.parent && bone.parent.isBone ) {
  41401. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41402. _vector$2.setFromMatrixPosition( _boneMatrix );
  41403. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41404. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41405. _vector$2.setFromMatrixPosition( _boneMatrix );
  41406. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41407. j += 2;
  41408. }
  41409. }
  41410. geometry.getAttribute( 'position' ).needsUpdate = true;
  41411. super.updateMatrixWorld( force );
  41412. }
  41413. /**
  41414. * Defines the colors of the helper.
  41415. *
  41416. * @param {Color} color1 - The first line color for each bone.
  41417. * @param {Color} color2 - The second line color for each bone.
  41418. * @return {SkeletonHelper} A reference to this helper.
  41419. */
  41420. setColors( color1, color2 ) {
  41421. const geometry = this.geometry;
  41422. const colorAttribute = geometry.getAttribute( 'color' );
  41423. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41424. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41425. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41426. }
  41427. colorAttribute.needsUpdate = true;
  41428. return this;
  41429. }
  41430. /**
  41431. * Frees the GPU-related resources allocated by this instance. Call this
  41432. * method whenever this instance is no longer used in your app.
  41433. */
  41434. dispose() {
  41435. this.geometry.dispose();
  41436. this.material.dispose();
  41437. }
  41438. }
  41439. function getBoneList( object ) {
  41440. const boneList = [];
  41441. if ( object.isBone === true ) {
  41442. boneList.push( object );
  41443. }
  41444. for ( let i = 0; i < object.children.length; i ++ ) {
  41445. boneList.push( ...getBoneList( object.children[ i ] ) );
  41446. }
  41447. return boneList;
  41448. }
  41449. /**
  41450. * This displays a helper object consisting of a spherical mesh for
  41451. * visualizing an instance of {@link PointLight}.
  41452. *
  41453. * ```js
  41454. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41455. * pointLight.position.set( 10, 10, 10 );
  41456. * scene.add( pointLight );
  41457. *
  41458. * const sphereSize = 1;
  41459. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41460. * scene.add( pointLightHelper );
  41461. * ```
  41462. *
  41463. * @augments Mesh
  41464. */
  41465. class PointLightHelper extends Mesh {
  41466. /**
  41467. * Constructs a new point light helper.
  41468. *
  41469. * @param {PointLight} light - The light to be visualized.
  41470. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41471. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41472. * the color of the light.
  41473. */
  41474. constructor( light, sphereSize, color ) {
  41475. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41476. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41477. super( geometry, material );
  41478. /**
  41479. * The light being visualized.
  41480. *
  41481. * @type {PointLight}
  41482. */
  41483. this.light = light;
  41484. /**
  41485. * The color parameter passed in the constructor.
  41486. * If not set, the helper will take the color of the light.
  41487. *
  41488. * @type {number|Color|string}
  41489. */
  41490. this.color = color;
  41491. this.type = 'PointLightHelper';
  41492. this.matrix = this.light.matrixWorld;
  41493. this.matrixAutoUpdate = false;
  41494. this.update();
  41495. }
  41496. /**
  41497. * Frees the GPU-related resources allocated by this instance. Call this
  41498. * method whenever this instance is no longer used in your app.
  41499. */
  41500. dispose() {
  41501. this.geometry.dispose();
  41502. this.material.dispose();
  41503. }
  41504. /**
  41505. * Updates the helper to match the position of the
  41506. * light being visualized.
  41507. */
  41508. update() {
  41509. this.light.updateWorldMatrix( true, false );
  41510. if ( this.color !== undefined ) {
  41511. this.material.color.set( this.color );
  41512. } else {
  41513. this.material.color.copy( this.light.color );
  41514. }
  41515. /*
  41516. const d = this.light.distance;
  41517. if ( d === 0.0 ) {
  41518. this.lightDistance.visible = false;
  41519. } else {
  41520. this.lightDistance.visible = true;
  41521. this.lightDistance.scale.set( d, d, d );
  41522. }
  41523. */
  41524. }
  41525. }
  41526. const _vector$1 = /*@__PURE__*/ new Vector3();
  41527. const _color1 = /*@__PURE__*/ new Color();
  41528. const _color2 = /*@__PURE__*/ new Color();
  41529. /**
  41530. * Creates a visual aid consisting of a spherical mesh for a
  41531. * given {@link HemisphereLight}.
  41532. *
  41533. * When the hemisphere light is transformed or its light properties are changed,
  41534. * it's necessary to call the `update()` method of the respective helper.
  41535. *
  41536. * ```js
  41537. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41538. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41539. * scene.add( helper );
  41540. * ```
  41541. *
  41542. * @augments Object3D
  41543. */
  41544. class HemisphereLightHelper extends Object3D {
  41545. /**
  41546. * Constructs a new hemisphere light helper.
  41547. *
  41548. * @param {HemisphereLight} light - The light to be visualized.
  41549. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41550. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41551. * the color of the light.
  41552. */
  41553. constructor( light, size, color ) {
  41554. super();
  41555. /**
  41556. * The light being visualized.
  41557. *
  41558. * @type {HemisphereLight}
  41559. */
  41560. this.light = light;
  41561. this.matrix = light.matrixWorld;
  41562. this.matrixAutoUpdate = false;
  41563. /**
  41564. * The color parameter passed in the constructor.
  41565. * If not set, the helper will take the color of the light.
  41566. *
  41567. * @type {number|Color|string}
  41568. */
  41569. this.color = color;
  41570. this.type = 'HemisphereLightHelper';
  41571. const geometry = new OctahedronGeometry( size );
  41572. geometry.rotateY( Math.PI * 0.5 );
  41573. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41574. if ( this.color === undefined ) this.material.vertexColors = true;
  41575. const position = geometry.getAttribute( 'position' );
  41576. const colors = new Float32Array( position.count * 3 );
  41577. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41578. this.add( new Mesh( geometry, this.material ) );
  41579. this.update();
  41580. }
  41581. /**
  41582. * Frees the GPU-related resources allocated by this instance. Call this
  41583. * method whenever this instance is no longer used in your app.
  41584. */
  41585. dispose() {
  41586. this.children[ 0 ].geometry.dispose();
  41587. this.children[ 0 ].material.dispose();
  41588. }
  41589. /**
  41590. * Updates the helper to match the position and direction of the
  41591. * light being visualized.
  41592. */
  41593. update() {
  41594. const mesh = this.children[ 0 ];
  41595. if ( this.color !== undefined ) {
  41596. this.material.color.set( this.color );
  41597. } else {
  41598. const colors = mesh.geometry.getAttribute( 'color' );
  41599. _color1.copy( this.light.color );
  41600. _color2.copy( this.light.groundColor );
  41601. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41602. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41603. colors.setXYZ( i, color.r, color.g, color.b );
  41604. }
  41605. colors.needsUpdate = true;
  41606. }
  41607. this.light.updateWorldMatrix( true, false );
  41608. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41609. }
  41610. }
  41611. /**
  41612. * The helper is an object to define grids. Grids are two-dimensional
  41613. * arrays of lines.
  41614. *
  41615. * ```js
  41616. * const size = 10;
  41617. * const divisions = 10;
  41618. *
  41619. * const gridHelper = new THREE.GridHelper( size, divisions );
  41620. * scene.add( gridHelper );
  41621. * ```
  41622. *
  41623. * @augments LineSegments
  41624. */
  41625. class GridHelper extends LineSegments {
  41626. /**
  41627. * Constructs a new grid helper.
  41628. *
  41629. * @param {number} [size=10] - The size of the grid.
  41630. * @param {number} [divisions=10] - The number of divisions across the grid.
  41631. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41632. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41633. */
  41634. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41635. color1 = new Color( color1 );
  41636. color2 = new Color( color2 );
  41637. const center = divisions / 2;
  41638. const step = size / divisions;
  41639. const halfSize = size / 2;
  41640. const vertices = [], colors = [];
  41641. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41642. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41643. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41644. const color = i === center ? color1 : color2;
  41645. color.toArray( colors, j ); j += 3;
  41646. color.toArray( colors, j ); j += 3;
  41647. color.toArray( colors, j ); j += 3;
  41648. color.toArray( colors, j ); j += 3;
  41649. }
  41650. const geometry = new BufferGeometry();
  41651. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41652. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41653. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41654. super( geometry, material );
  41655. this.type = 'GridHelper';
  41656. }
  41657. /**
  41658. * Frees the GPU-related resources allocated by this instance. Call this
  41659. * method whenever this instance is no longer used in your app.
  41660. */
  41661. dispose() {
  41662. this.geometry.dispose();
  41663. this.material.dispose();
  41664. }
  41665. }
  41666. /**
  41667. * This helper is an object to define polar grids. Grids are
  41668. * two-dimensional arrays of lines.
  41669. *
  41670. * ```js
  41671. * const radius = 10;
  41672. * const sectors = 16;
  41673. * const rings = 8;
  41674. * const divisions = 64;
  41675. *
  41676. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41677. * scene.add( helper );
  41678. * ```
  41679. *
  41680. * @augments LineSegments
  41681. */
  41682. class PolarGridHelper extends LineSegments {
  41683. /**
  41684. * Constructs a new polar grid helper.
  41685. *
  41686. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41687. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41688. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41689. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41690. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41691. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41692. */
  41693. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41694. color1 = new Color( color1 );
  41695. color2 = new Color( color2 );
  41696. const vertices = [];
  41697. const colors = [];
  41698. // create the sectors
  41699. if ( sectors > 1 ) {
  41700. for ( let i = 0; i < sectors; i ++ ) {
  41701. const v = ( i / sectors ) * ( Math.PI * 2 );
  41702. const x = Math.sin( v ) * radius;
  41703. const z = Math.cos( v ) * radius;
  41704. vertices.push( 0, 0, 0 );
  41705. vertices.push( x, 0, z );
  41706. const color = ( i & 1 ) ? color1 : color2;
  41707. colors.push( color.r, color.g, color.b );
  41708. colors.push( color.r, color.g, color.b );
  41709. }
  41710. }
  41711. // create the rings
  41712. for ( let i = 0; i < rings; i ++ ) {
  41713. const color = ( i & 1 ) ? color1 : color2;
  41714. const r = radius - ( radius / rings * i );
  41715. for ( let j = 0; j < divisions; j ++ ) {
  41716. // first vertex
  41717. let v = ( j / divisions ) * ( Math.PI * 2 );
  41718. let x = Math.sin( v ) * r;
  41719. let z = Math.cos( v ) * r;
  41720. vertices.push( x, 0, z );
  41721. colors.push( color.r, color.g, color.b );
  41722. // second vertex
  41723. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41724. x = Math.sin( v ) * r;
  41725. z = Math.cos( v ) * r;
  41726. vertices.push( x, 0, z );
  41727. colors.push( color.r, color.g, color.b );
  41728. }
  41729. }
  41730. const geometry = new BufferGeometry();
  41731. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41732. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41733. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41734. super( geometry, material );
  41735. this.type = 'PolarGridHelper';
  41736. }
  41737. /**
  41738. * Frees the GPU-related resources allocated by this instance. Call this
  41739. * method whenever this instance is no longer used in your app.
  41740. */
  41741. dispose() {
  41742. this.geometry.dispose();
  41743. this.material.dispose();
  41744. }
  41745. }
  41746. const _v1 = /*@__PURE__*/ new Vector3();
  41747. const _v2 = /*@__PURE__*/ new Vector3();
  41748. const _v3 = /*@__PURE__*/ new Vector3();
  41749. /**
  41750. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41751. * effect on the scene. This consists of a plane and a line representing the
  41752. * light's position and direction.
  41753. *
  41754. * When the directional light or its target are transformed or light properties
  41755. * are changed, it's necessary to call the `update()` method of the respective helper.
  41756. *
  41757. * ```js
  41758. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41759. * scene.add( light );
  41760. *
  41761. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41762. * scene.add( helper );
  41763. * ```
  41764. *
  41765. * @augments Object3D
  41766. */
  41767. class DirectionalLightHelper extends Object3D {
  41768. /**
  41769. * Constructs a new directional light helper.
  41770. *
  41771. * @param {DirectionalLight} light - The light to be visualized.
  41772. * @param {number} [size=1] - The dimensions of the plane.
  41773. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41774. * the color of the light.
  41775. */
  41776. constructor( light, size, color ) {
  41777. super();
  41778. /**
  41779. * The light being visualized.
  41780. *
  41781. * @type {DirectionalLight}
  41782. */
  41783. this.light = light;
  41784. this.matrix = light.matrixWorld;
  41785. this.matrixAutoUpdate = false;
  41786. /**
  41787. * The color parameter passed in the constructor.
  41788. * If not set, the helper will take the color of the light.
  41789. *
  41790. * @type {number|Color|string}
  41791. */
  41792. this.color = color;
  41793. this.type = 'DirectionalLightHelper';
  41794. if ( size === undefined ) size = 1;
  41795. let geometry = new BufferGeometry();
  41796. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41797. - size, size, 0,
  41798. size, size, 0,
  41799. size, - size, 0,
  41800. - size, - size, 0,
  41801. - size, size, 0
  41802. ], 3 ) );
  41803. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41804. /**
  41805. * Contains the line showing the location of the directional light.
  41806. *
  41807. * @type {Line}
  41808. */
  41809. this.lightPlane = new Line( geometry, material );
  41810. this.add( this.lightPlane );
  41811. geometry = new BufferGeometry();
  41812. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41813. /**
  41814. * Represents the target line of the directional light.
  41815. *
  41816. * @type {Line}
  41817. */
  41818. this.targetLine = new Line( geometry, material );
  41819. this.add( this.targetLine );
  41820. this.update();
  41821. }
  41822. /**
  41823. * Frees the GPU-related resources allocated by this instance. Call this
  41824. * method whenever this instance is no longer used in your app.
  41825. */
  41826. dispose() {
  41827. this.lightPlane.geometry.dispose();
  41828. this.lightPlane.material.dispose();
  41829. this.targetLine.geometry.dispose();
  41830. this.targetLine.material.dispose();
  41831. }
  41832. /**
  41833. * Updates the helper to match the position and direction of the
  41834. * light being visualized.
  41835. */
  41836. update() {
  41837. this.light.updateWorldMatrix( true, false );
  41838. this.light.target.updateWorldMatrix( true, false );
  41839. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41840. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41841. _v3.subVectors( _v2, _v1 );
  41842. this.lightPlane.lookAt( _v2 );
  41843. if ( this.color !== undefined ) {
  41844. this.lightPlane.material.color.set( this.color );
  41845. this.targetLine.material.color.set( this.color );
  41846. } else {
  41847. this.lightPlane.material.color.copy( this.light.color );
  41848. this.targetLine.material.color.copy( this.light.color );
  41849. }
  41850. this.targetLine.lookAt( _v2 );
  41851. this.targetLine.scale.z = _v3.length();
  41852. }
  41853. }
  41854. const _vector = /*@__PURE__*/ new Vector3();
  41855. const _camera = /*@__PURE__*/ new Camera();
  41856. /**
  41857. * This helps with visualizing what a camera contains in its frustum. It
  41858. * visualizes the frustum of a camera using a line segments.
  41859. *
  41860. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  41861. *
  41862. * `CameraHelper` must be a child of the scene.
  41863. *
  41864. * When the camera is transformed or its projection matrix is changed, it's necessary
  41865. * to call the `update()` method of the respective helper.
  41866. *
  41867. * ```js
  41868. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41869. * const helper = new THREE.CameraHelper( camera );
  41870. * scene.add( helper );
  41871. * ```
  41872. *
  41873. * @augments LineSegments
  41874. */
  41875. class CameraHelper extends LineSegments {
  41876. /**
  41877. * Constructs a new arrow helper.
  41878. *
  41879. * @param {Camera} camera - The camera to visualize.
  41880. */
  41881. constructor( camera ) {
  41882. const geometry = new BufferGeometry();
  41883. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41884. const vertices = [];
  41885. const colors = [];
  41886. const pointMap = {};
  41887. // near
  41888. addLine( 'n1', 'n2' );
  41889. addLine( 'n2', 'n4' );
  41890. addLine( 'n4', 'n3' );
  41891. addLine( 'n3', 'n1' );
  41892. // far
  41893. addLine( 'f1', 'f2' );
  41894. addLine( 'f2', 'f4' );
  41895. addLine( 'f4', 'f3' );
  41896. addLine( 'f3', 'f1' );
  41897. // sides
  41898. addLine( 'n1', 'f1' );
  41899. addLine( 'n2', 'f2' );
  41900. addLine( 'n3', 'f3' );
  41901. addLine( 'n4', 'f4' );
  41902. // cone
  41903. addLine( 'p', 'n1' );
  41904. addLine( 'p', 'n2' );
  41905. addLine( 'p', 'n3' );
  41906. addLine( 'p', 'n4' );
  41907. // up
  41908. addLine( 'u1', 'u2' );
  41909. addLine( 'u2', 'u3' );
  41910. addLine( 'u3', 'u1' );
  41911. // target
  41912. addLine( 'c', 't' );
  41913. addLine( 'p', 'c' );
  41914. // cross
  41915. addLine( 'cn1', 'cn2' );
  41916. addLine( 'cn3', 'cn4' );
  41917. addLine( 'cf1', 'cf2' );
  41918. addLine( 'cf3', 'cf4' );
  41919. function addLine( a, b ) {
  41920. addPoint( a );
  41921. addPoint( b );
  41922. }
  41923. function addPoint( id ) {
  41924. vertices.push( 0, 0, 0 );
  41925. colors.push( 0, 0, 0 );
  41926. if ( pointMap[ id ] === undefined ) {
  41927. pointMap[ id ] = [];
  41928. }
  41929. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41930. }
  41931. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41932. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41933. super( geometry, material );
  41934. this.type = 'CameraHelper';
  41935. /**
  41936. * The camera being visualized.
  41937. *
  41938. * @type {Camera}
  41939. */
  41940. this.camera = camera;
  41941. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41942. this.matrix = camera.matrixWorld;
  41943. this.matrixAutoUpdate = false;
  41944. /**
  41945. * This contains the points used to visualize the camera.
  41946. *
  41947. * @type {Object<string,Array<number>>}
  41948. */
  41949. this.pointMap = pointMap;
  41950. this.update();
  41951. // colors
  41952. const colorFrustum = new Color( 0xffaa00 );
  41953. const colorCone = new Color( 0xff0000 );
  41954. const colorUp = new Color( 0x00aaff );
  41955. const colorTarget = new Color( 0xffffff );
  41956. const colorCross = new Color( 0x333333 );
  41957. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41958. }
  41959. /**
  41960. * Defines the colors of the helper.
  41961. *
  41962. * @param {Color} frustum - The frustum line color.
  41963. * @param {Color} cone - The cone line color.
  41964. * @param {Color} up - The up line color.
  41965. * @param {Color} target - The target line color.
  41966. * @param {Color} cross - The cross line color.
  41967. * @return {CameraHelper} A reference to this helper.
  41968. */
  41969. setColors( frustum, cone, up, target, cross ) {
  41970. const geometry = this.geometry;
  41971. const colorAttribute = geometry.getAttribute( 'color' );
  41972. // near
  41973. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41974. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41975. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41976. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41977. // far
  41978. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41979. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41980. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41981. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41982. // sides
  41983. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41984. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41985. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41986. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41987. // cone
  41988. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41989. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41990. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41991. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41992. // up
  41993. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41994. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41995. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41996. // target
  41997. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41998. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41999. // cross
  42000. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  42001. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  42002. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  42003. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  42004. colorAttribute.needsUpdate = true;
  42005. return this;
  42006. }
  42007. /**
  42008. * Updates the helper based on the projection matrix of the camera.
  42009. */
  42010. update() {
  42011. const geometry = this.geometry;
  42012. const pointMap = this.pointMap;
  42013. const w = 1, h = 1;
  42014. let nearZ, farZ;
  42015. // we need just camera projection matrix inverse
  42016. // world matrix must be identity
  42017. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  42018. // Adjust z values based on coordinate system
  42019. if ( this.camera.reversedDepth === true ) {
  42020. nearZ = 1;
  42021. farZ = 0;
  42022. } else {
  42023. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  42024. nearZ = -1;
  42025. farZ = 1;
  42026. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  42027. nearZ = 0;
  42028. farZ = 1;
  42029. } else {
  42030. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  42031. }
  42032. }
  42033. // center / target
  42034. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  42035. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  42036. // near
  42037. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  42038. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  42039. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  42040. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  42041. // far
  42042. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  42043. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  42044. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  42045. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  42046. // up
  42047. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  42048. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  42049. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  42050. // cross
  42051. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  42052. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  42053. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  42054. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  42055. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  42056. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  42057. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  42058. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  42059. geometry.getAttribute( 'position' ).needsUpdate = true;
  42060. }
  42061. /**
  42062. * Frees the GPU-related resources allocated by this instance. Call this
  42063. * method whenever this instance is no longer used in your app.
  42064. */
  42065. dispose() {
  42066. this.geometry.dispose();
  42067. this.material.dispose();
  42068. }
  42069. }
  42070. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  42071. _vector.set( x, y, z ).unproject( camera );
  42072. const points = pointMap[ point ];
  42073. if ( points !== undefined ) {
  42074. const position = geometry.getAttribute( 'position' );
  42075. for ( let i = 0, l = points.length; i < l; i ++ ) {
  42076. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  42077. }
  42078. }
  42079. }
  42080. const _box = /*@__PURE__*/ new Box3();
  42081. /**
  42082. * Helper object to graphically show the world-axis-aligned bounding box
  42083. * around an object. The actual bounding box is handled with {@link Box3},
  42084. * this is just a visual helper for debugging. It can be automatically
  42085. * resized with {@link BoxHelper#update} when the object it's created from
  42086. * is transformed. Note that the object must have a geometry for this to work,
  42087. * so it won't work with sprites.
  42088. *
  42089. * ```js
  42090. * const sphere = new THREE.SphereGeometry();
  42091. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  42092. * const box = new THREE.BoxHelper( object, 0xffff00 );
  42093. * scene.add( box );
  42094. * ```
  42095. *
  42096. * @augments LineSegments
  42097. */
  42098. class BoxHelper extends LineSegments {
  42099. /**
  42100. * Constructs a new box helper.
  42101. *
  42102. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  42103. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42104. */
  42105. constructor( object, color = 0xffff00 ) {
  42106. 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 ] );
  42107. const positions = new Float32Array( 8 * 3 );
  42108. const geometry = new BufferGeometry();
  42109. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42110. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  42111. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42112. /**
  42113. * The 3D object being visualized.
  42114. *
  42115. * @type {Object3D}
  42116. */
  42117. this.object = object;
  42118. this.type = 'BoxHelper';
  42119. this.matrixAutoUpdate = false;
  42120. this.update();
  42121. }
  42122. /**
  42123. * Updates the helper's geometry to match the dimensions of the object,
  42124. * including any children.
  42125. */
  42126. update() {
  42127. if ( this.object !== undefined ) {
  42128. _box.setFromObject( this.object );
  42129. }
  42130. if ( _box.isEmpty() ) return;
  42131. const min = _box.min;
  42132. const max = _box.max;
  42133. /*
  42134. 5____4
  42135. 1/___0/|
  42136. | 6__|_7
  42137. 2/___3/
  42138. 0: max.x, max.y, max.z
  42139. 1: min.x, max.y, max.z
  42140. 2: min.x, min.y, max.z
  42141. 3: max.x, min.y, max.z
  42142. 4: max.x, max.y, min.z
  42143. 5: min.x, max.y, min.z
  42144. 6: min.x, min.y, min.z
  42145. 7: max.x, min.y, min.z
  42146. */
  42147. const position = this.geometry.attributes.position;
  42148. const array = position.array;
  42149. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  42150. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  42151. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  42152. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  42153. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  42154. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  42155. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  42156. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  42157. position.needsUpdate = true;
  42158. this.geometry.computeBoundingSphere();
  42159. }
  42160. /**
  42161. * Updates the wireframe box for the passed object.
  42162. *
  42163. * @param {Object3D} object - The 3D object to create the helper for.
  42164. * @return {BoxHelper} A reference to this instance.
  42165. */
  42166. setFromObject( object ) {
  42167. this.object = object;
  42168. this.update();
  42169. return this;
  42170. }
  42171. copy( source, recursive ) {
  42172. super.copy( source, recursive );
  42173. this.object = source.object;
  42174. return this;
  42175. }
  42176. /**
  42177. * Frees the GPU-related resources allocated by this instance. Call this
  42178. * method whenever this instance is no longer used in your app.
  42179. */
  42180. dispose() {
  42181. this.geometry.dispose();
  42182. this.material.dispose();
  42183. }
  42184. }
  42185. /**
  42186. * A helper object to visualize an instance of {@link Box3}.
  42187. *
  42188. * ```js
  42189. * const box = new THREE.Box3();
  42190. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  42191. *
  42192. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  42193. * scene.add( helper )
  42194. * ```
  42195. *
  42196. * @augments LineSegments
  42197. */
  42198. class Box3Helper extends LineSegments {
  42199. /**
  42200. * Constructs a new box3 helper.
  42201. *
  42202. * @param {Box3} box - The box to visualize.
  42203. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42204. */
  42205. constructor( box, color = 0xffff00 ) {
  42206. 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 ] );
  42207. 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 ];
  42208. const geometry = new BufferGeometry();
  42209. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42210. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42211. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42212. /**
  42213. * The box being visualized.
  42214. *
  42215. * @type {Box3}
  42216. */
  42217. this.box = box;
  42218. this.type = 'Box3Helper';
  42219. this.geometry.computeBoundingSphere();
  42220. }
  42221. updateMatrixWorld( force ) {
  42222. const box = this.box;
  42223. if ( box.isEmpty() ) return;
  42224. box.getCenter( this.position );
  42225. box.getSize( this.scale );
  42226. this.scale.multiplyScalar( 0.5 );
  42227. super.updateMatrixWorld( force );
  42228. }
  42229. /**
  42230. * Frees the GPU-related resources allocated by this instance. Call this
  42231. * method whenever this instance is no longer used in your app.
  42232. */
  42233. dispose() {
  42234. this.geometry.dispose();
  42235. this.material.dispose();
  42236. }
  42237. }
  42238. /**
  42239. * A helper object to visualize an instance of {@link Plane}.
  42240. *
  42241. * ```js
  42242. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  42243. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  42244. * scene.add( helper );
  42245. * ```
  42246. *
  42247. * @augments Line
  42248. */
  42249. class PlaneHelper extends Line {
  42250. /**
  42251. * Constructs a new plane helper.
  42252. *
  42253. * @param {Plane} plane - The plane to be visualized.
  42254. * @param {number} [size=1] - The side length of plane helper.
  42255. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  42256. */
  42257. constructor( plane, size = 1, hex = 0xffff00 ) {
  42258. const color = hex;
  42259. 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 ];
  42260. const geometry = new BufferGeometry();
  42261. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42262. geometry.computeBoundingSphere();
  42263. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42264. this.type = 'PlaneHelper';
  42265. /**
  42266. * The plane being visualized.
  42267. *
  42268. * @type {Plane}
  42269. */
  42270. this.plane = plane;
  42271. /**
  42272. * The side length of plane helper.
  42273. *
  42274. * @type {number}
  42275. * @default 1
  42276. */
  42277. this.size = size;
  42278. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  42279. const geometry2 = new BufferGeometry();
  42280. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42281. geometry2.computeBoundingSphere();
  42282. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42283. }
  42284. updateMatrixWorld( force ) {
  42285. this.position.set( 0, 0, 0 );
  42286. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42287. this.lookAt( this.plane.normal );
  42288. this.translateZ( - this.plane.constant );
  42289. super.updateMatrixWorld( force );
  42290. }
  42291. /**
  42292. * Updates the helper to match the position and direction of the
  42293. * light being visualized.
  42294. */
  42295. dispose() {
  42296. this.geometry.dispose();
  42297. this.material.dispose();
  42298. this.children[ 0 ].geometry.dispose();
  42299. this.children[ 0 ].material.dispose();
  42300. }
  42301. }
  42302. const _axis = /*@__PURE__*/ new Vector3();
  42303. let _lineGeometry, _coneGeometry;
  42304. /**
  42305. * An 3D arrow object for visualizing directions.
  42306. *
  42307. * ```js
  42308. * const dir = new THREE.Vector3( 1, 2, 0 );
  42309. *
  42310. * //normalize the direction vector (convert to vector of length 1)
  42311. * dir.normalize();
  42312. *
  42313. * const origin = new THREE.Vector3( 0, 0, 0 );
  42314. * const length = 1;
  42315. * const hex = 0xffff00;
  42316. *
  42317. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42318. * scene.add( arrowHelper );
  42319. * ```
  42320. *
  42321. * @augments Object3D
  42322. */
  42323. class ArrowHelper extends Object3D {
  42324. /**
  42325. * Constructs a new arrow helper.
  42326. *
  42327. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42328. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42329. * @param {number} [length=1] - Length of the arrow in world units.
  42330. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42331. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42332. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42333. */
  42334. 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 ) {
  42335. super();
  42336. this.type = 'ArrowHelper';
  42337. if ( _lineGeometry === undefined ) {
  42338. _lineGeometry = new BufferGeometry();
  42339. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42340. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42341. _coneGeometry.translate( 0, -0.5, 0 );
  42342. }
  42343. this.position.copy( origin );
  42344. /**
  42345. * The line part of the arrow helper.
  42346. *
  42347. * @type {Line}
  42348. */
  42349. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42350. this.line.matrixAutoUpdate = false;
  42351. this.add( this.line );
  42352. /**
  42353. * The cone part of the arrow helper.
  42354. *
  42355. * @type {Mesh}
  42356. */
  42357. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42358. this.cone.matrixAutoUpdate = false;
  42359. this.add( this.cone );
  42360. this.setDirection( dir );
  42361. this.setLength( length, headLength, headWidth );
  42362. }
  42363. /**
  42364. * Sets the direction of the helper.
  42365. *
  42366. * @param {Vector3} dir - The normalized direction vector.
  42367. */
  42368. setDirection( dir ) {
  42369. // dir is assumed to be normalized
  42370. if ( dir.y > 0.99999 ) {
  42371. this.quaternion.set( 0, 0, 0, 1 );
  42372. } else if ( dir.y < -0.99999 ) {
  42373. this.quaternion.set( 1, 0, 0, 0 );
  42374. } else {
  42375. _axis.set( dir.z, 0, - dir.x ).normalize();
  42376. const radians = Math.acos( dir.y );
  42377. this.quaternion.setFromAxisAngle( _axis, radians );
  42378. }
  42379. }
  42380. /**
  42381. * Sets the length of the helper.
  42382. *
  42383. * @param {number} length - Length of the arrow in world units.
  42384. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42385. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42386. */
  42387. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42388. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42389. this.line.updateMatrix();
  42390. this.cone.scale.set( headWidth, headLength, headWidth );
  42391. this.cone.position.y = length;
  42392. this.cone.updateMatrix();
  42393. }
  42394. /**
  42395. * Sets the color of the helper.
  42396. *
  42397. * @param {number|Color|string} color - The color to set.
  42398. */
  42399. setColor( color ) {
  42400. this.line.material.color.set( color );
  42401. this.cone.material.color.set( color );
  42402. }
  42403. copy( source ) {
  42404. super.copy( source, false );
  42405. this.line.copy( source.line );
  42406. this.cone.copy( source.cone );
  42407. return this;
  42408. }
  42409. /**
  42410. * Frees the GPU-related resources allocated by this instance. Call this
  42411. * method whenever this instance is no longer used in your app.
  42412. */
  42413. dispose() {
  42414. this.line.geometry.dispose();
  42415. this.line.material.dispose();
  42416. this.cone.geometry.dispose();
  42417. this.cone.material.dispose();
  42418. }
  42419. }
  42420. /**
  42421. * An axis object to visualize the 3 axes in a simple way.
  42422. * The X axis is red. The Y axis is green. The Z axis is blue.
  42423. *
  42424. * ```js
  42425. * const axesHelper = new THREE.AxesHelper( 5 );
  42426. * scene.add( axesHelper );
  42427. * ```
  42428. *
  42429. * @augments LineSegments
  42430. */
  42431. class AxesHelper extends LineSegments {
  42432. /**
  42433. * Constructs a new axes helper.
  42434. *
  42435. * @param {number} [size=1] - Size of the lines representing the axes.
  42436. */
  42437. constructor( size = 1 ) {
  42438. const vertices = [
  42439. 0, 0, 0, size, 0, 0,
  42440. 0, 0, 0, 0, size, 0,
  42441. 0, 0, 0, 0, 0, size
  42442. ];
  42443. const colors = [
  42444. 1, 0, 0, 1, 0.6, 0,
  42445. 0, 1, 0, 0.6, 1, 0,
  42446. 0, 0, 1, 0, 0.6, 1
  42447. ];
  42448. const geometry = new BufferGeometry();
  42449. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42450. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42451. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42452. super( geometry, material );
  42453. this.type = 'AxesHelper';
  42454. }
  42455. /**
  42456. * Defines the colors of the axes helper.
  42457. *
  42458. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42459. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42460. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42461. * @return {AxesHelper} A reference to this axes helper.
  42462. */
  42463. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42464. const color = new Color();
  42465. const array = this.geometry.attributes.color.array;
  42466. color.set( xAxisColor );
  42467. color.toArray( array, 0 );
  42468. color.toArray( array, 3 );
  42469. color.set( yAxisColor );
  42470. color.toArray( array, 6 );
  42471. color.toArray( array, 9 );
  42472. color.set( zAxisColor );
  42473. color.toArray( array, 12 );
  42474. color.toArray( array, 15 );
  42475. this.geometry.attributes.color.needsUpdate = true;
  42476. return this;
  42477. }
  42478. /**
  42479. * Frees the GPU-related resources allocated by this instance. Call this
  42480. * method whenever this instance is no longer used in your app.
  42481. */
  42482. dispose() {
  42483. this.geometry.dispose();
  42484. this.material.dispose();
  42485. }
  42486. }
  42487. /**
  42488. * This class is used to convert a series of paths to an array of
  42489. * shapes. It is specifically used in context of fonts and SVG.
  42490. */
  42491. class ShapePath {
  42492. /**
  42493. * Constructs a new shape path.
  42494. */
  42495. constructor() {
  42496. this.type = 'ShapePath';
  42497. /**
  42498. * The color of the shape.
  42499. *
  42500. * @type {Color}
  42501. */
  42502. this.color = new Color();
  42503. /**
  42504. * The paths that have been generated for this shape.
  42505. *
  42506. * @type {Array<Path>}
  42507. * @default null
  42508. */
  42509. this.subPaths = [];
  42510. /**
  42511. * The current path that is being generated.
  42512. *
  42513. * @type {?Path}
  42514. * @default null
  42515. */
  42516. this.currentPath = null;
  42517. }
  42518. /**
  42519. * Creates a new path and moves it current point to the given one.
  42520. *
  42521. * @param {number} x - The x coordinate.
  42522. * @param {number} y - The y coordinate.
  42523. * @return {ShapePath} A reference to this shape path.
  42524. */
  42525. moveTo( x, y ) {
  42526. this.currentPath = new Path();
  42527. this.subPaths.push( this.currentPath );
  42528. this.currentPath.moveTo( x, y );
  42529. return this;
  42530. }
  42531. /**
  42532. * Adds an instance of {@link LineCurve} to the path by connecting
  42533. * the current point with the given one.
  42534. *
  42535. * @param {number} x - The x coordinate of the end point.
  42536. * @param {number} y - The y coordinate of the end point.
  42537. * @return {ShapePath} A reference to this shape path.
  42538. */
  42539. lineTo( x, y ) {
  42540. this.currentPath.lineTo( x, y );
  42541. return this;
  42542. }
  42543. /**
  42544. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42545. * the current point with the given one.
  42546. *
  42547. * @param {number} aCPx - The x coordinate of the control point.
  42548. * @param {number} aCPy - The y coordinate of the control point.
  42549. * @param {number} aX - The x coordinate of the end point.
  42550. * @param {number} aY - The y coordinate of the end point.
  42551. * @return {ShapePath} A reference to this shape path.
  42552. */
  42553. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42554. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42555. return this;
  42556. }
  42557. /**
  42558. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42559. * the current point with the given one.
  42560. *
  42561. * @param {number} aCP1x - The x coordinate of the first control point.
  42562. * @param {number} aCP1y - The y coordinate of the first control point.
  42563. * @param {number} aCP2x - The x coordinate of the second control point.
  42564. * @param {number} aCP2y - The y coordinate of the second control point.
  42565. * @param {number} aX - The x coordinate of the end point.
  42566. * @param {number} aY - The y coordinate of the end point.
  42567. * @return {ShapePath} A reference to this shape path.
  42568. */
  42569. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42570. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42571. return this;
  42572. }
  42573. /**
  42574. * Adds an instance of {@link SplineCurve} to the path by connecting
  42575. * the current point with the given list of points.
  42576. *
  42577. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42578. * @return {ShapePath} A reference to this shape path.
  42579. */
  42580. splineThru( pts ) {
  42581. this.currentPath.splineThru( pts );
  42582. return this;
  42583. }
  42584. /**
  42585. * Converts the paths into an array of shapes.
  42586. *
  42587. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42588. * If this flag is set to `true`, then those are flipped.
  42589. * @return {Array<Shape>} An array of shapes.
  42590. */
  42591. toShapes( isCCW ) {
  42592. function toShapesNoHoles( inSubpaths ) {
  42593. const shapes = [];
  42594. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42595. const tmpPath = inSubpaths[ i ];
  42596. const tmpShape = new Shape();
  42597. tmpShape.curves = tmpPath.curves;
  42598. shapes.push( tmpShape );
  42599. }
  42600. return shapes;
  42601. }
  42602. function isPointInsidePolygon( inPt, inPolygon ) {
  42603. const polyLen = inPolygon.length;
  42604. // inPt on polygon contour => immediate success or
  42605. // toggling of inside/outside at every single! intersection point of an edge
  42606. // with the horizontal line through inPt, left of inPt
  42607. // not counting lowerY endpoints of edges and whole edges on that line
  42608. let inside = false;
  42609. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42610. let edgeLowPt = inPolygon[ p ];
  42611. let edgeHighPt = inPolygon[ q ];
  42612. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42613. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42614. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42615. // not parallel
  42616. if ( edgeDy < 0 ) {
  42617. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42618. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42619. }
  42620. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42621. if ( inPt.y === edgeLowPt.y ) {
  42622. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42623. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42624. } else {
  42625. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42626. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42627. if ( perpEdge < 0 ) continue;
  42628. inside = ! inside; // true intersection left of inPt
  42629. }
  42630. } else {
  42631. // parallel or collinear
  42632. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42633. // edge lies on the same horizontal line as inPt
  42634. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42635. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42636. // continue;
  42637. }
  42638. }
  42639. return inside;
  42640. }
  42641. const isClockWise = ShapeUtils.isClockWise;
  42642. const subPaths = this.subPaths;
  42643. if ( subPaths.length === 0 ) return [];
  42644. let solid, tmpPath, tmpShape;
  42645. const shapes = [];
  42646. if ( subPaths.length === 1 ) {
  42647. tmpPath = subPaths[ 0 ];
  42648. tmpShape = new Shape();
  42649. tmpShape.curves = tmpPath.curves;
  42650. shapes.push( tmpShape );
  42651. return shapes;
  42652. }
  42653. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42654. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42655. // log("Holes first", holesFirst);
  42656. const betterShapeHoles = [];
  42657. const newShapes = [];
  42658. let newShapeHoles = [];
  42659. let mainIdx = 0;
  42660. let tmpPoints;
  42661. newShapes[ mainIdx ] = undefined;
  42662. newShapeHoles[ mainIdx ] = [];
  42663. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42664. tmpPath = subPaths[ i ];
  42665. tmpPoints = tmpPath.getPoints();
  42666. solid = isClockWise( tmpPoints );
  42667. solid = isCCW ? ! solid : solid;
  42668. if ( solid ) {
  42669. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42670. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42671. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42672. if ( holesFirst ) mainIdx ++;
  42673. newShapeHoles[ mainIdx ] = [];
  42674. //log('cw', i);
  42675. } else {
  42676. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42677. //log('ccw', i);
  42678. }
  42679. }
  42680. // only Holes? -> probably all Shapes with wrong orientation
  42681. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42682. if ( newShapes.length > 1 ) {
  42683. let ambiguous = false;
  42684. let toChange = 0;
  42685. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42686. betterShapeHoles[ sIdx ] = [];
  42687. }
  42688. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42689. const sho = newShapeHoles[ sIdx ];
  42690. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42691. const ho = sho[ hIdx ];
  42692. let hole_unassigned = true;
  42693. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42694. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42695. if ( sIdx !== s2Idx ) toChange ++;
  42696. if ( hole_unassigned ) {
  42697. hole_unassigned = false;
  42698. betterShapeHoles[ s2Idx ].push( ho );
  42699. } else {
  42700. ambiguous = true;
  42701. }
  42702. }
  42703. }
  42704. if ( hole_unassigned ) {
  42705. betterShapeHoles[ sIdx ].push( ho );
  42706. }
  42707. }
  42708. }
  42709. if ( toChange > 0 && ambiguous === false ) {
  42710. newShapeHoles = betterShapeHoles;
  42711. }
  42712. }
  42713. let tmpHoles;
  42714. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42715. tmpShape = newShapes[ i ].s;
  42716. shapes.push( tmpShape );
  42717. tmpHoles = newShapeHoles[ i ];
  42718. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42719. tmpShape.holes.push( tmpHoles[ j ].h );
  42720. }
  42721. }
  42722. //log("shape", shapes);
  42723. return shapes;
  42724. }
  42725. }
  42726. /**
  42727. * Abstract base class for controls.
  42728. *
  42729. * @abstract
  42730. * @augments EventDispatcher
  42731. */
  42732. class Controls extends EventDispatcher {
  42733. /**
  42734. * Constructs a new controls instance.
  42735. *
  42736. * @param {Object3D} object - The object that is managed by the controls.
  42737. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42738. */
  42739. constructor( object, domElement = null ) {
  42740. super();
  42741. /**
  42742. * The object that is managed by the controls.
  42743. *
  42744. * @type {Object3D}
  42745. */
  42746. this.object = object;
  42747. /**
  42748. * The HTML element used for event listeners.
  42749. *
  42750. * @type {?HTMLElement}
  42751. * @default null
  42752. */
  42753. this.domElement = domElement;
  42754. /**
  42755. * Whether the controls responds to user input or not.
  42756. *
  42757. * @type {boolean}
  42758. * @default true
  42759. */
  42760. this.enabled = true;
  42761. /**
  42762. * The internal state of the controls.
  42763. *
  42764. * @type {number}
  42765. * @default -1
  42766. */
  42767. this.state = -1;
  42768. /**
  42769. * This object defines the keyboard input of the controls.
  42770. *
  42771. * @type {Object}
  42772. */
  42773. this.keys = {};
  42774. /**
  42775. * This object defines what type of actions are assigned to the available mouse buttons.
  42776. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42777. *
  42778. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42779. */
  42780. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42781. /**
  42782. * This object defines what type of actions are assigned to what kind of touch interaction.
  42783. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42784. *
  42785. * @type {{ONE: ?number, TWO: ?number}}
  42786. */
  42787. this.touches = { ONE: null, TWO: null };
  42788. }
  42789. /**
  42790. * Connects the controls to the DOM. This method has so called "side effects" since
  42791. * it adds the module's event listeners to the DOM.
  42792. *
  42793. * @param {HTMLElement} element - The DOM element to connect to.
  42794. */
  42795. connect( element ) {
  42796. if ( element === undefined ) {
  42797. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42798. return;
  42799. }
  42800. if ( this.domElement !== null ) this.disconnect();
  42801. this.domElement = element;
  42802. }
  42803. /**
  42804. * Disconnects the controls from the DOM.
  42805. */
  42806. disconnect() {}
  42807. /**
  42808. * Call this method if you no longer want use to the controls. It frees all internal
  42809. * resources and removes all event listeners.
  42810. */
  42811. dispose() {}
  42812. /**
  42813. * Controls should implement this method if they have to update their internal state
  42814. * per simulation step.
  42815. *
  42816. * @param {number} [delta] - The time delta in seconds.
  42817. */
  42818. update( /* delta */ ) {}
  42819. }
  42820. /**
  42821. * Scales the texture as large as possible within its surface without cropping
  42822. * or stretching the texture. The method preserves the original aspect ratio of
  42823. * the texture. Akin to CSS `object-fit: contain`
  42824. *
  42825. * @param {Texture} texture - The texture.
  42826. * @param {number} aspect - The texture's aspect ratio.
  42827. * @return {Texture} The updated texture.
  42828. */
  42829. function contain( texture, aspect ) {
  42830. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42831. if ( imageAspect > aspect ) {
  42832. texture.repeat.x = 1;
  42833. texture.repeat.y = imageAspect / aspect;
  42834. texture.offset.x = 0;
  42835. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42836. } else {
  42837. texture.repeat.x = aspect / imageAspect;
  42838. texture.repeat.y = 1;
  42839. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42840. texture.offset.y = 0;
  42841. }
  42842. return texture;
  42843. }
  42844. /**
  42845. * Scales the texture to the smallest possible size to fill the surface, leaving
  42846. * no empty space. The method preserves the original aspect ratio of the texture.
  42847. * Akin to CSS `object-fit: cover`.
  42848. *
  42849. * @param {Texture} texture - The texture.
  42850. * @param {number} aspect - The texture's aspect ratio.
  42851. * @return {Texture} The updated texture.
  42852. */
  42853. function cover( texture, aspect ) {
  42854. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42855. if ( imageAspect > aspect ) {
  42856. texture.repeat.x = aspect / imageAspect;
  42857. texture.repeat.y = 1;
  42858. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42859. texture.offset.y = 0;
  42860. } else {
  42861. texture.repeat.x = 1;
  42862. texture.repeat.y = imageAspect / aspect;
  42863. texture.offset.x = 0;
  42864. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42865. }
  42866. return texture;
  42867. }
  42868. /**
  42869. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42870. *
  42871. * @param {Texture} texture - The texture.
  42872. * @return {Texture} The updated texture.
  42873. */
  42874. function fill( texture ) {
  42875. texture.repeat.x = 1;
  42876. texture.repeat.y = 1;
  42877. texture.offset.x = 0;
  42878. texture.offset.y = 0;
  42879. return texture;
  42880. }
  42881. /**
  42882. * Determines how many bytes must be used to represent the texture.
  42883. *
  42884. * @param {number} width - The width of the texture.
  42885. * @param {number} height - The height of the texture.
  42886. * @param {number} format - The texture's format.
  42887. * @param {number} type - The texture's type.
  42888. * @return {number} The byte length.
  42889. */
  42890. function getByteLength( width, height, format, type ) {
  42891. const typeByteLength = getTextureTypeByteLength( type );
  42892. switch ( format ) {
  42893. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42894. case AlphaFormat:
  42895. return width * height;
  42896. case RedFormat:
  42897. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42898. case RedIntegerFormat:
  42899. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42900. case RGFormat:
  42901. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42902. case RGIntegerFormat:
  42903. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42904. case RGBFormat:
  42905. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42906. case RGBAFormat:
  42907. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42908. case RGBAIntegerFormat:
  42909. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42910. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42911. case RGB_S3TC_DXT1_Format:
  42912. case RGBA_S3TC_DXT1_Format:
  42913. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42914. case RGBA_S3TC_DXT3_Format:
  42915. case RGBA_S3TC_DXT5_Format:
  42916. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42917. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42918. case RGB_PVRTC_2BPPV1_Format:
  42919. case RGBA_PVRTC_2BPPV1_Format:
  42920. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42921. case RGB_PVRTC_4BPPV1_Format:
  42922. case RGBA_PVRTC_4BPPV1_Format:
  42923. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42924. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42925. case RGB_ETC1_Format:
  42926. case RGB_ETC2_Format:
  42927. case R11_EAC_Format:
  42928. case SIGNED_R11_EAC_Format:
  42929. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42930. case RGBA_ETC2_EAC_Format:
  42931. case RG11_EAC_Format:
  42932. case SIGNED_RG11_EAC_Format:
  42933. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42934. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42935. case RGBA_ASTC_4x4_Format:
  42936. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42937. case RGBA_ASTC_5x4_Format:
  42938. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42939. case RGBA_ASTC_5x5_Format:
  42940. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42941. case RGBA_ASTC_6x5_Format:
  42942. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42943. case RGBA_ASTC_6x6_Format:
  42944. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42945. case RGBA_ASTC_8x5_Format:
  42946. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42947. case RGBA_ASTC_8x6_Format:
  42948. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42949. case RGBA_ASTC_8x8_Format:
  42950. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42951. case RGBA_ASTC_10x5_Format:
  42952. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42953. case RGBA_ASTC_10x6_Format:
  42954. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42955. case RGBA_ASTC_10x8_Format:
  42956. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42957. case RGBA_ASTC_10x10_Format:
  42958. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42959. case RGBA_ASTC_12x10_Format:
  42960. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42961. case RGBA_ASTC_12x12_Format:
  42962. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42963. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42964. case RGBA_BPTC_Format:
  42965. case RGB_BPTC_SIGNED_Format:
  42966. case RGB_BPTC_UNSIGNED_Format:
  42967. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42968. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42969. case RED_RGTC1_Format:
  42970. case SIGNED_RED_RGTC1_Format:
  42971. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42972. case RED_GREEN_RGTC2_Format:
  42973. case SIGNED_RED_GREEN_RGTC2_Format:
  42974. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42975. }
  42976. throw new Error(
  42977. `Unable to determine texture byte length for ${format} format.`,
  42978. );
  42979. }
  42980. function getTextureTypeByteLength( type ) {
  42981. switch ( type ) {
  42982. case UnsignedByteType:
  42983. case ByteType:
  42984. return { byteLength: 1, components: 1 };
  42985. case UnsignedShortType:
  42986. case ShortType:
  42987. case HalfFloatType:
  42988. return { byteLength: 2, components: 1 };
  42989. case UnsignedShort4444Type:
  42990. case UnsignedShort5551Type:
  42991. return { byteLength: 2, components: 4 };
  42992. case UnsignedIntType:
  42993. case IntType:
  42994. case FloatType:
  42995. return { byteLength: 4, components: 1 };
  42996. case UnsignedInt5999Type:
  42997. case UnsignedInt101111Type:
  42998. return { byteLength: 4, components: 3 };
  42999. }
  43000. throw new Error( `Unknown texture type ${type}.` );
  43001. }
  43002. /**
  43003. * A class containing utility functions for textures.
  43004. *
  43005. * @hideconstructor
  43006. */
  43007. class TextureUtils {
  43008. /**
  43009. * Scales the texture as large as possible within its surface without cropping
  43010. * or stretching the texture. The method preserves the original aspect ratio of
  43011. * the texture. Akin to CSS `object-fit: contain`
  43012. *
  43013. * @param {Texture} texture - The texture.
  43014. * @param {number} aspect - The texture's aspect ratio.
  43015. * @return {Texture} The updated texture.
  43016. */
  43017. static contain( texture, aspect ) {
  43018. return contain( texture, aspect );
  43019. }
  43020. /**
  43021. * Scales the texture to the smallest possible size to fill the surface, leaving
  43022. * no empty space. The method preserves the original aspect ratio of the texture.
  43023. * Akin to CSS `object-fit: cover`.
  43024. *
  43025. * @param {Texture} texture - The texture.
  43026. * @param {number} aspect - The texture's aspect ratio.
  43027. * @return {Texture} The updated texture.
  43028. */
  43029. static cover( texture, aspect ) {
  43030. return cover( texture, aspect );
  43031. }
  43032. /**
  43033. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43034. *
  43035. * @param {Texture} texture - The texture.
  43036. * @return {Texture} The updated texture.
  43037. */
  43038. static fill( texture ) {
  43039. return fill( texture );
  43040. }
  43041. /**
  43042. * Determines how many bytes must be used to represent the texture.
  43043. *
  43044. * @param {number} width - The width of the texture.
  43045. * @param {number} height - The height of the texture.
  43046. * @param {number} format - The texture's format.
  43047. * @param {number} type - The texture's type.
  43048. * @return {number} The byte length.
  43049. */
  43050. static getByteLength( width, height, format, type ) {
  43051. return getByteLength( width, height, format, type );
  43052. }
  43053. }
  43054. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43055. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43056. revision: REVISION,
  43057. } } ) );
  43058. }
  43059. if ( typeof window !== 'undefined' ) {
  43060. if ( window.__THREE__ ) {
  43061. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43062. } else {
  43063. window.__THREE__ = REVISION;
  43064. }
  43065. }
  43066. 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, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, Compatibility, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeDepthTexture, 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, ExternalTexture, 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, InterpolateBezier, 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, MaterialBlending, 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, NoNormalPacking, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NormalGAPacking, NormalRGPacking, 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, R11_EAC_Format, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, 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_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_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, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, cloneUniforms, createCanvasElement, createElementNS, error, getByteLength, getConsoleFunction, getUnlitUniformColorSpace, isTypedArray, log, mergeUniforms, probeAsync, setConsoleFunction, warn, warnOnce };
粤ICP备19079148号