three.core.js 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325
  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. * Zero curvature ending for animations.
  1032. *
  1033. * @type {number}
  1034. * @constant
  1035. */
  1036. const ZeroCurvatureEnding = 2400;
  1037. /**
  1038. * Zero slope ending for animations.
  1039. *
  1040. * @type {number}
  1041. * @constant
  1042. */
  1043. const ZeroSlopeEnding = 2401;
  1044. /**
  1045. * Wrap around ending for animations.
  1046. *
  1047. * @type {number}
  1048. * @constant
  1049. */
  1050. const WrapAroundEnding = 2402;
  1051. /**
  1052. * Default animation blend mode.
  1053. *
  1054. * @type {number}
  1055. * @constant
  1056. */
  1057. const NormalAnimationBlendMode = 2500;
  1058. /**
  1059. * Additive animation blend mode. Can be used to layer motions on top of
  1060. * each other to build complex performances from smaller re-usable assets.
  1061. *
  1062. * @type {number}
  1063. * @constant
  1064. */
  1065. const AdditiveAnimationBlendMode = 2501;
  1066. /**
  1067. * For every three vertices draw a single triangle.
  1068. *
  1069. * @type {number}
  1070. * @constant
  1071. */
  1072. const TrianglesDrawMode = 0;
  1073. /**
  1074. * For each vertex draw a triangle from the last three vertices.
  1075. *
  1076. * @type {number}
  1077. * @constant
  1078. */
  1079. const TriangleStripDrawMode = 1;
  1080. /**
  1081. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1082. *
  1083. * @type {number}
  1084. * @constant
  1085. */
  1086. const TriangleFanDrawMode = 2;
  1087. /**
  1088. * The depth value is inverted (1.0 - z) for visualization purposes.
  1089. *
  1090. * @type {number}
  1091. * @constant
  1092. */
  1093. const BasicDepthPacking = 3200;
  1094. /**
  1095. * The depth value is packed into 32 bit RGBA.
  1096. *
  1097. * @type {number}
  1098. * @constant
  1099. */
  1100. const RGBADepthPacking = 3201;
  1101. /**
  1102. * The depth value is packed into 24 bit RGB.
  1103. *
  1104. * @type {number}
  1105. * @constant
  1106. */
  1107. const RGBDepthPacking = 3202;
  1108. /**
  1109. * The depth value is packed into 16 bit RG.
  1110. *
  1111. * @type {number}
  1112. * @constant
  1113. */
  1114. const RGDepthPacking = 3203;
  1115. /**
  1116. * Normal information is relative to the underlying surface.
  1117. *
  1118. * @type {number}
  1119. * @constant
  1120. */
  1121. const TangentSpaceNormalMap = 0;
  1122. /**
  1123. * Normal information is relative to the object orientation.
  1124. *
  1125. * @type {number}
  1126. * @constant
  1127. */
  1128. const ObjectSpaceNormalMap = 1;
  1129. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1130. /**
  1131. * No color space.
  1132. *
  1133. * @type {string}
  1134. * @constant
  1135. */
  1136. const NoColorSpace = '';
  1137. /**
  1138. * sRGB color space.
  1139. *
  1140. * @type {string}
  1141. * @constant
  1142. */
  1143. const SRGBColorSpace = 'srgb';
  1144. /**
  1145. * sRGB-linear color space.
  1146. *
  1147. * @type {string}
  1148. * @constant
  1149. */
  1150. const LinearSRGBColorSpace = 'srgb-linear';
  1151. /**
  1152. * Linear transfer function.
  1153. *
  1154. * @type {string}
  1155. * @constant
  1156. */
  1157. const LinearTransfer = 'linear';
  1158. /**
  1159. * sRGB transfer function.
  1160. *
  1161. * @type {string}
  1162. * @constant
  1163. */
  1164. const SRGBTransfer = 'srgb';
  1165. /**
  1166. * No normal map packing.
  1167. *
  1168. * @type {string}
  1169. * @constant
  1170. */
  1171. const NoNormalPacking = '';
  1172. /**
  1173. * Normal RG packing.
  1174. *
  1175. * @type {string}
  1176. * @constant
  1177. */
  1178. const NormalRGPacking = 'rg';
  1179. /**
  1180. * Normal GA packing.
  1181. *
  1182. * @type {string}
  1183. * @constant
  1184. */
  1185. const NormalGAPacking = 'ga';
  1186. /**
  1187. * Sets the stencil buffer value to `0`.
  1188. *
  1189. * @type {number}
  1190. * @constant
  1191. */
  1192. const ZeroStencilOp = 0;
  1193. /**
  1194. * Keeps the current value.
  1195. *
  1196. * @type {number}
  1197. * @constant
  1198. */
  1199. const KeepStencilOp = 7680;
  1200. /**
  1201. * Sets the stencil buffer value to the specified reference value.
  1202. *
  1203. * @type {number}
  1204. * @constant
  1205. */
  1206. const ReplaceStencilOp = 7681;
  1207. /**
  1208. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1209. *
  1210. * @type {number}
  1211. * @constant
  1212. */
  1213. const IncrementStencilOp = 7682;
  1214. /**
  1215. * Decrements the current stencil buffer value. Clamps to `0`.
  1216. *
  1217. * @type {number}
  1218. * @constant
  1219. */
  1220. const DecrementStencilOp = 7683;
  1221. /**
  1222. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1223. * the maximum representable unsigned value.
  1224. *
  1225. * @type {number}
  1226. * @constant
  1227. */
  1228. const IncrementWrapStencilOp = 34055;
  1229. /**
  1230. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1231. * unsigned value when decrementing a stencil buffer value of `0`.
  1232. *
  1233. * @type {number}
  1234. * @constant
  1235. */
  1236. const DecrementWrapStencilOp = 34056;
  1237. /**
  1238. * Inverts the current stencil buffer value bitwise.
  1239. *
  1240. * @type {number}
  1241. * @constant
  1242. */
  1243. const InvertStencilOp = 5386;
  1244. /**
  1245. * Will never return true.
  1246. *
  1247. * @type {number}
  1248. * @constant
  1249. */
  1250. const NeverStencilFunc = 512;
  1251. /**
  1252. * Will return true if the stencil reference value is less than the current stencil value.
  1253. *
  1254. * @type {number}
  1255. * @constant
  1256. */
  1257. const LessStencilFunc = 513;
  1258. /**
  1259. * Will return true if the stencil reference value is equal to the current stencil value.
  1260. *
  1261. * @type {number}
  1262. * @constant
  1263. */
  1264. const EqualStencilFunc = 514;
  1265. /**
  1266. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1267. *
  1268. * @type {number}
  1269. * @constant
  1270. */
  1271. const LessEqualStencilFunc = 515;
  1272. /**
  1273. * Will return true if the stencil reference value is greater than the current stencil value.
  1274. *
  1275. * @type {number}
  1276. * @constant
  1277. */
  1278. const GreaterStencilFunc = 516;
  1279. /**
  1280. * Will return true if the stencil reference value is not equal to the current stencil value.
  1281. *
  1282. * @type {number}
  1283. * @constant
  1284. */
  1285. const NotEqualStencilFunc = 517;
  1286. /**
  1287. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1288. *
  1289. * @type {number}
  1290. * @constant
  1291. */
  1292. const GreaterEqualStencilFunc = 518;
  1293. /**
  1294. * Will always return true.
  1295. *
  1296. * @type {number}
  1297. * @constant
  1298. */
  1299. const AlwaysStencilFunc = 519;
  1300. /**
  1301. * Never pass.
  1302. *
  1303. * @type {number}
  1304. * @constant
  1305. */
  1306. const NeverCompare = 512;
  1307. /**
  1308. * Pass if the incoming value is less than the texture value.
  1309. *
  1310. * @type {number}
  1311. * @constant
  1312. */
  1313. const LessCompare = 513;
  1314. /**
  1315. * Pass if the incoming value equals the texture value.
  1316. *
  1317. * @type {number}
  1318. * @constant
  1319. */
  1320. const EqualCompare = 514;
  1321. /**
  1322. * Pass if the incoming value is less than or equal to the texture value.
  1323. *
  1324. * @type {number}
  1325. * @constant
  1326. */
  1327. const LessEqualCompare = 515;
  1328. /**
  1329. * Pass if the incoming value is greater than the texture value.
  1330. *
  1331. * @type {number}
  1332. * @constant
  1333. */
  1334. const GreaterCompare = 516;
  1335. /**
  1336. * Pass if the incoming value is not equal to the texture value.
  1337. *
  1338. * @type {number}
  1339. * @constant
  1340. */
  1341. const NotEqualCompare = 517;
  1342. /**
  1343. * Pass if the incoming value is greater than or equal to the texture value.
  1344. *
  1345. * @type {number}
  1346. * @constant
  1347. */
  1348. const GreaterEqualCompare = 518;
  1349. /**
  1350. * Always pass.
  1351. *
  1352. * @type {number}
  1353. * @constant
  1354. */
  1355. const AlwaysCompare = 519;
  1356. /**
  1357. * The contents are intended to be specified once by the application, and used many
  1358. * times as the source for drawing and image specification commands.
  1359. *
  1360. * @type {number}
  1361. * @constant
  1362. */
  1363. const StaticDrawUsage = 35044;
  1364. /**
  1365. * The contents are intended to be respecified repeatedly by the application, and
  1366. * used many times as the source for drawing and image specification commands.
  1367. *
  1368. * @type {number}
  1369. * @constant
  1370. */
  1371. const DynamicDrawUsage = 35048;
  1372. /**
  1373. * The contents are intended to be specified once by the application, and used at most
  1374. * a few times as the source for drawing and image specification commands.
  1375. *
  1376. * @type {number}
  1377. * @constant
  1378. */
  1379. const StreamDrawUsage = 35040;
  1380. /**
  1381. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1382. * many times by the application.
  1383. *
  1384. * @type {number}
  1385. * @constant
  1386. */
  1387. const StaticReadUsage = 35045;
  1388. /**
  1389. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1390. * many times by the application.
  1391. *
  1392. * @type {number}
  1393. * @constant
  1394. */
  1395. const DynamicReadUsage = 35049;
  1396. /**
  1397. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1398. * a few times by the application
  1399. *
  1400. * @type {number}
  1401. * @constant
  1402. */
  1403. const StreamReadUsage = 35041;
  1404. /**
  1405. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1406. * the source for WebGL drawing and image specification commands.
  1407. *
  1408. * @type {number}
  1409. * @constant
  1410. */
  1411. const StaticCopyUsage = 35046;
  1412. /**
  1413. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1414. * as the source for WebGL drawing and image specification commands.
  1415. *
  1416. * @type {number}
  1417. * @constant
  1418. */
  1419. const DynamicCopyUsage = 35050;
  1420. /**
  1421. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1422. * as the source for WebGL drawing and image specification commands.
  1423. *
  1424. * @type {number}
  1425. * @constant
  1426. */
  1427. const StreamCopyUsage = 35042;
  1428. /**
  1429. * GLSL 1 shader code.
  1430. *
  1431. * @type {string}
  1432. * @constant
  1433. */
  1434. const GLSL1 = '100';
  1435. /**
  1436. * GLSL 3 shader code.
  1437. *
  1438. * @type {string}
  1439. * @constant
  1440. */
  1441. const GLSL3 = '300 es';
  1442. /**
  1443. * WebGL coordinate system.
  1444. *
  1445. * @type {number}
  1446. * @constant
  1447. */
  1448. const WebGLCoordinateSystem = 2000;
  1449. /**
  1450. * WebGPU coordinate system.
  1451. *
  1452. * @type {number}
  1453. * @constant
  1454. */
  1455. const WebGPUCoordinateSystem = 2001;
  1456. /**
  1457. * Represents the different timestamp query types.
  1458. *
  1459. * @type {ConstantsTimestampQuery}
  1460. * @constant
  1461. */
  1462. const TimestampQuery = {
  1463. COMPUTE: 'compute',
  1464. RENDER: 'render'
  1465. };
  1466. /**
  1467. * Represents mouse buttons and interaction types in context of controls.
  1468. *
  1469. * @type {ConstantsInterpolationSamplingType}
  1470. * @constant
  1471. */
  1472. const InterpolationSamplingType = {
  1473. PERSPECTIVE: 'perspective',
  1474. LINEAR: 'linear',
  1475. FLAT: 'flat'
  1476. };
  1477. /**
  1478. * Represents the different interpolation sampling modes.
  1479. *
  1480. * @type {ConstantsInterpolationSamplingMode}
  1481. * @constant
  1482. */
  1483. const InterpolationSamplingMode = {
  1484. NORMAL: 'normal',
  1485. CENTROID: 'centroid',
  1486. SAMPLE: 'sample',
  1487. FIRST: 'first',
  1488. EITHER: 'either'
  1489. };
  1490. /**
  1491. * Compatibility flags for features that may not be supported across all platforms.
  1492. *
  1493. * @type {Object}
  1494. * @constant
  1495. */
  1496. const Compatibility = {
  1497. TEXTURE_COMPARE: 'depthTextureCompare'
  1498. };
  1499. /**
  1500. * This type represents mouse buttons and interaction types in context of controls.
  1501. *
  1502. * @typedef {Object} ConstantsMouse
  1503. * @property {number} MIDDLE - The left mouse button.
  1504. * @property {number} LEFT - The middle mouse button.
  1505. * @property {number} RIGHT - The right mouse button.
  1506. * @property {number} ROTATE - A rotate interaction.
  1507. * @property {number} DOLLY - A dolly interaction.
  1508. * @property {number} PAN - A pan interaction.
  1509. **/
  1510. /**
  1511. * This type represents touch interaction types in context of controls.
  1512. *
  1513. * @typedef {Object} ConstantsTouch
  1514. * @property {number} ROTATE - A rotate interaction.
  1515. * @property {number} PAN - A pan interaction.
  1516. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1517. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1518. **/
  1519. /**
  1520. * This type represents the different timestamp query types.
  1521. *
  1522. * @typedef {Object} ConstantsTimestampQuery
  1523. * @property {string} COMPUTE - A `compute` timestamp query.
  1524. * @property {string} RENDER - A `render` timestamp query.
  1525. **/
  1526. /**
  1527. * Represents the different interpolation sampling types.
  1528. *
  1529. * @typedef {Object} ConstantsInterpolationSamplingType
  1530. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1531. * @property {string} LINEAR - Linear interpolation.
  1532. * @property {string} FLAT - Flat interpolation.
  1533. */
  1534. /**
  1535. * Represents the different interpolation sampling modes.
  1536. *
  1537. * @typedef {Object} ConstantsInterpolationSamplingMode
  1538. * @property {string} NORMAL - Normal sampling mode.
  1539. * @property {string} CENTROID - Centroid sampling mode.
  1540. * @property {string} SAMPLE - Sample-specific sampling mode.
  1541. * @property {string} FIRST - Flat interpolation using the first vertex.
  1542. * @property {string} EITHER - Flat interpolation using either vertex.
  1543. */
  1544. /**
  1545. * Finds the minimum value in an array.
  1546. *
  1547. * @private
  1548. * @param {Array<number>} array - The array to search for the minimum value.
  1549. * @return {number} The minimum value in the array, or Infinity if the array is empty.
  1550. */
  1551. /**
  1552. * Checks if an array contains values that require Uint32 representation.
  1553. *
  1554. * This function determines whether the array contains any values >= 65535,
  1555. * which would require a Uint32Array rather than a Uint16Array for proper storage.
  1556. * The function iterates from the end of the array, assuming larger values are
  1557. * typically located at the end.
  1558. *
  1559. * @private
  1560. * @param {Array<number>} array - The array to check.
  1561. * @return {boolean} True if the array contains values >= 65535, false otherwise.
  1562. */
  1563. function arrayNeedsUint32( array ) {
  1564. // assumes larger values usually on last
  1565. for ( let i = array.length - 1; i >= 0; -- i ) {
  1566. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1567. }
  1568. return false;
  1569. }
  1570. /**
  1571. * Map of typed array constructor names to their constructors.
  1572. * This mapping enables dynamic creation of typed arrays based on string type names.
  1573. *
  1574. * @private
  1575. * @constant
  1576. * @type {Object<string, TypedArrayConstructor>}
  1577. */
  1578. const TYPED_ARRAYS = {
  1579. Int8Array: Int8Array,
  1580. Uint8Array: Uint8Array,
  1581. Uint8ClampedArray: Uint8ClampedArray,
  1582. Int16Array: Int16Array,
  1583. Uint16Array: Uint16Array,
  1584. Int32Array: Int32Array,
  1585. Uint32Array: Uint32Array,
  1586. Float32Array: Float32Array,
  1587. Float64Array: Float64Array
  1588. };
  1589. /**
  1590. * Creates a typed array of the specified type from the given buffer.
  1591. *
  1592. * @private
  1593. * @param {string} type - The name of the typed array type (e.g., 'Float32Array', 'Uint16Array').
  1594. * @param {ArrayBuffer} buffer - The buffer to create the typed array from.
  1595. * @return {TypedArray} A new typed array of the specified type.
  1596. */
  1597. function getTypedArray( type, buffer ) {
  1598. return new TYPED_ARRAYS[ type ]( buffer );
  1599. }
  1600. /**
  1601. * Returns `true` if the given object is a typed array.
  1602. *
  1603. * @param {any} array - The object to check.
  1604. * @return {boolean} Whether the given object is a typed array.
  1605. */
  1606. function isTypedArray( array ) {
  1607. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1608. }
  1609. /**
  1610. * Creates an XHTML element with the specified tag name.
  1611. *
  1612. * This function uses the XHTML namespace to create DOM elements,
  1613. * ensuring proper element creation in XML-based contexts.
  1614. *
  1615. * @private
  1616. * @param {string} name - The tag name of the element to create (e.g., 'canvas', 'div').
  1617. * @return {HTMLElement} The created XHTML element.
  1618. */
  1619. function createElementNS( name ) {
  1620. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1621. }
  1622. /**
  1623. * Creates a canvas element configured for block display.
  1624. *
  1625. * This is a convenience function that creates a canvas element with
  1626. * display style set to 'block', which is commonly used in three.js
  1627. * rendering contexts to avoid inline element spacing issues.
  1628. *
  1629. * @return {HTMLCanvasElement} A canvas element with display set to 'block'.
  1630. */
  1631. function createCanvasElement() {
  1632. const canvas = createElementNS( 'canvas' );
  1633. canvas.style.display = 'block';
  1634. return canvas;
  1635. }
  1636. /**
  1637. * Internal cache for tracking warning messages to prevent duplicate warnings.
  1638. *
  1639. * @private
  1640. * @type {Object<string, boolean>}
  1641. */
  1642. const _cache = {};
  1643. /**
  1644. * Custom console function handler for intercepting log, warn, and error calls.
  1645. *
  1646. * @private
  1647. * @type {Function|null}
  1648. */
  1649. let _setConsoleFunction = null;
  1650. /**
  1651. * Sets a custom function to handle console output.
  1652. *
  1653. * This allows external code to intercept and handle console.log, console.warn,
  1654. * and console.error calls made by three.js, which is useful for custom logging,
  1655. * testing, or debugging workflows.
  1656. *
  1657. * @param {Function} fn - The function to handle console output. Should accept
  1658. * (type, message, ...params) where type is 'log', 'warn', or 'error'.
  1659. */
  1660. function setConsoleFunction( fn ) {
  1661. _setConsoleFunction = fn;
  1662. }
  1663. /**
  1664. * Gets the currently set custom console function.
  1665. *
  1666. * @return {Function|null} The custom console function, or null if not set.
  1667. */
  1668. function getConsoleFunction() {
  1669. return _setConsoleFunction;
  1670. }
  1671. /**
  1672. * Logs an informational message with the 'THREE.' prefix.
  1673. *
  1674. * If a custom console function is set via setConsoleFunction(), it will be used
  1675. * instead of the native console.log. The first parameter is treated as the
  1676. * method name and is automatically prefixed with 'THREE.'.
  1677. *
  1678. * @param {...any} params - The message components. The first param is used as
  1679. * the method name and prefixed with 'THREE.'.
  1680. */
  1681. function log( ...params ) {
  1682. const message = 'THREE.' + params.shift();
  1683. if ( _setConsoleFunction ) {
  1684. _setConsoleFunction( 'log', message, ...params );
  1685. } else {
  1686. console.log( message, ...params );
  1687. }
  1688. }
  1689. /**
  1690. * Logs a warning message with the 'THREE.' prefix.
  1691. *
  1692. * If a custom console function is set via setConsoleFunction(), it will be used
  1693. * instead of the native console.warn. The first parameter is treated as the
  1694. * method name and is automatically prefixed with 'THREE.'.
  1695. *
  1696. * @param {...any} params - The message components. The first param is used as
  1697. * the method name and prefixed with 'THREE.'.
  1698. */
  1699. function warn( ...params ) {
  1700. const message = 'THREE.' + params.shift();
  1701. if ( _setConsoleFunction ) {
  1702. _setConsoleFunction( 'warn', message, ...params );
  1703. } else {
  1704. console.warn( message, ...params );
  1705. }
  1706. }
  1707. /**
  1708. * Logs an error message with the 'THREE.' prefix.
  1709. *
  1710. * If a custom console function is set via setConsoleFunction(), it will be used
  1711. * instead of the native console.error. The first parameter is treated as the
  1712. * method name and is automatically prefixed with 'THREE.'.
  1713. *
  1714. * @param {...any} params - The message components. The first param is used as
  1715. * the method name and prefixed with 'THREE.'.
  1716. */
  1717. function error( ...params ) {
  1718. const message = 'THREE.' + params.shift();
  1719. if ( _setConsoleFunction ) {
  1720. _setConsoleFunction( 'error', message, ...params );
  1721. } else {
  1722. console.error( message, ...params );
  1723. }
  1724. }
  1725. /**
  1726. * Logs a warning message only once, preventing duplicate warnings.
  1727. *
  1728. * This function maintains an internal cache of warning messages and will only
  1729. * output each unique warning message once. Useful for warnings that may be
  1730. * triggered repeatedly but should only be shown to the user once.
  1731. *
  1732. * @param {...any} params - The warning message components.
  1733. */
  1734. function warnOnce( ...params ) {
  1735. const message = params.join( ' ' );
  1736. if ( message in _cache ) return;
  1737. _cache[ message ] = true;
  1738. warn( ...params );
  1739. }
  1740. /**
  1741. * Asynchronously probes for WebGL sync object completion.
  1742. *
  1743. * This function creates a promise that resolves when the WebGL sync object
  1744. * signals completion or rejects if the sync operation fails. It uses polling
  1745. * at the specified interval to check the sync status without blocking the
  1746. * main thread. This is useful for GPU-CPU synchronization in WebGL contexts.
  1747. *
  1748. * @private
  1749. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL rendering context.
  1750. * @param {WebGLSync} sync - The WebGL sync object to wait for.
  1751. * @param {number} interval - The polling interval in milliseconds.
  1752. * @return {Promise<void>} A promise that resolves when the sync completes or rejects if it fails.
  1753. */
  1754. function probeAsync( gl, sync, interval ) {
  1755. return new Promise( function ( resolve, reject ) {
  1756. function probe() {
  1757. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1758. case gl.WAIT_FAILED:
  1759. reject();
  1760. break;
  1761. case gl.TIMEOUT_EXPIRED:
  1762. setTimeout( probe, interval );
  1763. break;
  1764. default:
  1765. resolve();
  1766. }
  1767. }
  1768. setTimeout( probe, interval );
  1769. } );
  1770. }
  1771. /**
  1772. * This modules allows to dispatch event objects on custom JavaScript objects.
  1773. *
  1774. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1775. *
  1776. * Code Example:
  1777. * ```js
  1778. * class Car extends EventDispatcher {
  1779. * start() {
  1780. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1781. * }
  1782. *};
  1783. *
  1784. * // Using events with the custom object
  1785. * const car = new Car();
  1786. * car.addEventListener( 'start', function ( event ) {
  1787. * alert( event.message );
  1788. * } );
  1789. *
  1790. * car.start();
  1791. * ```
  1792. */
  1793. class EventDispatcher {
  1794. /**
  1795. * Adds the given event listener to the given event type.
  1796. *
  1797. * @param {string} type - The type of event to listen to.
  1798. * @param {Function} listener - The function that gets called when the event is fired.
  1799. */
  1800. addEventListener( type, listener ) {
  1801. if ( this._listeners === undefined ) this._listeners = {};
  1802. const listeners = this._listeners;
  1803. if ( listeners[ type ] === undefined ) {
  1804. listeners[ type ] = [];
  1805. }
  1806. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1807. listeners[ type ].push( listener );
  1808. }
  1809. }
  1810. /**
  1811. * Returns `true` if the given event listener has been added to the given event type.
  1812. *
  1813. * @param {string} type - The type of event.
  1814. * @param {Function} listener - The listener to check.
  1815. * @return {boolean} Whether the given event listener has been added to the given event type.
  1816. */
  1817. hasEventListener( type, listener ) {
  1818. const listeners = this._listeners;
  1819. if ( listeners === undefined ) return false;
  1820. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1821. }
  1822. /**
  1823. * Removes the given event listener from the given event type.
  1824. *
  1825. * @param {string} type - The type of event.
  1826. * @param {Function} listener - The listener to remove.
  1827. */
  1828. removeEventListener( type, listener ) {
  1829. const listeners = this._listeners;
  1830. if ( listeners === undefined ) return;
  1831. const listenerArray = listeners[ type ];
  1832. if ( listenerArray !== undefined ) {
  1833. const index = listenerArray.indexOf( listener );
  1834. if ( index !== -1 ) {
  1835. listenerArray.splice( index, 1 );
  1836. }
  1837. }
  1838. }
  1839. /**
  1840. * Dispatches an event object.
  1841. *
  1842. * @param {Object} event - The event that gets fired.
  1843. */
  1844. dispatchEvent( event ) {
  1845. const listeners = this._listeners;
  1846. if ( listeners === undefined ) return;
  1847. const listenerArray = listeners[ event.type ];
  1848. if ( listenerArray !== undefined ) {
  1849. event.target = this;
  1850. // Make a copy, in case listeners are removed while iterating.
  1851. const array = listenerArray.slice( 0 );
  1852. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1853. array[ i ].call( this, event );
  1854. }
  1855. event.target = null;
  1856. }
  1857. }
  1858. }
  1859. 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' ];
  1860. let _seed = 1234567;
  1861. const DEG2RAD = Math.PI / 180;
  1862. const RAD2DEG = 180 / Math.PI;
  1863. /**
  1864. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1865. * (universally unique identifier).
  1866. *
  1867. * @return {string} The UUID.
  1868. */
  1869. function generateUUID() {
  1870. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1871. const d0 = Math.random() * 0xffffffff | 0;
  1872. const d1 = Math.random() * 0xffffffff | 0;
  1873. const d2 = Math.random() * 0xffffffff | 0;
  1874. const d3 = Math.random() * 0xffffffff | 0;
  1875. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1876. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1877. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1878. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1879. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1880. return uuid.toLowerCase();
  1881. }
  1882. /**
  1883. * Clamps the given value between min and max.
  1884. *
  1885. * @param {number} value - The value to clamp.
  1886. * @param {number} min - The min value.
  1887. * @param {number} max - The max value.
  1888. * @return {number} The clamped value.
  1889. */
  1890. function clamp( value, min, max ) {
  1891. return Math.max( min, Math.min( max, value ) );
  1892. }
  1893. /**
  1894. * Computes the Euclidean modulo of the given parameters that
  1895. * is `( ( n % m ) + m ) % m`.
  1896. *
  1897. * @param {number} n - The first parameter.
  1898. * @param {number} m - The second parameter.
  1899. * @return {number} The Euclidean modulo.
  1900. */
  1901. function euclideanModulo( n, m ) {
  1902. // https://en.wikipedia.org/wiki/Modulo_operation
  1903. return ( ( n % m ) + m ) % m;
  1904. }
  1905. /**
  1906. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1907. * for the given value.
  1908. *
  1909. * @param {number} x - The value to be mapped.
  1910. * @param {number} a1 - Minimum value for range A.
  1911. * @param {number} a2 - Maximum value for range A.
  1912. * @param {number} b1 - Minimum value for range B.
  1913. * @param {number} b2 - Maximum value for range B.
  1914. * @return {number} The mapped value.
  1915. */
  1916. function mapLinear( x, a1, a2, b1, b2 ) {
  1917. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1918. }
  1919. /**
  1920. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1921. * between the start and end point.
  1922. *
  1923. * @param {number} x - The start point
  1924. * @param {number} y - The end point.
  1925. * @param {number} value - A value between start and end.
  1926. * @return {number} The interpolation factor.
  1927. */
  1928. function inverseLerp( x, y, value ) {
  1929. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1930. if ( x !== y ) {
  1931. return ( value - x ) / ( y - x );
  1932. } else {
  1933. return 0;
  1934. }
  1935. }
  1936. /**
  1937. * Returns a value linearly interpolated from two known points based on the given interval -
  1938. * `t = 0` will return `x` and `t = 1` will return `y`.
  1939. *
  1940. * @param {number} x - The start point
  1941. * @param {number} y - The end point.
  1942. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1943. * @return {number} The interpolated value.
  1944. */
  1945. function lerp( x, y, t ) {
  1946. return ( 1 - t ) * x + t * y;
  1947. }
  1948. /**
  1949. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1950. * time to maintain frame rate independent movement. For details, see
  1951. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  1952. *
  1953. * @param {number} x - The current point.
  1954. * @param {number} y - The target point.
  1955. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1956. * and a lower value will make the movement more gradual.
  1957. * @param {number} dt - Delta time in seconds.
  1958. * @return {number} The interpolated value.
  1959. */
  1960. function damp( x, y, lambda, dt ) {
  1961. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1962. }
  1963. /**
  1964. * Returns a value that alternates between `0` and the given `length` parameter.
  1965. *
  1966. * @param {number} x - The value to pingpong.
  1967. * @param {number} [length=1] - The positive value the function will pingpong to.
  1968. * @return {number} The alternated value.
  1969. */
  1970. function pingpong( x, length = 1 ) {
  1971. // https://www.desmos.com/calculator/vcsjnyz7x4
  1972. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1973. }
  1974. /**
  1975. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1976. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1977. * the `min` and `max`.
  1978. *
  1979. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  1980. *
  1981. * @param {number} x - The value to evaluate based on its position between min and max.
  1982. * @param {number} min - The min value. Any x value below min will be `0`.
  1983. * @param {number} max - The max value. Any x value above max will be `1`.
  1984. * @return {number} The alternated value.
  1985. */
  1986. function smoothstep( x, min, max ) {
  1987. if ( x <= min ) return 0;
  1988. if ( x >= max ) return 1;
  1989. x = ( x - min ) / ( max - min );
  1990. return x * x * ( 3 - 2 * x );
  1991. }
  1992. /**
  1993. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  1994. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1995. *
  1996. * @param {number} x - The value to evaluate based on its position between min and max.
  1997. * @param {number} min - The min value. Any x value below min will be `0`.
  1998. * @param {number} max - The max value. Any x value above max will be `1`.
  1999. * @return {number} The alternated value.
  2000. */
  2001. function smootherstep( x, min, max ) {
  2002. if ( x <= min ) return 0;
  2003. if ( x >= max ) return 1;
  2004. x = ( x - min ) / ( max - min );
  2005. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  2006. }
  2007. /**
  2008. * Returns a random integer from `<low, high>` interval.
  2009. *
  2010. * @param {number} low - The lower value boundary.
  2011. * @param {number} high - The upper value boundary
  2012. * @return {number} A random integer.
  2013. */
  2014. function randInt( low, high ) {
  2015. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2016. }
  2017. /**
  2018. * Returns a random float from `<low, high>` interval.
  2019. *
  2020. * @param {number} low - The lower value boundary.
  2021. * @param {number} high - The upper value boundary
  2022. * @return {number} A random float.
  2023. */
  2024. function randFloat( low, high ) {
  2025. return low + Math.random() * ( high - low );
  2026. }
  2027. /**
  2028. * Returns a random integer from `<-range/2, range/2>` interval.
  2029. *
  2030. * @param {number} range - Defines the value range.
  2031. * @return {number} A random float.
  2032. */
  2033. function randFloatSpread( range ) {
  2034. return range * ( 0.5 - Math.random() );
  2035. }
  2036. /**
  2037. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2038. *
  2039. * @param {number} [s] - The integer seed.
  2040. * @return {number} A random float.
  2041. */
  2042. function seededRandom( s ) {
  2043. if ( s !== undefined ) _seed = s;
  2044. // Mulberry32 generator
  2045. let t = _seed += 0x6D2B79F5;
  2046. t = Math.imul( t ^ t >>> 15, t | 1 );
  2047. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  2048. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  2049. }
  2050. /**
  2051. * Converts degrees to radians.
  2052. *
  2053. * @param {number} degrees - A value in degrees.
  2054. * @return {number} The converted value in radians.
  2055. */
  2056. function degToRad( degrees ) {
  2057. return degrees * DEG2RAD;
  2058. }
  2059. /**
  2060. * Converts radians to degrees.
  2061. *
  2062. * @param {number} radians - A value in radians.
  2063. * @return {number} The converted value in degrees.
  2064. */
  2065. function radToDeg( radians ) {
  2066. return radians * RAD2DEG;
  2067. }
  2068. /**
  2069. * Returns `true` if the given number is a power of two.
  2070. *
  2071. * @param {number} value - The value to check.
  2072. * @return {boolean} Whether the given number is a power of two or not.
  2073. */
  2074. function isPowerOfTwo( value ) {
  2075. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  2076. }
  2077. /**
  2078. * Returns the smallest power of two that is greater than or equal to the given number.
  2079. *
  2080. * @param {number} value - The value to find a POT for.
  2081. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2082. */
  2083. function ceilPowerOfTwo( value ) {
  2084. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  2085. }
  2086. /**
  2087. * Returns the largest power of two that is less than or equal to the given number.
  2088. *
  2089. * @param {number} value - The value to find a POT for.
  2090. * @return {number} The largest power of two that is less than or equal to the given number.
  2091. */
  2092. function floorPowerOfTwo( value ) {
  2093. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  2094. }
  2095. /**
  2096. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2097. * defined by the given angles and order.
  2098. *
  2099. * Rotations are applied to the axes in the order specified by order:
  2100. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2101. *
  2102. * @param {Quaternion} q - The quaternion to set.
  2103. * @param {number} a - The rotation applied to the first axis, in radians.
  2104. * @param {number} b - The rotation applied to the second axis, in radians.
  2105. * @param {number} c - The rotation applied to the third axis, in radians.
  2106. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2107. */
  2108. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  2109. const cos = Math.cos;
  2110. const sin = Math.sin;
  2111. const c2 = cos( b / 2 );
  2112. const s2 = sin( b / 2 );
  2113. const c13 = cos( ( a + c ) / 2 );
  2114. const s13 = sin( ( a + c ) / 2 );
  2115. const c1_3 = cos( ( a - c ) / 2 );
  2116. const s1_3 = sin( ( a - c ) / 2 );
  2117. const c3_1 = cos( ( c - a ) / 2 );
  2118. const s3_1 = sin( ( c - a ) / 2 );
  2119. switch ( order ) {
  2120. case 'XYX':
  2121. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  2122. break;
  2123. case 'YZY':
  2124. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  2125. break;
  2126. case 'ZXZ':
  2127. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  2128. break;
  2129. case 'XZX':
  2130. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  2131. break;
  2132. case 'YXY':
  2133. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  2134. break;
  2135. case 'ZYZ':
  2136. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  2137. break;
  2138. default:
  2139. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  2140. }
  2141. }
  2142. /**
  2143. * Denormalizes the given value according to the given typed array.
  2144. *
  2145. * @param {number} value - The value to denormalize.
  2146. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2147. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2148. */
  2149. function denormalize( value, array ) {
  2150. switch ( array.constructor ) {
  2151. case Float32Array:
  2152. return value;
  2153. case Uint32Array:
  2154. return value / 4294967295.0;
  2155. case Uint16Array:
  2156. return value / 65535.0;
  2157. case Uint8Array:
  2158. return value / 255.0;
  2159. case Int32Array:
  2160. return Math.max( value / 2147483647.0, -1 );
  2161. case Int16Array:
  2162. return Math.max( value / 32767.0, -1 );
  2163. case Int8Array:
  2164. return Math.max( value / 127.0, -1 );
  2165. default:
  2166. throw new Error( 'Invalid component type.' );
  2167. }
  2168. }
  2169. /**
  2170. * Normalizes the given value according to the given typed array.
  2171. *
  2172. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2173. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2174. * @return {number} The normalize value.
  2175. */
  2176. function normalize( value, array ) {
  2177. switch ( array.constructor ) {
  2178. case Float32Array:
  2179. return value;
  2180. case Uint32Array:
  2181. return Math.round( value * 4294967295.0 );
  2182. case Uint16Array:
  2183. return Math.round( value * 65535.0 );
  2184. case Uint8Array:
  2185. return Math.round( value * 255.0 );
  2186. case Int32Array:
  2187. return Math.round( value * 2147483647.0 );
  2188. case Int16Array:
  2189. return Math.round( value * 32767.0 );
  2190. case Int8Array:
  2191. return Math.round( value * 127.0 );
  2192. default:
  2193. throw new Error( 'Invalid component type.' );
  2194. }
  2195. }
  2196. /**
  2197. * @class
  2198. * @classdesc A collection of math utility functions.
  2199. * @hideconstructor
  2200. */
  2201. const MathUtils = {
  2202. DEG2RAD: DEG2RAD,
  2203. RAD2DEG: RAD2DEG,
  2204. /**
  2205. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2206. * (universally unique identifier).
  2207. *
  2208. * @static
  2209. * @method
  2210. * @return {string} The UUID.
  2211. */
  2212. generateUUID: generateUUID,
  2213. /**
  2214. * Clamps the given value between min and max.
  2215. *
  2216. * @static
  2217. * @method
  2218. * @param {number} value - The value to clamp.
  2219. * @param {number} min - The min value.
  2220. * @param {number} max - The max value.
  2221. * @return {number} The clamped value.
  2222. */
  2223. clamp: clamp,
  2224. /**
  2225. * Computes the Euclidean modulo of the given parameters that
  2226. * is `( ( n % m ) + m ) % m`.
  2227. *
  2228. * @static
  2229. * @method
  2230. * @param {number} n - The first parameter.
  2231. * @param {number} m - The second parameter.
  2232. * @return {number} The Euclidean modulo.
  2233. */
  2234. euclideanModulo: euclideanModulo,
  2235. /**
  2236. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2237. * for the given value.
  2238. *
  2239. * @static
  2240. * @method
  2241. * @param {number} x - The value to be mapped.
  2242. * @param {number} a1 - Minimum value for range A.
  2243. * @param {number} a2 - Maximum value for range A.
  2244. * @param {number} b1 - Minimum value for range B.
  2245. * @param {number} b2 - Maximum value for range B.
  2246. * @return {number} The mapped value.
  2247. */
  2248. mapLinear: mapLinear,
  2249. /**
  2250. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2251. * between the start and end point.
  2252. *
  2253. * @static
  2254. * @method
  2255. * @param {number} x - The start point
  2256. * @param {number} y - The end point.
  2257. * @param {number} value - A value between start and end.
  2258. * @return {number} The interpolation factor.
  2259. */
  2260. inverseLerp: inverseLerp,
  2261. /**
  2262. * Returns a value linearly interpolated from two known points based on the given interval -
  2263. * `t = 0` will return `x` and `t = 1` will return `y`.
  2264. *
  2265. * @static
  2266. * @method
  2267. * @param {number} x - The start point
  2268. * @param {number} y - The end point.
  2269. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2270. * @return {number} The interpolated value.
  2271. */
  2272. lerp: lerp,
  2273. /**
  2274. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2275. * time to maintain frame rate independent movement. For details, see
  2276. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2277. *
  2278. * @static
  2279. * @method
  2280. * @param {number} x - The current point.
  2281. * @param {number} y - The target point.
  2282. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2283. * and a lower value will make the movement more gradual.
  2284. * @param {number} dt - Delta time in seconds.
  2285. * @return {number} The interpolated value.
  2286. */
  2287. damp: damp,
  2288. /**
  2289. * Returns a value that alternates between `0` and the given `length` parameter.
  2290. *
  2291. * @static
  2292. * @method
  2293. * @param {number} x - The value to pingpong.
  2294. * @param {number} [length=1] - The positive value the function will pingpong to.
  2295. * @return {number} The alternated value.
  2296. */
  2297. pingpong: pingpong,
  2298. /**
  2299. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2300. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2301. * the `min` and `max`.
  2302. *
  2303. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2304. *
  2305. * @static
  2306. * @method
  2307. * @param {number} x - The value to evaluate based on its position between min and max.
  2308. * @param {number} min - The min value. Any x value below min will be `0`.
  2309. * @param {number} max - The max value. Any x value above max will be `1`.
  2310. * @return {number} The alternated value.
  2311. */
  2312. smoothstep: smoothstep,
  2313. /**
  2314. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2315. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2316. *
  2317. * @static
  2318. * @method
  2319. * @param {number} x - The value to evaluate based on its position between min and max.
  2320. * @param {number} min - The min value. Any x value below min will be `0`.
  2321. * @param {number} max - The max value. Any x value above max will be `1`.
  2322. * @return {number} The alternated value.
  2323. */
  2324. smootherstep: smootherstep,
  2325. /**
  2326. * Returns a random integer from `<low, high>` interval.
  2327. *
  2328. * @static
  2329. * @method
  2330. * @param {number} low - The lower value boundary.
  2331. * @param {number} high - The upper value boundary
  2332. * @return {number} A random integer.
  2333. */
  2334. randInt: randInt,
  2335. /**
  2336. * Returns a random float from `<low, high>` interval.
  2337. *
  2338. * @static
  2339. * @method
  2340. * @param {number} low - The lower value boundary.
  2341. * @param {number} high - The upper value boundary
  2342. * @return {number} A random float.
  2343. */
  2344. randFloat: randFloat,
  2345. /**
  2346. * Returns a random integer from `<-range/2, range/2>` interval.
  2347. *
  2348. * @static
  2349. * @method
  2350. * @param {number} range - Defines the value range.
  2351. * @return {number} A random float.
  2352. */
  2353. randFloatSpread: randFloatSpread,
  2354. /**
  2355. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2356. *
  2357. * @static
  2358. * @method
  2359. * @param {number} [s] - The integer seed.
  2360. * @return {number} A random float.
  2361. */
  2362. seededRandom: seededRandom,
  2363. /**
  2364. * Converts degrees to radians.
  2365. *
  2366. * @static
  2367. * @method
  2368. * @param {number} degrees - A value in degrees.
  2369. * @return {number} The converted value in radians.
  2370. */
  2371. degToRad: degToRad,
  2372. /**
  2373. * Converts radians to degrees.
  2374. *
  2375. * @static
  2376. * @method
  2377. * @param {number} radians - A value in radians.
  2378. * @return {number} The converted value in degrees.
  2379. */
  2380. radToDeg: radToDeg,
  2381. /**
  2382. * Returns `true` if the given number is a power of two.
  2383. *
  2384. * @static
  2385. * @method
  2386. * @param {number} value - The value to check.
  2387. * @return {boolean} Whether the given number is a power of two or not.
  2388. */
  2389. isPowerOfTwo: isPowerOfTwo,
  2390. /**
  2391. * Returns the smallest power of two that is greater than or equal to the given number.
  2392. *
  2393. * @static
  2394. * @method
  2395. * @param {number} value - The value to find a POT for.
  2396. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2397. */
  2398. ceilPowerOfTwo: ceilPowerOfTwo,
  2399. /**
  2400. * Returns the largest power of two that is less than or equal to the given number.
  2401. *
  2402. * @static
  2403. * @method
  2404. * @param {number} value - The value to find a POT for.
  2405. * @return {number} The largest power of two that is less than or equal to the given number.
  2406. */
  2407. floorPowerOfTwo: floorPowerOfTwo,
  2408. /**
  2409. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2410. * defined by the given angles and order.
  2411. *
  2412. * Rotations are applied to the axes in the order specified by order:
  2413. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2414. *
  2415. * @static
  2416. * @method
  2417. * @param {Quaternion} q - The quaternion to set.
  2418. * @param {number} a - The rotation applied to the first axis, in radians.
  2419. * @param {number} b - The rotation applied to the second axis, in radians.
  2420. * @param {number} c - The rotation applied to the third axis, in radians.
  2421. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2422. */
  2423. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2424. /**
  2425. * Normalizes the given value according to the given typed array.
  2426. *
  2427. * @static
  2428. * @method
  2429. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2430. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2431. * @return {number} The normalize value.
  2432. */
  2433. normalize: normalize,
  2434. /**
  2435. * Denormalizes the given value according to the given typed array.
  2436. *
  2437. * @static
  2438. * @method
  2439. * @param {number} value - The value to denormalize.
  2440. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2441. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2442. */
  2443. denormalize: denormalize
  2444. };
  2445. /**
  2446. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2447. * (labeled x and y), which can be used to represent a number of things, such as:
  2448. *
  2449. * - A point in 2D space (i.e. a position on a plane).
  2450. * - A direction and length across a plane. In three.js the length will
  2451. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2452. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2453. * - Any arbitrary ordered pair of numbers.
  2454. *
  2455. * There are other things a 2D vector can be used to represent, such as
  2456. * momentum vectors, complex numbers and so on, however these are the most
  2457. * common uses in three.js.
  2458. *
  2459. * Iterating through a vector instance will yield its components `(x, y)` in
  2460. * the corresponding order.
  2461. * ```js
  2462. * const a = new THREE.Vector2( 0, 1 );
  2463. *
  2464. * //no arguments; will be initialised to (0, 0)
  2465. * const b = new THREE.Vector2( );
  2466. *
  2467. * const d = a.distanceTo( b );
  2468. * ```
  2469. */
  2470. class Vector2 {
  2471. /**
  2472. * Constructs a new 2D vector.
  2473. *
  2474. * @param {number} [x=0] - The x value of this vector.
  2475. * @param {number} [y=0] - The y value of this vector.
  2476. */
  2477. constructor( x = 0, y = 0 ) {
  2478. /**
  2479. * This flag can be used for type testing.
  2480. *
  2481. * @type {boolean}
  2482. * @readonly
  2483. * @default true
  2484. */
  2485. Vector2.prototype.isVector2 = true;
  2486. /**
  2487. * The x value of this vector.
  2488. *
  2489. * @type {number}
  2490. */
  2491. this.x = x;
  2492. /**
  2493. * The y value of this vector.
  2494. *
  2495. * @type {number}
  2496. */
  2497. this.y = y;
  2498. }
  2499. /**
  2500. * Alias for {@link Vector2#x}.
  2501. *
  2502. * @type {number}
  2503. */
  2504. get width() {
  2505. return this.x;
  2506. }
  2507. set width( value ) {
  2508. this.x = value;
  2509. }
  2510. /**
  2511. * Alias for {@link Vector2#y}.
  2512. *
  2513. * @type {number}
  2514. */
  2515. get height() {
  2516. return this.y;
  2517. }
  2518. set height( value ) {
  2519. this.y = value;
  2520. }
  2521. /**
  2522. * Sets the vector components.
  2523. *
  2524. * @param {number} x - The value of the x component.
  2525. * @param {number} y - The value of the y component.
  2526. * @return {Vector2} A reference to this vector.
  2527. */
  2528. set( x, y ) {
  2529. this.x = x;
  2530. this.y = y;
  2531. return this;
  2532. }
  2533. /**
  2534. * Sets the vector components to the same value.
  2535. *
  2536. * @param {number} scalar - The value to set for all vector components.
  2537. * @return {Vector2} A reference to this vector.
  2538. */
  2539. setScalar( scalar ) {
  2540. this.x = scalar;
  2541. this.y = scalar;
  2542. return this;
  2543. }
  2544. /**
  2545. * Sets the vector's x component to the given value
  2546. *
  2547. * @param {number} x - The value to set.
  2548. * @return {Vector2} A reference to this vector.
  2549. */
  2550. setX( x ) {
  2551. this.x = x;
  2552. return this;
  2553. }
  2554. /**
  2555. * Sets the vector's y component to the given value
  2556. *
  2557. * @param {number} y - The value to set.
  2558. * @return {Vector2} A reference to this vector.
  2559. */
  2560. setY( y ) {
  2561. this.y = y;
  2562. return this;
  2563. }
  2564. /**
  2565. * Allows to set a vector component with an index.
  2566. *
  2567. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2568. * @param {number} value - The value to set.
  2569. * @return {Vector2} A reference to this vector.
  2570. */
  2571. setComponent( index, value ) {
  2572. switch ( index ) {
  2573. case 0: this.x = value; break;
  2574. case 1: this.y = value; break;
  2575. default: throw new Error( 'index is out of range: ' + index );
  2576. }
  2577. return this;
  2578. }
  2579. /**
  2580. * Returns the value of the vector component which matches the given index.
  2581. *
  2582. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2583. * @return {number} A vector component value.
  2584. */
  2585. getComponent( index ) {
  2586. switch ( index ) {
  2587. case 0: return this.x;
  2588. case 1: return this.y;
  2589. default: throw new Error( 'index is out of range: ' + index );
  2590. }
  2591. }
  2592. /**
  2593. * Returns a new vector with copied values from this instance.
  2594. *
  2595. * @return {Vector2} A clone of this instance.
  2596. */
  2597. clone() {
  2598. return new this.constructor( this.x, this.y );
  2599. }
  2600. /**
  2601. * Copies the values of the given vector to this instance.
  2602. *
  2603. * @param {Vector2} v - The vector to copy.
  2604. * @return {Vector2} A reference to this vector.
  2605. */
  2606. copy( v ) {
  2607. this.x = v.x;
  2608. this.y = v.y;
  2609. return this;
  2610. }
  2611. /**
  2612. * Adds the given vector to this instance.
  2613. *
  2614. * @param {Vector2} v - The vector to add.
  2615. * @return {Vector2} A reference to this vector.
  2616. */
  2617. add( v ) {
  2618. this.x += v.x;
  2619. this.y += v.y;
  2620. return this;
  2621. }
  2622. /**
  2623. * Adds the given scalar value to all components of this instance.
  2624. *
  2625. * @param {number} s - The scalar to add.
  2626. * @return {Vector2} A reference to this vector.
  2627. */
  2628. addScalar( s ) {
  2629. this.x += s;
  2630. this.y += s;
  2631. return this;
  2632. }
  2633. /**
  2634. * Adds the given vectors and stores the result in this instance.
  2635. *
  2636. * @param {Vector2} a - The first vector.
  2637. * @param {Vector2} b - The second vector.
  2638. * @return {Vector2} A reference to this vector.
  2639. */
  2640. addVectors( a, b ) {
  2641. this.x = a.x + b.x;
  2642. this.y = a.y + b.y;
  2643. return this;
  2644. }
  2645. /**
  2646. * Adds the given vector scaled by the given factor to this instance.
  2647. *
  2648. * @param {Vector2} v - The vector.
  2649. * @param {number} s - The factor that scales `v`.
  2650. * @return {Vector2} A reference to this vector.
  2651. */
  2652. addScaledVector( v, s ) {
  2653. this.x += v.x * s;
  2654. this.y += v.y * s;
  2655. return this;
  2656. }
  2657. /**
  2658. * Subtracts the given vector from this instance.
  2659. *
  2660. * @param {Vector2} v - The vector to subtract.
  2661. * @return {Vector2} A reference to this vector.
  2662. */
  2663. sub( v ) {
  2664. this.x -= v.x;
  2665. this.y -= v.y;
  2666. return this;
  2667. }
  2668. /**
  2669. * Subtracts the given scalar value from all components of this instance.
  2670. *
  2671. * @param {number} s - The scalar to subtract.
  2672. * @return {Vector2} A reference to this vector.
  2673. */
  2674. subScalar( s ) {
  2675. this.x -= s;
  2676. this.y -= s;
  2677. return this;
  2678. }
  2679. /**
  2680. * Subtracts the given vectors and stores the result in this instance.
  2681. *
  2682. * @param {Vector2} a - The first vector.
  2683. * @param {Vector2} b - The second vector.
  2684. * @return {Vector2} A reference to this vector.
  2685. */
  2686. subVectors( a, b ) {
  2687. this.x = a.x - b.x;
  2688. this.y = a.y - b.y;
  2689. return this;
  2690. }
  2691. /**
  2692. * Multiplies the given vector with this instance.
  2693. *
  2694. * @param {Vector2} v - The vector to multiply.
  2695. * @return {Vector2} A reference to this vector.
  2696. */
  2697. multiply( v ) {
  2698. this.x *= v.x;
  2699. this.y *= v.y;
  2700. return this;
  2701. }
  2702. /**
  2703. * Multiplies the given scalar value with all components of this instance.
  2704. *
  2705. * @param {number} scalar - The scalar to multiply.
  2706. * @return {Vector2} A reference to this vector.
  2707. */
  2708. multiplyScalar( scalar ) {
  2709. this.x *= scalar;
  2710. this.y *= scalar;
  2711. return this;
  2712. }
  2713. /**
  2714. * Divides this instance by the given vector.
  2715. *
  2716. * @param {Vector2} v - The vector to divide.
  2717. * @return {Vector2} A reference to this vector.
  2718. */
  2719. divide( v ) {
  2720. this.x /= v.x;
  2721. this.y /= v.y;
  2722. return this;
  2723. }
  2724. /**
  2725. * Divides this vector by the given scalar.
  2726. *
  2727. * @param {number} scalar - The scalar to divide.
  2728. * @return {Vector2} A reference to this vector.
  2729. */
  2730. divideScalar( scalar ) {
  2731. return this.multiplyScalar( 1 / scalar );
  2732. }
  2733. /**
  2734. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2735. * the given 3x3 matrix.
  2736. *
  2737. * @param {Matrix3} m - The matrix to apply.
  2738. * @return {Vector2} A reference to this vector.
  2739. */
  2740. applyMatrix3( m ) {
  2741. const x = this.x, y = this.y;
  2742. const e = m.elements;
  2743. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2744. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2745. return this;
  2746. }
  2747. /**
  2748. * If this vector's x or y value is greater than the given vector's x or y
  2749. * value, replace that value with the corresponding min value.
  2750. *
  2751. * @param {Vector2} v - The vector.
  2752. * @return {Vector2} A reference to this vector.
  2753. */
  2754. min( v ) {
  2755. this.x = Math.min( this.x, v.x );
  2756. this.y = Math.min( this.y, v.y );
  2757. return this;
  2758. }
  2759. /**
  2760. * If this vector's x or y value is less than the given vector's x or y
  2761. * value, replace that value with the corresponding max value.
  2762. *
  2763. * @param {Vector2} v - The vector.
  2764. * @return {Vector2} A reference to this vector.
  2765. */
  2766. max( v ) {
  2767. this.x = Math.max( this.x, v.x );
  2768. this.y = Math.max( this.y, v.y );
  2769. return this;
  2770. }
  2771. /**
  2772. * If this vector's x or y value is greater than the max vector's x or y
  2773. * value, it is replaced by the corresponding value.
  2774. * If this vector's x or y value is less than the min vector's x or y value,
  2775. * it is replaced by the corresponding value.
  2776. *
  2777. * @param {Vector2} min - The minimum x and y values.
  2778. * @param {Vector2} max - The maximum x and y values in the desired range.
  2779. * @return {Vector2} A reference to this vector.
  2780. */
  2781. clamp( min, max ) {
  2782. // assumes min < max, componentwise
  2783. this.x = clamp( this.x, min.x, max.x );
  2784. this.y = clamp( this.y, min.y, max.y );
  2785. return this;
  2786. }
  2787. /**
  2788. * If this vector's x or y values are greater than the max value, they are
  2789. * replaced by the max value.
  2790. * If this vector's x or y values are less than the min value, they are
  2791. * replaced by the min value.
  2792. *
  2793. * @param {number} minVal - The minimum value the components will be clamped to.
  2794. * @param {number} maxVal - The maximum value the components will be clamped to.
  2795. * @return {Vector2} A reference to this vector.
  2796. */
  2797. clampScalar( minVal, maxVal ) {
  2798. this.x = clamp( this.x, minVal, maxVal );
  2799. this.y = clamp( this.y, minVal, maxVal );
  2800. return this;
  2801. }
  2802. /**
  2803. * If this vector's length is greater than the max value, it is replaced by
  2804. * the max value.
  2805. * If this vector's length is less than the min value, it is replaced by the
  2806. * min value.
  2807. *
  2808. * @param {number} min - The minimum value the vector length will be clamped to.
  2809. * @param {number} max - The maximum value the vector length will be clamped to.
  2810. * @return {Vector2} A reference to this vector.
  2811. */
  2812. clampLength( min, max ) {
  2813. const length = this.length();
  2814. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2815. }
  2816. /**
  2817. * The components of this vector are rounded down to the nearest integer value.
  2818. *
  2819. * @return {Vector2} A reference to this vector.
  2820. */
  2821. floor() {
  2822. this.x = Math.floor( this.x );
  2823. this.y = Math.floor( this.y );
  2824. return this;
  2825. }
  2826. /**
  2827. * The components of this vector are rounded up to the nearest integer value.
  2828. *
  2829. * @return {Vector2} A reference to this vector.
  2830. */
  2831. ceil() {
  2832. this.x = Math.ceil( this.x );
  2833. this.y = Math.ceil( this.y );
  2834. return this;
  2835. }
  2836. /**
  2837. * The components of this vector are rounded to the nearest integer value
  2838. *
  2839. * @return {Vector2} A reference to this vector.
  2840. */
  2841. round() {
  2842. this.x = Math.round( this.x );
  2843. this.y = Math.round( this.y );
  2844. return this;
  2845. }
  2846. /**
  2847. * The components of this vector are rounded towards zero (up if negative,
  2848. * down if positive) to an integer value.
  2849. *
  2850. * @return {Vector2} A reference to this vector.
  2851. */
  2852. roundToZero() {
  2853. this.x = Math.trunc( this.x );
  2854. this.y = Math.trunc( this.y );
  2855. return this;
  2856. }
  2857. /**
  2858. * Inverts this vector - i.e. sets x = -x and y = -y.
  2859. *
  2860. * @return {Vector2} A reference to this vector.
  2861. */
  2862. negate() {
  2863. this.x = - this.x;
  2864. this.y = - this.y;
  2865. return this;
  2866. }
  2867. /**
  2868. * Calculates the dot product of the given vector with this instance.
  2869. *
  2870. * @param {Vector2} v - The vector to compute the dot product with.
  2871. * @return {number} The result of the dot product.
  2872. */
  2873. dot( v ) {
  2874. return this.x * v.x + this.y * v.y;
  2875. }
  2876. /**
  2877. * Calculates the cross product of the given vector with this instance.
  2878. *
  2879. * @param {Vector2} v - The vector to compute the cross product with.
  2880. * @return {number} The result of the cross product.
  2881. */
  2882. cross( v ) {
  2883. return this.x * v.y - this.y * v.x;
  2884. }
  2885. /**
  2886. * Computes the square of the Euclidean length (straight-line length) from
  2887. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2888. * compare the length squared instead as it is slightly more efficient to calculate.
  2889. *
  2890. * @return {number} The square length of this vector.
  2891. */
  2892. lengthSq() {
  2893. return this.x * this.x + this.y * this.y;
  2894. }
  2895. /**
  2896. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2897. *
  2898. * @return {number} The length of this vector.
  2899. */
  2900. length() {
  2901. return Math.sqrt( this.x * this.x + this.y * this.y );
  2902. }
  2903. /**
  2904. * Computes the Manhattan length of this vector.
  2905. *
  2906. * @return {number} The length of this vector.
  2907. */
  2908. manhattanLength() {
  2909. return Math.abs( this.x ) + Math.abs( this.y );
  2910. }
  2911. /**
  2912. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2913. * with the same direction as this one, but with a vector length of `1`.
  2914. *
  2915. * @return {Vector2} A reference to this vector.
  2916. */
  2917. normalize() {
  2918. return this.divideScalar( this.length() || 1 );
  2919. }
  2920. /**
  2921. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2922. *
  2923. * @return {number} The angle in radians.
  2924. */
  2925. angle() {
  2926. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2927. return angle;
  2928. }
  2929. /**
  2930. * Returns the angle between the given vector and this instance in radians.
  2931. *
  2932. * @param {Vector2} v - The vector to compute the angle with.
  2933. * @return {number} The angle in radians.
  2934. */
  2935. angleTo( v ) {
  2936. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2937. if ( denominator === 0 ) return Math.PI / 2;
  2938. const theta = this.dot( v ) / denominator;
  2939. // clamp, to handle numerical problems
  2940. return Math.acos( clamp( theta, -1, 1 ) );
  2941. }
  2942. /**
  2943. * Computes the distance from the given vector to this instance.
  2944. *
  2945. * @param {Vector2} v - The vector to compute the distance to.
  2946. * @return {number} The distance.
  2947. */
  2948. distanceTo( v ) {
  2949. return Math.sqrt( this.distanceToSquared( v ) );
  2950. }
  2951. /**
  2952. * Computes the squared distance from the given vector to this instance.
  2953. * If you are just comparing the distance with another distance, you should compare
  2954. * the distance squared instead as it is slightly more efficient to calculate.
  2955. *
  2956. * @param {Vector2} v - The vector to compute the squared distance to.
  2957. * @return {number} The squared distance.
  2958. */
  2959. distanceToSquared( v ) {
  2960. const dx = this.x - v.x, dy = this.y - v.y;
  2961. return dx * dx + dy * dy;
  2962. }
  2963. /**
  2964. * Computes the Manhattan distance from the given vector to this instance.
  2965. *
  2966. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2967. * @return {number} The Manhattan distance.
  2968. */
  2969. manhattanDistanceTo( v ) {
  2970. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2971. }
  2972. /**
  2973. * Sets this vector to a vector with the same direction as this one, but
  2974. * with the specified length.
  2975. *
  2976. * @param {number} length - The new length of this vector.
  2977. * @return {Vector2} A reference to this vector.
  2978. */
  2979. setLength( length ) {
  2980. return this.normalize().multiplyScalar( length );
  2981. }
  2982. /**
  2983. * Linearly interpolates between the given vector and this instance, where
  2984. * alpha is the percent distance along the line - alpha = 0 will be this
  2985. * vector, and alpha = 1 will be the given one.
  2986. *
  2987. * @param {Vector2} v - The vector to interpolate towards.
  2988. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2989. * @return {Vector2} A reference to this vector.
  2990. */
  2991. lerp( v, alpha ) {
  2992. this.x += ( v.x - this.x ) * alpha;
  2993. this.y += ( v.y - this.y ) * alpha;
  2994. return this;
  2995. }
  2996. /**
  2997. * Linearly interpolates between the given vectors, where alpha is the percent
  2998. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2999. * be the second one. The result is stored in this instance.
  3000. *
  3001. * @param {Vector2} v1 - The first vector.
  3002. * @param {Vector2} v2 - The second vector.
  3003. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3004. * @return {Vector2} A reference to this vector.
  3005. */
  3006. lerpVectors( v1, v2, alpha ) {
  3007. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3008. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3009. return this;
  3010. }
  3011. /**
  3012. * Returns `true` if this vector is equal with the given one.
  3013. *
  3014. * @param {Vector2} v - The vector to test for equality.
  3015. * @return {boolean} Whether this vector is equal with the given one.
  3016. */
  3017. equals( v ) {
  3018. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  3019. }
  3020. /**
  3021. * Sets this vector's x value to be `array[ offset ]` and y
  3022. * value to be `array[ offset + 1 ]`.
  3023. *
  3024. * @param {Array<number>} array - An array holding the vector component values.
  3025. * @param {number} [offset=0] - The offset into the array.
  3026. * @return {Vector2} A reference to this vector.
  3027. */
  3028. fromArray( array, offset = 0 ) {
  3029. this.x = array[ offset ];
  3030. this.y = array[ offset + 1 ];
  3031. return this;
  3032. }
  3033. /**
  3034. * Writes the components of this vector to the given array. If no array is provided,
  3035. * the method returns a new instance.
  3036. *
  3037. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  3038. * @param {number} [offset=0] - Index of the first element in the array.
  3039. * @return {Array<number>} The vector components.
  3040. */
  3041. toArray( array = [], offset = 0 ) {
  3042. array[ offset ] = this.x;
  3043. array[ offset + 1 ] = this.y;
  3044. return array;
  3045. }
  3046. /**
  3047. * Sets the components of this vector from the given buffer attribute.
  3048. *
  3049. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  3050. * @param {number} index - The index into the attribute.
  3051. * @return {Vector2} A reference to this vector.
  3052. */
  3053. fromBufferAttribute( attribute, index ) {
  3054. this.x = attribute.getX( index );
  3055. this.y = attribute.getY( index );
  3056. return this;
  3057. }
  3058. /**
  3059. * Rotates this vector around the given center by the given angle.
  3060. *
  3061. * @param {Vector2} center - The point around which to rotate.
  3062. * @param {number} angle - The angle to rotate, in radians.
  3063. * @return {Vector2} A reference to this vector.
  3064. */
  3065. rotateAround( center, angle ) {
  3066. const c = Math.cos( angle ), s = Math.sin( angle );
  3067. const x = this.x - center.x;
  3068. const y = this.y - center.y;
  3069. this.x = x * c - y * s + center.x;
  3070. this.y = x * s + y * c + center.y;
  3071. return this;
  3072. }
  3073. /**
  3074. * Sets each component of this vector to a pseudo-random value between `0` and
  3075. * `1`, excluding `1`.
  3076. *
  3077. * @return {Vector2} A reference to this vector.
  3078. */
  3079. random() {
  3080. this.x = Math.random();
  3081. this.y = Math.random();
  3082. return this;
  3083. }
  3084. *[ Symbol.iterator ]() {
  3085. yield this.x;
  3086. yield this.y;
  3087. }
  3088. }
  3089. /**
  3090. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  3091. *
  3092. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  3093. * the corresponding order.
  3094. *
  3095. * Note that three.js expects Quaternions to be normalized.
  3096. * ```js
  3097. * const quaternion = new THREE.Quaternion();
  3098. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  3099. *
  3100. * const vector = new THREE.Vector3( 1, 0, 0 );
  3101. * vector.applyQuaternion( quaternion );
  3102. * ```
  3103. */
  3104. class Quaternion {
  3105. /**
  3106. * Constructs a new quaternion.
  3107. *
  3108. * @param {number} [x=0] - The x value of this quaternion.
  3109. * @param {number} [y=0] - The y value of this quaternion.
  3110. * @param {number} [z=0] - The z value of this quaternion.
  3111. * @param {number} [w=1] - The w value of this quaternion.
  3112. */
  3113. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  3114. /**
  3115. * This flag can be used for type testing.
  3116. *
  3117. * @type {boolean}
  3118. * @readonly
  3119. * @default true
  3120. */
  3121. this.isQuaternion = true;
  3122. this._x = x;
  3123. this._y = y;
  3124. this._z = z;
  3125. this._w = w;
  3126. }
  3127. /**
  3128. * Interpolates between two quaternions via SLERP. This implementation assumes the
  3129. * quaternion data are managed in flat arrays.
  3130. *
  3131. * @param {Array<number>} dst - The destination array.
  3132. * @param {number} dstOffset - An offset into the destination array.
  3133. * @param {Array<number>} src0 - The source array of the first quaternion.
  3134. * @param {number} srcOffset0 - An offset into the first source array.
  3135. * @param {Array<number>} src1 - The source array of the second quaternion.
  3136. * @param {number} srcOffset1 - An offset into the second source array.
  3137. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3138. * @see {@link Quaternion#slerp}
  3139. */
  3140. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3141. let x0 = src0[ srcOffset0 + 0 ],
  3142. y0 = src0[ srcOffset0 + 1 ],
  3143. z0 = src0[ srcOffset0 + 2 ],
  3144. w0 = src0[ srcOffset0 + 3 ];
  3145. let x1 = src1[ srcOffset1 + 0 ],
  3146. y1 = src1[ srcOffset1 + 1 ],
  3147. z1 = src1[ srcOffset1 + 2 ],
  3148. w1 = src1[ srcOffset1 + 3 ];
  3149. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3150. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3151. if ( dot < 0 ) {
  3152. x1 = - x1;
  3153. y1 = - y1;
  3154. z1 = - z1;
  3155. w1 = - w1;
  3156. dot = - dot;
  3157. }
  3158. let s = 1 - t;
  3159. if ( dot < 0.9995 ) {
  3160. // slerp
  3161. const theta = Math.acos( dot );
  3162. const sin = Math.sin( theta );
  3163. s = Math.sin( s * theta ) / sin;
  3164. t = Math.sin( t * theta ) / sin;
  3165. x0 = x0 * s + x1 * t;
  3166. y0 = y0 * s + y1 * t;
  3167. z0 = z0 * s + z1 * t;
  3168. w0 = w0 * s + w1 * t;
  3169. } else {
  3170. // for small angles, lerp then normalize
  3171. x0 = x0 * s + x1 * t;
  3172. y0 = y0 * s + y1 * t;
  3173. z0 = z0 * s + z1 * t;
  3174. w0 = w0 * s + w1 * t;
  3175. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3176. x0 *= f;
  3177. y0 *= f;
  3178. z0 *= f;
  3179. w0 *= f;
  3180. }
  3181. }
  3182. dst[ dstOffset ] = x0;
  3183. dst[ dstOffset + 1 ] = y0;
  3184. dst[ dstOffset + 2 ] = z0;
  3185. dst[ dstOffset + 3 ] = w0;
  3186. }
  3187. /**
  3188. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3189. * in flat arrays.
  3190. *
  3191. * @param {Array<number>} dst - The destination array.
  3192. * @param {number} dstOffset - An offset into the destination array.
  3193. * @param {Array<number>} src0 - The source array of the first quaternion.
  3194. * @param {number} srcOffset0 - An offset into the first source array.
  3195. * @param {Array<number>} src1 - The source array of the second quaternion.
  3196. * @param {number} srcOffset1 - An offset into the second source array.
  3197. * @return {Array<number>} The destination array.
  3198. * @see {@link Quaternion#multiplyQuaternions}.
  3199. */
  3200. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3201. const x0 = src0[ srcOffset0 ];
  3202. const y0 = src0[ srcOffset0 + 1 ];
  3203. const z0 = src0[ srcOffset0 + 2 ];
  3204. const w0 = src0[ srcOffset0 + 3 ];
  3205. const x1 = src1[ srcOffset1 ];
  3206. const y1 = src1[ srcOffset1 + 1 ];
  3207. const z1 = src1[ srcOffset1 + 2 ];
  3208. const w1 = src1[ srcOffset1 + 3 ];
  3209. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3210. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3211. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3212. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3213. return dst;
  3214. }
  3215. /**
  3216. * The x value of this quaternion.
  3217. *
  3218. * @type {number}
  3219. * @default 0
  3220. */
  3221. get x() {
  3222. return this._x;
  3223. }
  3224. set x( value ) {
  3225. this._x = value;
  3226. this._onChangeCallback();
  3227. }
  3228. /**
  3229. * The y value of this quaternion.
  3230. *
  3231. * @type {number}
  3232. * @default 0
  3233. */
  3234. get y() {
  3235. return this._y;
  3236. }
  3237. set y( value ) {
  3238. this._y = value;
  3239. this._onChangeCallback();
  3240. }
  3241. /**
  3242. * The z value of this quaternion.
  3243. *
  3244. * @type {number}
  3245. * @default 0
  3246. */
  3247. get z() {
  3248. return this._z;
  3249. }
  3250. set z( value ) {
  3251. this._z = value;
  3252. this._onChangeCallback();
  3253. }
  3254. /**
  3255. * The w value of this quaternion.
  3256. *
  3257. * @type {number}
  3258. * @default 1
  3259. */
  3260. get w() {
  3261. return this._w;
  3262. }
  3263. set w( value ) {
  3264. this._w = value;
  3265. this._onChangeCallback();
  3266. }
  3267. /**
  3268. * Sets the quaternion components.
  3269. *
  3270. * @param {number} x - The x value of this quaternion.
  3271. * @param {number} y - The y value of this quaternion.
  3272. * @param {number} z - The z value of this quaternion.
  3273. * @param {number} w - The w value of this quaternion.
  3274. * @return {Quaternion} A reference to this quaternion.
  3275. */
  3276. set( x, y, z, w ) {
  3277. this._x = x;
  3278. this._y = y;
  3279. this._z = z;
  3280. this._w = w;
  3281. this._onChangeCallback();
  3282. return this;
  3283. }
  3284. /**
  3285. * Returns a new quaternion with copied values from this instance.
  3286. *
  3287. * @return {Quaternion} A clone of this instance.
  3288. */
  3289. clone() {
  3290. return new this.constructor( this._x, this._y, this._z, this._w );
  3291. }
  3292. /**
  3293. * Copies the values of the given quaternion to this instance.
  3294. *
  3295. * @param {Quaternion} quaternion - The quaternion to copy.
  3296. * @return {Quaternion} A reference to this quaternion.
  3297. */
  3298. copy( quaternion ) {
  3299. this._x = quaternion.x;
  3300. this._y = quaternion.y;
  3301. this._z = quaternion.z;
  3302. this._w = quaternion.w;
  3303. this._onChangeCallback();
  3304. return this;
  3305. }
  3306. /**
  3307. * Sets this quaternion from the rotation specified by the given
  3308. * Euler angles.
  3309. *
  3310. * @param {Euler} euler - The Euler angles.
  3311. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3312. * @return {Quaternion} A reference to this quaternion.
  3313. */
  3314. setFromEuler( euler, update = true ) {
  3315. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3316. // http://www.mathworks.com/matlabcentral/fileexchange/
  3317. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3318. // content/SpinCalc.m
  3319. const cos = Math.cos;
  3320. const sin = Math.sin;
  3321. const c1 = cos( x / 2 );
  3322. const c2 = cos( y / 2 );
  3323. const c3 = cos( z / 2 );
  3324. const s1 = sin( x / 2 );
  3325. const s2 = sin( y / 2 );
  3326. const s3 = sin( z / 2 );
  3327. switch ( order ) {
  3328. case 'XYZ':
  3329. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3330. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3331. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3332. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3333. break;
  3334. case 'YXZ':
  3335. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3336. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3337. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3338. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3339. break;
  3340. case 'ZXY':
  3341. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3342. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3343. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3344. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3345. break;
  3346. case 'ZYX':
  3347. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3348. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3349. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3350. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3351. break;
  3352. case 'YZX':
  3353. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3354. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3355. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3356. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3357. break;
  3358. case 'XZY':
  3359. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3360. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3361. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3362. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3363. break;
  3364. default:
  3365. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3366. }
  3367. if ( update === true ) this._onChangeCallback();
  3368. return this;
  3369. }
  3370. /**
  3371. * Sets this quaternion from the given axis and angle.
  3372. *
  3373. * @param {Vector3} axis - The normalized axis.
  3374. * @param {number} angle - The angle in radians.
  3375. * @return {Quaternion} A reference to this quaternion.
  3376. */
  3377. setFromAxisAngle( axis, angle ) {
  3378. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3379. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3380. this._x = axis.x * s;
  3381. this._y = axis.y * s;
  3382. this._z = axis.z * s;
  3383. this._w = Math.cos( halfAngle );
  3384. this._onChangeCallback();
  3385. return this;
  3386. }
  3387. /**
  3388. * Sets this quaternion from the given rotation matrix.
  3389. *
  3390. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3391. * @return {Quaternion} A reference to this quaternion.
  3392. */
  3393. setFromRotationMatrix( m ) {
  3394. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3395. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3396. const te = m.elements,
  3397. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3398. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3399. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3400. trace = m11 + m22 + m33;
  3401. if ( trace > 0 ) {
  3402. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3403. this._w = 0.25 / s;
  3404. this._x = ( m32 - m23 ) * s;
  3405. this._y = ( m13 - m31 ) * s;
  3406. this._z = ( m21 - m12 ) * s;
  3407. } else if ( m11 > m22 && m11 > m33 ) {
  3408. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3409. this._w = ( m32 - m23 ) / s;
  3410. this._x = 0.25 * s;
  3411. this._y = ( m12 + m21 ) / s;
  3412. this._z = ( m13 + m31 ) / s;
  3413. } else if ( m22 > m33 ) {
  3414. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3415. this._w = ( m13 - m31 ) / s;
  3416. this._x = ( m12 + m21 ) / s;
  3417. this._y = 0.25 * s;
  3418. this._z = ( m23 + m32 ) / s;
  3419. } else {
  3420. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3421. this._w = ( m21 - m12 ) / s;
  3422. this._x = ( m13 + m31 ) / s;
  3423. this._y = ( m23 + m32 ) / s;
  3424. this._z = 0.25 * s;
  3425. }
  3426. this._onChangeCallback();
  3427. return this;
  3428. }
  3429. /**
  3430. * Sets this quaternion to the rotation required to rotate the direction vector
  3431. * `vFrom` to the direction vector `vTo`.
  3432. *
  3433. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3434. * @param {Vector3} vTo - The second (normalized) direction vector.
  3435. * @return {Quaternion} A reference to this quaternion.
  3436. */
  3437. setFromUnitVectors( vFrom, vTo ) {
  3438. // assumes direction vectors vFrom and vTo are normalized
  3439. let r = vFrom.dot( vTo ) + 1;
  3440. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3441. // vFrom and vTo point in opposite directions
  3442. r = 0;
  3443. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3444. this._x = - vFrom.y;
  3445. this._y = vFrom.x;
  3446. this._z = 0;
  3447. this._w = r;
  3448. } else {
  3449. this._x = 0;
  3450. this._y = - vFrom.z;
  3451. this._z = vFrom.y;
  3452. this._w = r;
  3453. }
  3454. } else {
  3455. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3456. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3457. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3458. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3459. this._w = r;
  3460. }
  3461. return this.normalize();
  3462. }
  3463. /**
  3464. * Returns the angle between this quaternion and the given one in radians.
  3465. *
  3466. * @param {Quaternion} q - The quaternion to compute the angle with.
  3467. * @return {number} The angle in radians.
  3468. */
  3469. angleTo( q ) {
  3470. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3471. }
  3472. /**
  3473. * Rotates this quaternion by a given angular step to the given quaternion.
  3474. * The method ensures that the final quaternion will not overshoot `q`.
  3475. *
  3476. * @param {Quaternion} q - The target quaternion.
  3477. * @param {number} step - The angular step in radians.
  3478. * @return {Quaternion} A reference to this quaternion.
  3479. */
  3480. rotateTowards( q, step ) {
  3481. const angle = this.angleTo( q );
  3482. if ( angle === 0 ) return this;
  3483. const t = Math.min( 1, step / angle );
  3484. this.slerp( q, t );
  3485. return this;
  3486. }
  3487. /**
  3488. * Sets this quaternion to the identity quaternion; that is, to the
  3489. * quaternion that represents "no rotation".
  3490. *
  3491. * @return {Quaternion} A reference to this quaternion.
  3492. */
  3493. identity() {
  3494. return this.set( 0, 0, 0, 1 );
  3495. }
  3496. /**
  3497. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3498. * quaternion is assumed to have unit length.
  3499. *
  3500. * @return {Quaternion} A reference to this quaternion.
  3501. */
  3502. invert() {
  3503. return this.conjugate();
  3504. }
  3505. /**
  3506. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3507. * quaternion represents the same rotation in the opposite direction about
  3508. * the rotational axis.
  3509. *
  3510. * @return {Quaternion} A reference to this quaternion.
  3511. */
  3512. conjugate() {
  3513. this._x *= -1;
  3514. this._y *= -1;
  3515. this._z *= -1;
  3516. this._onChangeCallback();
  3517. return this;
  3518. }
  3519. /**
  3520. * Calculates the dot product of this quaternion and the given one.
  3521. *
  3522. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3523. * @return {number} The result of the dot product.
  3524. */
  3525. dot( v ) {
  3526. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3527. }
  3528. /**
  3529. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3530. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3531. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3532. * {@link Quaternion#length}.
  3533. *
  3534. * @return {number} The squared Euclidean length.
  3535. */
  3536. lengthSq() {
  3537. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3538. }
  3539. /**
  3540. * Computes the Euclidean length (straight-line length) of this quaternion,
  3541. * considered as a 4 dimensional vector.
  3542. *
  3543. * @return {number} The Euclidean length.
  3544. */
  3545. length() {
  3546. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3547. }
  3548. /**
  3549. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3550. * the same rotation as this one, but has a length equal to `1`.
  3551. *
  3552. * @return {Quaternion} A reference to this quaternion.
  3553. */
  3554. normalize() {
  3555. let l = this.length();
  3556. if ( l === 0 ) {
  3557. this._x = 0;
  3558. this._y = 0;
  3559. this._z = 0;
  3560. this._w = 1;
  3561. } else {
  3562. l = 1 / l;
  3563. this._x = this._x * l;
  3564. this._y = this._y * l;
  3565. this._z = this._z * l;
  3566. this._w = this._w * l;
  3567. }
  3568. this._onChangeCallback();
  3569. return this;
  3570. }
  3571. /**
  3572. * Multiplies this quaternion by the given one.
  3573. *
  3574. * @param {Quaternion} q - The quaternion.
  3575. * @return {Quaternion} A reference to this quaternion.
  3576. */
  3577. multiply( q ) {
  3578. return this.multiplyQuaternions( this, q );
  3579. }
  3580. /**
  3581. * Pre-multiplies this quaternion by the given one.
  3582. *
  3583. * @param {Quaternion} q - The quaternion.
  3584. * @return {Quaternion} A reference to this quaternion.
  3585. */
  3586. premultiply( q ) {
  3587. return this.multiplyQuaternions( q, this );
  3588. }
  3589. /**
  3590. * Multiplies the given quaternions and stores the result in this instance.
  3591. *
  3592. * @param {Quaternion} a - The first quaternion.
  3593. * @param {Quaternion} b - The second quaternion.
  3594. * @return {Quaternion} A reference to this quaternion.
  3595. */
  3596. multiplyQuaternions( a, b ) {
  3597. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3598. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3599. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3600. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3601. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3602. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3603. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3604. this._onChangeCallback();
  3605. return this;
  3606. }
  3607. /**
  3608. * Performs a spherical linear interpolation between this quaternion and the target quaternion.
  3609. *
  3610. * @param {Quaternion} qb - The target quaternion.
  3611. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3612. * @return {Quaternion} A reference to this quaternion.
  3613. */
  3614. slerp( qb, t ) {
  3615. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3616. let dot = this.dot( qb );
  3617. if ( dot < 0 ) {
  3618. x = - x;
  3619. y = - y;
  3620. z = - z;
  3621. w = - w;
  3622. dot = - dot;
  3623. }
  3624. let s = 1 - t;
  3625. if ( dot < 0.9995 ) {
  3626. // slerp
  3627. const theta = Math.acos( dot );
  3628. const sin = Math.sin( theta );
  3629. s = Math.sin( s * theta ) / sin;
  3630. t = Math.sin( t * theta ) / sin;
  3631. this._x = this._x * s + x * t;
  3632. this._y = this._y * s + y * t;
  3633. this._z = this._z * s + z * t;
  3634. this._w = this._w * s + w * t;
  3635. this._onChangeCallback();
  3636. } else {
  3637. // for small angles, lerp then normalize
  3638. this._x = this._x * s + x * t;
  3639. this._y = this._y * s + y * t;
  3640. this._z = this._z * s + z * t;
  3641. this._w = this._w * s + w * t;
  3642. this.normalize(); // normalize calls _onChangeCallback()
  3643. }
  3644. return this;
  3645. }
  3646. /**
  3647. * Performs a spherical linear interpolation between the given quaternions
  3648. * and stores the result in this quaternion.
  3649. *
  3650. * @param {Quaternion} qa - The source quaternion.
  3651. * @param {Quaternion} qb - The target quaternion.
  3652. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3653. * @return {Quaternion} A reference to this quaternion.
  3654. */
  3655. slerpQuaternions( qa, qb, t ) {
  3656. return this.copy( qa ).slerp( qb, t );
  3657. }
  3658. /**
  3659. * Sets this quaternion to a uniformly random, normalized quaternion.
  3660. *
  3661. * @return {Quaternion} A reference to this quaternion.
  3662. */
  3663. random() {
  3664. // Ken Shoemake
  3665. // Uniform random rotations
  3666. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3667. const theta1 = 2 * Math.PI * Math.random();
  3668. const theta2 = 2 * Math.PI * Math.random();
  3669. const x0 = Math.random();
  3670. const r1 = Math.sqrt( 1 - x0 );
  3671. const r2 = Math.sqrt( x0 );
  3672. return this.set(
  3673. r1 * Math.sin( theta1 ),
  3674. r1 * Math.cos( theta1 ),
  3675. r2 * Math.sin( theta2 ),
  3676. r2 * Math.cos( theta2 ),
  3677. );
  3678. }
  3679. /**
  3680. * Returns `true` if this quaternion is equal with the given one.
  3681. *
  3682. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3683. * @return {boolean} Whether this quaternion is equal with the given one.
  3684. */
  3685. equals( quaternion ) {
  3686. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3687. }
  3688. /**
  3689. * Sets this quaternion's components from the given array.
  3690. *
  3691. * @param {Array<number>} array - An array holding the quaternion component values.
  3692. * @param {number} [offset=0] - The offset into the array.
  3693. * @return {Quaternion} A reference to this quaternion.
  3694. */
  3695. fromArray( array, offset = 0 ) {
  3696. this._x = array[ offset ];
  3697. this._y = array[ offset + 1 ];
  3698. this._z = array[ offset + 2 ];
  3699. this._w = array[ offset + 3 ];
  3700. this._onChangeCallback();
  3701. return this;
  3702. }
  3703. /**
  3704. * Writes the components of this quaternion to the given array. If no array is provided,
  3705. * the method returns a new instance.
  3706. *
  3707. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3708. * @param {number} [offset=0] - Index of the first element in the array.
  3709. * @return {Array<number>} The quaternion components.
  3710. */
  3711. toArray( array = [], offset = 0 ) {
  3712. array[ offset ] = this._x;
  3713. array[ offset + 1 ] = this._y;
  3714. array[ offset + 2 ] = this._z;
  3715. array[ offset + 3 ] = this._w;
  3716. return array;
  3717. }
  3718. /**
  3719. * Sets the components of this quaternion from the given buffer attribute.
  3720. *
  3721. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3722. * @param {number} index - The index into the attribute.
  3723. * @return {Quaternion} A reference to this quaternion.
  3724. */
  3725. fromBufferAttribute( attribute, index ) {
  3726. this._x = attribute.getX( index );
  3727. this._y = attribute.getY( index );
  3728. this._z = attribute.getZ( index );
  3729. this._w = attribute.getW( index );
  3730. this._onChangeCallback();
  3731. return this;
  3732. }
  3733. /**
  3734. * This methods defines the serialization result of this class. Returns the
  3735. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3736. *
  3737. * @return {Array<number>} The serialized quaternion.
  3738. */
  3739. toJSON() {
  3740. return this.toArray();
  3741. }
  3742. _onChange( callback ) {
  3743. this._onChangeCallback = callback;
  3744. return this;
  3745. }
  3746. _onChangeCallback() {}
  3747. *[ Symbol.iterator ]() {
  3748. yield this._x;
  3749. yield this._y;
  3750. yield this._z;
  3751. yield this._w;
  3752. }
  3753. }
  3754. /**
  3755. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3756. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3757. *
  3758. * - A point in 3D space.
  3759. * - A direction and length in 3D space. In three.js the length will
  3760. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3761. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3762. * - Any arbitrary ordered triplet of numbers.
  3763. *
  3764. * There are other things a 3D vector can be used to represent, such as
  3765. * momentum vectors and so on, however these are the most
  3766. * common uses in three.js.
  3767. *
  3768. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3769. * the corresponding order.
  3770. * ```js
  3771. * const a = new THREE.Vector3( 0, 1, 0 );
  3772. *
  3773. * //no arguments; will be initialised to (0, 0, 0)
  3774. * const b = new THREE.Vector3( );
  3775. *
  3776. * const d = a.distanceTo( b );
  3777. * ```
  3778. */
  3779. class Vector3 {
  3780. /**
  3781. * Constructs a new 3D vector.
  3782. *
  3783. * @param {number} [x=0] - The x value of this vector.
  3784. * @param {number} [y=0] - The y value of this vector.
  3785. * @param {number} [z=0] - The z value of this vector.
  3786. */
  3787. constructor( x = 0, y = 0, z = 0 ) {
  3788. /**
  3789. * This flag can be used for type testing.
  3790. *
  3791. * @type {boolean}
  3792. * @readonly
  3793. * @default true
  3794. */
  3795. Vector3.prototype.isVector3 = true;
  3796. /**
  3797. * The x value of this vector.
  3798. *
  3799. * @type {number}
  3800. */
  3801. this.x = x;
  3802. /**
  3803. * The y value of this vector.
  3804. *
  3805. * @type {number}
  3806. */
  3807. this.y = y;
  3808. /**
  3809. * The z value of this vector.
  3810. *
  3811. * @type {number}
  3812. */
  3813. this.z = z;
  3814. }
  3815. /**
  3816. * Sets the vector components.
  3817. *
  3818. * @param {number} x - The value of the x component.
  3819. * @param {number} y - The value of the y component.
  3820. * @param {number} z - The value of the z component.
  3821. * @return {Vector3} A reference to this vector.
  3822. */
  3823. set( x, y, z ) {
  3824. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3825. this.x = x;
  3826. this.y = y;
  3827. this.z = z;
  3828. return this;
  3829. }
  3830. /**
  3831. * Sets the vector components to the same value.
  3832. *
  3833. * @param {number} scalar - The value to set for all vector components.
  3834. * @return {Vector3} A reference to this vector.
  3835. */
  3836. setScalar( scalar ) {
  3837. this.x = scalar;
  3838. this.y = scalar;
  3839. this.z = scalar;
  3840. return this;
  3841. }
  3842. /**
  3843. * Sets the vector's x component to the given value.
  3844. *
  3845. * @param {number} x - The value to set.
  3846. * @return {Vector3} A reference to this vector.
  3847. */
  3848. setX( x ) {
  3849. this.x = x;
  3850. return this;
  3851. }
  3852. /**
  3853. * Sets the vector's y component to the given value.
  3854. *
  3855. * @param {number} y - The value to set.
  3856. * @return {Vector3} A reference to this vector.
  3857. */
  3858. setY( y ) {
  3859. this.y = y;
  3860. return this;
  3861. }
  3862. /**
  3863. * Sets the vector's z component to the given value.
  3864. *
  3865. * @param {number} z - The value to set.
  3866. * @return {Vector3} A reference to this vector.
  3867. */
  3868. setZ( z ) {
  3869. this.z = z;
  3870. return this;
  3871. }
  3872. /**
  3873. * Allows to set a vector component with an index.
  3874. *
  3875. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3876. * @param {number} value - The value to set.
  3877. * @return {Vector3} A reference to this vector.
  3878. */
  3879. setComponent( index, value ) {
  3880. switch ( index ) {
  3881. case 0: this.x = value; break;
  3882. case 1: this.y = value; break;
  3883. case 2: this.z = value; break;
  3884. default: throw new Error( 'index is out of range: ' + index );
  3885. }
  3886. return this;
  3887. }
  3888. /**
  3889. * Returns the value of the vector component which matches the given index.
  3890. *
  3891. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3892. * @return {number} A vector component value.
  3893. */
  3894. getComponent( index ) {
  3895. switch ( index ) {
  3896. case 0: return this.x;
  3897. case 1: return this.y;
  3898. case 2: return this.z;
  3899. default: throw new Error( 'index is out of range: ' + index );
  3900. }
  3901. }
  3902. /**
  3903. * Returns a new vector with copied values from this instance.
  3904. *
  3905. * @return {Vector3} A clone of this instance.
  3906. */
  3907. clone() {
  3908. return new this.constructor( this.x, this.y, this.z );
  3909. }
  3910. /**
  3911. * Copies the values of the given vector to this instance.
  3912. *
  3913. * @param {Vector3} v - The vector to copy.
  3914. * @return {Vector3} A reference to this vector.
  3915. */
  3916. copy( v ) {
  3917. this.x = v.x;
  3918. this.y = v.y;
  3919. this.z = v.z;
  3920. return this;
  3921. }
  3922. /**
  3923. * Adds the given vector to this instance.
  3924. *
  3925. * @param {Vector3} v - The vector to add.
  3926. * @return {Vector3} A reference to this vector.
  3927. */
  3928. add( v ) {
  3929. this.x += v.x;
  3930. this.y += v.y;
  3931. this.z += v.z;
  3932. return this;
  3933. }
  3934. /**
  3935. * Adds the given scalar value to all components of this instance.
  3936. *
  3937. * @param {number} s - The scalar to add.
  3938. * @return {Vector3} A reference to this vector.
  3939. */
  3940. addScalar( s ) {
  3941. this.x += s;
  3942. this.y += s;
  3943. this.z += s;
  3944. return this;
  3945. }
  3946. /**
  3947. * Adds the given vectors and stores the result in this instance.
  3948. *
  3949. * @param {Vector3} a - The first vector.
  3950. * @param {Vector3} b - The second vector.
  3951. * @return {Vector3} A reference to this vector.
  3952. */
  3953. addVectors( a, b ) {
  3954. this.x = a.x + b.x;
  3955. this.y = a.y + b.y;
  3956. this.z = a.z + b.z;
  3957. return this;
  3958. }
  3959. /**
  3960. * Adds the given vector scaled by the given factor to this instance.
  3961. *
  3962. * @param {Vector3|Vector4} v - The vector.
  3963. * @param {number} s - The factor that scales `v`.
  3964. * @return {Vector3} A reference to this vector.
  3965. */
  3966. addScaledVector( v, s ) {
  3967. this.x += v.x * s;
  3968. this.y += v.y * s;
  3969. this.z += v.z * s;
  3970. return this;
  3971. }
  3972. /**
  3973. * Subtracts the given vector from this instance.
  3974. *
  3975. * @param {Vector3} v - The vector to subtract.
  3976. * @return {Vector3} A reference to this vector.
  3977. */
  3978. sub( v ) {
  3979. this.x -= v.x;
  3980. this.y -= v.y;
  3981. this.z -= v.z;
  3982. return this;
  3983. }
  3984. /**
  3985. * Subtracts the given scalar value from all components of this instance.
  3986. *
  3987. * @param {number} s - The scalar to subtract.
  3988. * @return {Vector3} A reference to this vector.
  3989. */
  3990. subScalar( s ) {
  3991. this.x -= s;
  3992. this.y -= s;
  3993. this.z -= s;
  3994. return this;
  3995. }
  3996. /**
  3997. * Subtracts the given vectors and stores the result in this instance.
  3998. *
  3999. * @param {Vector3} a - The first vector.
  4000. * @param {Vector3} b - The second vector.
  4001. * @return {Vector3} A reference to this vector.
  4002. */
  4003. subVectors( a, b ) {
  4004. this.x = a.x - b.x;
  4005. this.y = a.y - b.y;
  4006. this.z = a.z - b.z;
  4007. return this;
  4008. }
  4009. /**
  4010. * Multiplies the given vector with this instance.
  4011. *
  4012. * @param {Vector3} v - The vector to multiply.
  4013. * @return {Vector3} A reference to this vector.
  4014. */
  4015. multiply( v ) {
  4016. this.x *= v.x;
  4017. this.y *= v.y;
  4018. this.z *= v.z;
  4019. return this;
  4020. }
  4021. /**
  4022. * Multiplies the given scalar value with all components of this instance.
  4023. *
  4024. * @param {number} scalar - The scalar to multiply.
  4025. * @return {Vector3} A reference to this vector.
  4026. */
  4027. multiplyScalar( scalar ) {
  4028. this.x *= scalar;
  4029. this.y *= scalar;
  4030. this.z *= scalar;
  4031. return this;
  4032. }
  4033. /**
  4034. * Multiplies the given vectors and stores the result in this instance.
  4035. *
  4036. * @param {Vector3} a - The first vector.
  4037. * @param {Vector3} b - The second vector.
  4038. * @return {Vector3} A reference to this vector.
  4039. */
  4040. multiplyVectors( a, b ) {
  4041. this.x = a.x * b.x;
  4042. this.y = a.y * b.y;
  4043. this.z = a.z * b.z;
  4044. return this;
  4045. }
  4046. /**
  4047. * Applies the given Euler rotation to this vector.
  4048. *
  4049. * @param {Euler} euler - The Euler angles.
  4050. * @return {Vector3} A reference to this vector.
  4051. */
  4052. applyEuler( euler ) {
  4053. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  4054. }
  4055. /**
  4056. * Applies a rotation specified by an axis and an angle to this vector.
  4057. *
  4058. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  4059. * @param {number} angle - The angle in radians.
  4060. * @return {Vector3} A reference to this vector.
  4061. */
  4062. applyAxisAngle( axis, angle ) {
  4063. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  4064. }
  4065. /**
  4066. * Multiplies this vector with the given 3x3 matrix.
  4067. *
  4068. * @param {Matrix3} m - The 3x3 matrix.
  4069. * @return {Vector3} A reference to this vector.
  4070. */
  4071. applyMatrix3( m ) {
  4072. const x = this.x, y = this.y, z = this.z;
  4073. const e = m.elements;
  4074. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  4075. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  4076. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  4077. return this;
  4078. }
  4079. /**
  4080. * Multiplies this vector by the given normal matrix and normalizes
  4081. * the result.
  4082. *
  4083. * @param {Matrix3} m - The normal matrix.
  4084. * @return {Vector3} A reference to this vector.
  4085. */
  4086. applyNormalMatrix( m ) {
  4087. return this.applyMatrix3( m ).normalize();
  4088. }
  4089. /**
  4090. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  4091. * divides by perspective.
  4092. *
  4093. * @param {Matrix4} m - The matrix to apply.
  4094. * @return {Vector3} A reference to this vector.
  4095. */
  4096. applyMatrix4( m ) {
  4097. const x = this.x, y = this.y, z = this.z;
  4098. const e = m.elements;
  4099. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  4100. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  4101. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  4102. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  4103. return this;
  4104. }
  4105. /**
  4106. * Applies the given Quaternion to this vector.
  4107. *
  4108. * @param {Quaternion} q - The Quaternion.
  4109. * @return {Vector3} A reference to this vector.
  4110. */
  4111. applyQuaternion( q ) {
  4112. // quaternion q is assumed to have unit length
  4113. const vx = this.x, vy = this.y, vz = this.z;
  4114. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  4115. // t = 2 * cross( q.xyz, v );
  4116. const tx = 2 * ( qy * vz - qz * vy );
  4117. const ty = 2 * ( qz * vx - qx * vz );
  4118. const tz = 2 * ( qx * vy - qy * vx );
  4119. // v + q.w * t + cross( q.xyz, t );
  4120. this.x = vx + qw * tx + qy * tz - qz * ty;
  4121. this.y = vy + qw * ty + qz * tx - qx * tz;
  4122. this.z = vz + qw * tz + qx * ty - qy * tx;
  4123. return this;
  4124. }
  4125. /**
  4126. * Projects this vector from world space into the camera's normalized
  4127. * device coordinate (NDC) space.
  4128. *
  4129. * @param {Camera} camera - The camera.
  4130. * @return {Vector3} A reference to this vector.
  4131. */
  4132. project( camera ) {
  4133. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4134. }
  4135. /**
  4136. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4137. * space into world space.
  4138. *
  4139. * @param {Camera} camera - The camera.
  4140. * @return {Vector3} A reference to this vector.
  4141. */
  4142. unproject( camera ) {
  4143. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4144. }
  4145. /**
  4146. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4147. * subset of the given 4x4 matrix and then normalizes the result.
  4148. *
  4149. * @param {Matrix4} m - The matrix.
  4150. * @return {Vector3} A reference to this vector.
  4151. */
  4152. transformDirection( m ) {
  4153. // input: THREE.Matrix4 affine matrix
  4154. // vector interpreted as a direction
  4155. const x = this.x, y = this.y, z = this.z;
  4156. const e = m.elements;
  4157. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4158. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4159. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4160. return this.normalize();
  4161. }
  4162. /**
  4163. * Divides this instance by the given vector.
  4164. *
  4165. * @param {Vector3} v - The vector to divide.
  4166. * @return {Vector3} A reference to this vector.
  4167. */
  4168. divide( v ) {
  4169. this.x /= v.x;
  4170. this.y /= v.y;
  4171. this.z /= v.z;
  4172. return this;
  4173. }
  4174. /**
  4175. * Divides this vector by the given scalar.
  4176. *
  4177. * @param {number} scalar - The scalar to divide.
  4178. * @return {Vector3} A reference to this vector.
  4179. */
  4180. divideScalar( scalar ) {
  4181. return this.multiplyScalar( 1 / scalar );
  4182. }
  4183. /**
  4184. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4185. * value, replace that value with the corresponding min value.
  4186. *
  4187. * @param {Vector3} v - The vector.
  4188. * @return {Vector3} A reference to this vector.
  4189. */
  4190. min( v ) {
  4191. this.x = Math.min( this.x, v.x );
  4192. this.y = Math.min( this.y, v.y );
  4193. this.z = Math.min( this.z, v.z );
  4194. return this;
  4195. }
  4196. /**
  4197. * If this vector's x, y or z value is less than the given vector's x, y or z
  4198. * value, replace that value with the corresponding max value.
  4199. *
  4200. * @param {Vector3} v - The vector.
  4201. * @return {Vector3} A reference to this vector.
  4202. */
  4203. max( v ) {
  4204. this.x = Math.max( this.x, v.x );
  4205. this.y = Math.max( this.y, v.y );
  4206. this.z = Math.max( this.z, v.z );
  4207. return this;
  4208. }
  4209. /**
  4210. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4211. * value, it is replaced by the corresponding value.
  4212. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4213. * it is replaced by the corresponding value.
  4214. *
  4215. * @param {Vector3} min - The minimum x, y and z values.
  4216. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4217. * @return {Vector3} A reference to this vector.
  4218. */
  4219. clamp( min, max ) {
  4220. // assumes min < max, componentwise
  4221. this.x = clamp( this.x, min.x, max.x );
  4222. this.y = clamp( this.y, min.y, max.y );
  4223. this.z = clamp( this.z, min.z, max.z );
  4224. return this;
  4225. }
  4226. /**
  4227. * If this vector's x, y or z values are greater than the max value, they are
  4228. * replaced by the max value.
  4229. * If this vector's x, y or z values are less than the min value, they are
  4230. * replaced by the min value.
  4231. *
  4232. * @param {number} minVal - The minimum value the components will be clamped to.
  4233. * @param {number} maxVal - The maximum value the components will be clamped to.
  4234. * @return {Vector3} A reference to this vector.
  4235. */
  4236. clampScalar( minVal, maxVal ) {
  4237. this.x = clamp( this.x, minVal, maxVal );
  4238. this.y = clamp( this.y, minVal, maxVal );
  4239. this.z = clamp( this.z, minVal, maxVal );
  4240. return this;
  4241. }
  4242. /**
  4243. * If this vector's length is greater than the max value, it is replaced by
  4244. * the max value.
  4245. * If this vector's length is less than the min value, it is replaced by the
  4246. * min value.
  4247. *
  4248. * @param {number} min - The minimum value the vector length will be clamped to.
  4249. * @param {number} max - The maximum value the vector length will be clamped to.
  4250. * @return {Vector3} A reference to this vector.
  4251. */
  4252. clampLength( min, max ) {
  4253. const length = this.length();
  4254. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4255. }
  4256. /**
  4257. * The components of this vector are rounded down to the nearest integer value.
  4258. *
  4259. * @return {Vector3} A reference to this vector.
  4260. */
  4261. floor() {
  4262. this.x = Math.floor( this.x );
  4263. this.y = Math.floor( this.y );
  4264. this.z = Math.floor( this.z );
  4265. return this;
  4266. }
  4267. /**
  4268. * The components of this vector are rounded up to the nearest integer value.
  4269. *
  4270. * @return {Vector3} A reference to this vector.
  4271. */
  4272. ceil() {
  4273. this.x = Math.ceil( this.x );
  4274. this.y = Math.ceil( this.y );
  4275. this.z = Math.ceil( this.z );
  4276. return this;
  4277. }
  4278. /**
  4279. * The components of this vector are rounded to the nearest integer value
  4280. *
  4281. * @return {Vector3} A reference to this vector.
  4282. */
  4283. round() {
  4284. this.x = Math.round( this.x );
  4285. this.y = Math.round( this.y );
  4286. this.z = Math.round( this.z );
  4287. return this;
  4288. }
  4289. /**
  4290. * The components of this vector are rounded towards zero (up if negative,
  4291. * down if positive) to an integer value.
  4292. *
  4293. * @return {Vector3} A reference to this vector.
  4294. */
  4295. roundToZero() {
  4296. this.x = Math.trunc( this.x );
  4297. this.y = Math.trunc( this.y );
  4298. this.z = Math.trunc( this.z );
  4299. return this;
  4300. }
  4301. /**
  4302. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4303. *
  4304. * @return {Vector3} A reference to this vector.
  4305. */
  4306. negate() {
  4307. this.x = - this.x;
  4308. this.y = - this.y;
  4309. this.z = - this.z;
  4310. return this;
  4311. }
  4312. /**
  4313. * Calculates the dot product of the given vector with this instance.
  4314. *
  4315. * @param {Vector3} v - The vector to compute the dot product with.
  4316. * @return {number} The result of the dot product.
  4317. */
  4318. dot( v ) {
  4319. return this.x * v.x + this.y * v.y + this.z * v.z;
  4320. }
  4321. /**
  4322. * Computes the square of the Euclidean length (straight-line length) from
  4323. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4324. * compare the length squared instead as it is slightly more efficient to calculate.
  4325. *
  4326. * @return {number} The square length of this vector.
  4327. */
  4328. lengthSq() {
  4329. return this.x * this.x + this.y * this.y + this.z * this.z;
  4330. }
  4331. /**
  4332. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4333. *
  4334. * @return {number} The length of this vector.
  4335. */
  4336. length() {
  4337. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4338. }
  4339. /**
  4340. * Computes the Manhattan length of this vector.
  4341. *
  4342. * @return {number} The length of this vector.
  4343. */
  4344. manhattanLength() {
  4345. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4346. }
  4347. /**
  4348. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4349. * with the same direction as this one, but with a vector length of `1`.
  4350. *
  4351. * @return {Vector3} A reference to this vector.
  4352. */
  4353. normalize() {
  4354. return this.divideScalar( this.length() || 1 );
  4355. }
  4356. /**
  4357. * Sets this vector to a vector with the same direction as this one, but
  4358. * with the specified length.
  4359. *
  4360. * @param {number} length - The new length of this vector.
  4361. * @return {Vector3} A reference to this vector.
  4362. */
  4363. setLength( length ) {
  4364. return this.normalize().multiplyScalar( length );
  4365. }
  4366. /**
  4367. * Linearly interpolates between the given vector and this instance, where
  4368. * alpha is the percent distance along the line - alpha = 0 will be this
  4369. * vector, and alpha = 1 will be the given one.
  4370. *
  4371. * @param {Vector3} v - The vector to interpolate towards.
  4372. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4373. * @return {Vector3} A reference to this vector.
  4374. */
  4375. lerp( v, alpha ) {
  4376. this.x += ( v.x - this.x ) * alpha;
  4377. this.y += ( v.y - this.y ) * alpha;
  4378. this.z += ( v.z - this.z ) * alpha;
  4379. return this;
  4380. }
  4381. /**
  4382. * Linearly interpolates between the given vectors, where alpha is the percent
  4383. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4384. * be the second one. The result is stored in this instance.
  4385. *
  4386. * @param {Vector3} v1 - The first vector.
  4387. * @param {Vector3} v2 - The second vector.
  4388. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4389. * @return {Vector3} A reference to this vector.
  4390. */
  4391. lerpVectors( v1, v2, alpha ) {
  4392. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4393. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4394. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4395. return this;
  4396. }
  4397. /**
  4398. * Calculates the cross product of the given vector with this instance.
  4399. *
  4400. * @param {Vector3} v - The vector to compute the cross product with.
  4401. * @return {Vector3} The result of the cross product.
  4402. */
  4403. cross( v ) {
  4404. return this.crossVectors( this, v );
  4405. }
  4406. /**
  4407. * Calculates the cross product of the given vectors and stores the result
  4408. * in this instance.
  4409. *
  4410. * @param {Vector3} a - The first vector.
  4411. * @param {Vector3} b - The second vector.
  4412. * @return {Vector3} A reference to this vector.
  4413. */
  4414. crossVectors( a, b ) {
  4415. const ax = a.x, ay = a.y, az = a.z;
  4416. const bx = b.x, by = b.y, bz = b.z;
  4417. this.x = ay * bz - az * by;
  4418. this.y = az * bx - ax * bz;
  4419. this.z = ax * by - ay * bx;
  4420. return this;
  4421. }
  4422. /**
  4423. * Projects this vector onto the given one.
  4424. *
  4425. * @param {Vector3} v - The vector to project to.
  4426. * @return {Vector3} A reference to this vector.
  4427. */
  4428. projectOnVector( v ) {
  4429. const denominator = v.lengthSq();
  4430. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4431. const scalar = v.dot( this ) / denominator;
  4432. return this.copy( v ).multiplyScalar( scalar );
  4433. }
  4434. /**
  4435. * Projects this vector onto a plane by subtracting this
  4436. * vector projected onto the plane's normal from this vector.
  4437. *
  4438. * @param {Vector3} planeNormal - The plane normal.
  4439. * @return {Vector3} A reference to this vector.
  4440. */
  4441. projectOnPlane( planeNormal ) {
  4442. _vector$c.copy( this ).projectOnVector( planeNormal );
  4443. return this.sub( _vector$c );
  4444. }
  4445. /**
  4446. * Reflects this vector off a plane orthogonal to the given normal vector.
  4447. *
  4448. * @param {Vector3} normal - The (normalized) normal vector.
  4449. * @return {Vector3} A reference to this vector.
  4450. */
  4451. reflect( normal ) {
  4452. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4453. }
  4454. /**
  4455. * Returns the angle between the given vector and this instance in radians.
  4456. *
  4457. * @param {Vector3} v - The vector to compute the angle with.
  4458. * @return {number} The angle in radians.
  4459. */
  4460. angleTo( v ) {
  4461. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4462. if ( denominator === 0 ) return Math.PI / 2;
  4463. const theta = this.dot( v ) / denominator;
  4464. // clamp, to handle numerical problems
  4465. return Math.acos( clamp( theta, -1, 1 ) );
  4466. }
  4467. /**
  4468. * Computes the distance from the given vector to this instance.
  4469. *
  4470. * @param {Vector3} v - The vector to compute the distance to.
  4471. * @return {number} The distance.
  4472. */
  4473. distanceTo( v ) {
  4474. return Math.sqrt( this.distanceToSquared( v ) );
  4475. }
  4476. /**
  4477. * Computes the squared distance from the given vector to this instance.
  4478. * If you are just comparing the distance with another distance, you should compare
  4479. * the distance squared instead as it is slightly more efficient to calculate.
  4480. *
  4481. * @param {Vector3} v - The vector to compute the squared distance to.
  4482. * @return {number} The squared distance.
  4483. */
  4484. distanceToSquared( v ) {
  4485. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4486. return dx * dx + dy * dy + dz * dz;
  4487. }
  4488. /**
  4489. * Computes the Manhattan distance from the given vector to this instance.
  4490. *
  4491. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4492. * @return {number} The Manhattan distance.
  4493. */
  4494. manhattanDistanceTo( v ) {
  4495. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4496. }
  4497. /**
  4498. * Sets the vector components from the given spherical coordinates.
  4499. *
  4500. * @param {Spherical} s - The spherical coordinates.
  4501. * @return {Vector3} A reference to this vector.
  4502. */
  4503. setFromSpherical( s ) {
  4504. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4505. }
  4506. /**
  4507. * Sets the vector components from the given spherical coordinates.
  4508. *
  4509. * @param {number} radius - The radius.
  4510. * @param {number} phi - The phi angle in radians.
  4511. * @param {number} theta - The theta angle in radians.
  4512. * @return {Vector3} A reference to this vector.
  4513. */
  4514. setFromSphericalCoords( radius, phi, theta ) {
  4515. const sinPhiRadius = Math.sin( phi ) * radius;
  4516. this.x = sinPhiRadius * Math.sin( theta );
  4517. this.y = Math.cos( phi ) * radius;
  4518. this.z = sinPhiRadius * Math.cos( theta );
  4519. return this;
  4520. }
  4521. /**
  4522. * Sets the vector components from the given cylindrical coordinates.
  4523. *
  4524. * @param {Cylindrical} c - The cylindrical coordinates.
  4525. * @return {Vector3} A reference to this vector.
  4526. */
  4527. setFromCylindrical( c ) {
  4528. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4529. }
  4530. /**
  4531. * Sets the vector components from the given cylindrical coordinates.
  4532. *
  4533. * @param {number} radius - The radius.
  4534. * @param {number} theta - The theta angle in radians.
  4535. * @param {number} y - The y value.
  4536. * @return {Vector3} A reference to this vector.
  4537. */
  4538. setFromCylindricalCoords( radius, theta, y ) {
  4539. this.x = radius * Math.sin( theta );
  4540. this.y = y;
  4541. this.z = radius * Math.cos( theta );
  4542. return this;
  4543. }
  4544. /**
  4545. * Sets the vector components to the position elements of the
  4546. * given transformation matrix.
  4547. *
  4548. * @param {Matrix4} m - The 4x4 matrix.
  4549. * @return {Vector3} A reference to this vector.
  4550. */
  4551. setFromMatrixPosition( m ) {
  4552. const e = m.elements;
  4553. this.x = e[ 12 ];
  4554. this.y = e[ 13 ];
  4555. this.z = e[ 14 ];
  4556. return this;
  4557. }
  4558. /**
  4559. * Sets the vector components to the scale elements of the
  4560. * given transformation matrix.
  4561. *
  4562. * @param {Matrix4} m - The 4x4 matrix.
  4563. * @return {Vector3} A reference to this vector.
  4564. */
  4565. setFromMatrixScale( m ) {
  4566. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4567. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4568. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4569. this.x = sx;
  4570. this.y = sy;
  4571. this.z = sz;
  4572. return this;
  4573. }
  4574. /**
  4575. * Sets the vector components from the specified matrix column.
  4576. *
  4577. * @param {Matrix4} m - The 4x4 matrix.
  4578. * @param {number} index - The column index.
  4579. * @return {Vector3} A reference to this vector.
  4580. */
  4581. setFromMatrixColumn( m, index ) {
  4582. return this.fromArray( m.elements, index * 4 );
  4583. }
  4584. /**
  4585. * Sets the vector components from the specified matrix column.
  4586. *
  4587. * @param {Matrix3} m - The 3x3 matrix.
  4588. * @param {number} index - The column index.
  4589. * @return {Vector3} A reference to this vector.
  4590. */
  4591. setFromMatrix3Column( m, index ) {
  4592. return this.fromArray( m.elements, index * 3 );
  4593. }
  4594. /**
  4595. * Sets the vector components from the given Euler angles.
  4596. *
  4597. * @param {Euler} e - The Euler angles to set.
  4598. * @return {Vector3} A reference to this vector.
  4599. */
  4600. setFromEuler( e ) {
  4601. this.x = e._x;
  4602. this.y = e._y;
  4603. this.z = e._z;
  4604. return this;
  4605. }
  4606. /**
  4607. * Sets the vector components from the RGB components of the
  4608. * given color.
  4609. *
  4610. * @param {Color} c - The color to set.
  4611. * @return {Vector3} A reference to this vector.
  4612. */
  4613. setFromColor( c ) {
  4614. this.x = c.r;
  4615. this.y = c.g;
  4616. this.z = c.b;
  4617. return this;
  4618. }
  4619. /**
  4620. * Returns `true` if this vector is equal with the given one.
  4621. *
  4622. * @param {Vector3} v - The vector to test for equality.
  4623. * @return {boolean} Whether this vector is equal with the given one.
  4624. */
  4625. equals( v ) {
  4626. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4627. }
  4628. /**
  4629. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4630. * and z value to be `array[ offset + 2 ]`.
  4631. *
  4632. * @param {Array<number>} array - An array holding the vector component values.
  4633. * @param {number} [offset=0] - The offset into the array.
  4634. * @return {Vector3} A reference to this vector.
  4635. */
  4636. fromArray( array, offset = 0 ) {
  4637. this.x = array[ offset ];
  4638. this.y = array[ offset + 1 ];
  4639. this.z = array[ offset + 2 ];
  4640. return this;
  4641. }
  4642. /**
  4643. * Writes the components of this vector to the given array. If no array is provided,
  4644. * the method returns a new instance.
  4645. *
  4646. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4647. * @param {number} [offset=0] - Index of the first element in the array.
  4648. * @return {Array<number>} The vector components.
  4649. */
  4650. toArray( array = [], offset = 0 ) {
  4651. array[ offset ] = this.x;
  4652. array[ offset + 1 ] = this.y;
  4653. array[ offset + 2 ] = this.z;
  4654. return array;
  4655. }
  4656. /**
  4657. * Sets the components of this vector from the given buffer attribute.
  4658. *
  4659. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4660. * @param {number} index - The index into the attribute.
  4661. * @return {Vector3} A reference to this vector.
  4662. */
  4663. fromBufferAttribute( attribute, index ) {
  4664. this.x = attribute.getX( index );
  4665. this.y = attribute.getY( index );
  4666. this.z = attribute.getZ( index );
  4667. return this;
  4668. }
  4669. /**
  4670. * Sets each component of this vector to a pseudo-random value between `0` and
  4671. * `1`, excluding `1`.
  4672. *
  4673. * @return {Vector3} A reference to this vector.
  4674. */
  4675. random() {
  4676. this.x = Math.random();
  4677. this.y = Math.random();
  4678. this.z = Math.random();
  4679. return this;
  4680. }
  4681. /**
  4682. * Sets this vector to a uniformly random point on a unit sphere.
  4683. *
  4684. * @return {Vector3} A reference to this vector.
  4685. */
  4686. randomDirection() {
  4687. // https://mathworld.wolfram.com/SpherePointPicking.html
  4688. const theta = Math.random() * Math.PI * 2;
  4689. const u = Math.random() * 2 - 1;
  4690. const c = Math.sqrt( 1 - u * u );
  4691. this.x = c * Math.cos( theta );
  4692. this.y = u;
  4693. this.z = c * Math.sin( theta );
  4694. return this;
  4695. }
  4696. *[ Symbol.iterator ]() {
  4697. yield this.x;
  4698. yield this.y;
  4699. yield this.z;
  4700. }
  4701. }
  4702. const _vector$c = /*@__PURE__*/ new Vector3();
  4703. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4704. /**
  4705. * Represents a 3x3 matrix.
  4706. *
  4707. * A Note on Row-Major and Column-Major Ordering:
  4708. *
  4709. * The constructor and {@link Matrix3#set} method take arguments in
  4710. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4711. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4712. * This means that calling:
  4713. * ```js
  4714. * const m = new THREE.Matrix();
  4715. * m.set( 11, 12, 13,
  4716. * 21, 22, 23,
  4717. * 31, 32, 33 );
  4718. * ```
  4719. * will result in the elements array containing:
  4720. * ```js
  4721. * m.elements = [ 11, 21, 31,
  4722. * 12, 22, 32,
  4723. * 13, 23, 33 ];
  4724. * ```
  4725. * and internally all calculations are performed using column-major ordering.
  4726. * However, as the actual ordering makes no difference mathematically and
  4727. * most people are used to thinking about matrices in row-major order, the
  4728. * three.js documentation shows matrices in row-major order. Just bear in
  4729. * mind that if you are reading the source code, you'll have to take the
  4730. * transpose of any matrices outlined here to make sense of the calculations.
  4731. */
  4732. class Matrix3 {
  4733. /**
  4734. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4735. * in row-major order. If no arguments are provided, the constructor
  4736. * initializes the matrix as an identity matrix.
  4737. *
  4738. * @param {number} [n11] - 1-1 matrix element.
  4739. * @param {number} [n12] - 1-2 matrix element.
  4740. * @param {number} [n13] - 1-3 matrix element.
  4741. * @param {number} [n21] - 2-1 matrix element.
  4742. * @param {number} [n22] - 2-2 matrix element.
  4743. * @param {number} [n23] - 2-3 matrix element.
  4744. * @param {number} [n31] - 3-1 matrix element.
  4745. * @param {number} [n32] - 3-2 matrix element.
  4746. * @param {number} [n33] - 3-3 matrix element.
  4747. */
  4748. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4749. /**
  4750. * This flag can be used for type testing.
  4751. *
  4752. * @type {boolean}
  4753. * @readonly
  4754. * @default true
  4755. */
  4756. Matrix3.prototype.isMatrix3 = true;
  4757. /**
  4758. * A column-major list of matrix values.
  4759. *
  4760. * @type {Array<number>}
  4761. */
  4762. this.elements = [
  4763. 1, 0, 0,
  4764. 0, 1, 0,
  4765. 0, 0, 1
  4766. ];
  4767. if ( n11 !== undefined ) {
  4768. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4769. }
  4770. }
  4771. /**
  4772. * Sets the elements of the matrix.The arguments are supposed to be
  4773. * in row-major order.
  4774. *
  4775. * @param {number} [n11] - 1-1 matrix element.
  4776. * @param {number} [n12] - 1-2 matrix element.
  4777. * @param {number} [n13] - 1-3 matrix element.
  4778. * @param {number} [n21] - 2-1 matrix element.
  4779. * @param {number} [n22] - 2-2 matrix element.
  4780. * @param {number} [n23] - 2-3 matrix element.
  4781. * @param {number} [n31] - 3-1 matrix element.
  4782. * @param {number} [n32] - 3-2 matrix element.
  4783. * @param {number} [n33] - 3-3 matrix element.
  4784. * @return {Matrix3} A reference to this matrix.
  4785. */
  4786. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4787. const te = this.elements;
  4788. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4789. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4790. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4791. return this;
  4792. }
  4793. /**
  4794. * Sets this matrix to the 3x3 identity matrix.
  4795. *
  4796. * @return {Matrix3} A reference to this matrix.
  4797. */
  4798. identity() {
  4799. this.set(
  4800. 1, 0, 0,
  4801. 0, 1, 0,
  4802. 0, 0, 1
  4803. );
  4804. return this;
  4805. }
  4806. /**
  4807. * Copies the values of the given matrix to this instance.
  4808. *
  4809. * @param {Matrix3} m - The matrix to copy.
  4810. * @return {Matrix3} A reference to this matrix.
  4811. */
  4812. copy( m ) {
  4813. const te = this.elements;
  4814. const me = m.elements;
  4815. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4816. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4817. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4818. return this;
  4819. }
  4820. /**
  4821. * Extracts the basis of this matrix into the three axis vectors provided.
  4822. *
  4823. * @param {Vector3} xAxis - The basis's x axis.
  4824. * @param {Vector3} yAxis - The basis's y axis.
  4825. * @param {Vector3} zAxis - The basis's z axis.
  4826. * @return {Matrix3} A reference to this matrix.
  4827. */
  4828. extractBasis( xAxis, yAxis, zAxis ) {
  4829. xAxis.setFromMatrix3Column( this, 0 );
  4830. yAxis.setFromMatrix3Column( this, 1 );
  4831. zAxis.setFromMatrix3Column( this, 2 );
  4832. return this;
  4833. }
  4834. /**
  4835. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4836. *
  4837. * @param {Matrix4} m - The 4x4 matrix.
  4838. * @return {Matrix3} A reference to this matrix.
  4839. */
  4840. setFromMatrix4( m ) {
  4841. const me = m.elements;
  4842. this.set(
  4843. me[ 0 ], me[ 4 ], me[ 8 ],
  4844. me[ 1 ], me[ 5 ], me[ 9 ],
  4845. me[ 2 ], me[ 6 ], me[ 10 ]
  4846. );
  4847. return this;
  4848. }
  4849. /**
  4850. * Post-multiplies this matrix by the given 3x3 matrix.
  4851. *
  4852. * @param {Matrix3} m - The matrix to multiply with.
  4853. * @return {Matrix3} A reference to this matrix.
  4854. */
  4855. multiply( m ) {
  4856. return this.multiplyMatrices( this, m );
  4857. }
  4858. /**
  4859. * Pre-multiplies this matrix by the given 3x3 matrix.
  4860. *
  4861. * @param {Matrix3} m - The matrix to multiply with.
  4862. * @return {Matrix3} A reference to this matrix.
  4863. */
  4864. premultiply( m ) {
  4865. return this.multiplyMatrices( m, this );
  4866. }
  4867. /**
  4868. * Multiples the given 3x3 matrices and stores the result
  4869. * in this matrix.
  4870. *
  4871. * @param {Matrix3} a - The first matrix.
  4872. * @param {Matrix3} b - The second matrix.
  4873. * @return {Matrix3} A reference to this matrix.
  4874. */
  4875. multiplyMatrices( a, b ) {
  4876. const ae = a.elements;
  4877. const be = b.elements;
  4878. const te = this.elements;
  4879. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4880. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4881. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4882. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4883. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4884. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4885. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4886. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4887. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4888. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4889. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4890. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4891. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4892. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4893. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4894. return this;
  4895. }
  4896. /**
  4897. * Multiplies every component of the matrix by the given scalar.
  4898. *
  4899. * @param {number} s - The scalar.
  4900. * @return {Matrix3} A reference to this matrix.
  4901. */
  4902. multiplyScalar( s ) {
  4903. const te = this.elements;
  4904. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4905. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4906. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4907. return this;
  4908. }
  4909. /**
  4910. * Computes and returns the determinant of this matrix.
  4911. *
  4912. * @return {number} The determinant.
  4913. */
  4914. determinant() {
  4915. const te = this.elements;
  4916. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4917. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4918. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4919. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4920. }
  4921. /**
  4922. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4923. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4924. * a zero matrix instead.
  4925. *
  4926. * @return {Matrix3} A reference to this matrix.
  4927. */
  4928. invert() {
  4929. const te = this.elements,
  4930. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4931. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4932. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4933. t11 = n33 * n22 - n32 * n23,
  4934. t12 = n32 * n13 - n33 * n12,
  4935. t13 = n23 * n12 - n22 * n13,
  4936. det = n11 * t11 + n21 * t12 + n31 * t13;
  4937. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4938. const detInv = 1 / det;
  4939. te[ 0 ] = t11 * detInv;
  4940. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4941. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4942. te[ 3 ] = t12 * detInv;
  4943. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4944. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4945. te[ 6 ] = t13 * detInv;
  4946. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4947. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4948. return this;
  4949. }
  4950. /**
  4951. * Transposes this matrix in place.
  4952. *
  4953. * @return {Matrix3} A reference to this matrix.
  4954. */
  4955. transpose() {
  4956. let tmp;
  4957. const m = this.elements;
  4958. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4959. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4960. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4961. return this;
  4962. }
  4963. /**
  4964. * Computes the normal matrix which is the inverse transpose of the upper
  4965. * left 3x3 portion of the given 4x4 matrix.
  4966. *
  4967. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4968. * @return {Matrix3} A reference to this matrix.
  4969. */
  4970. getNormalMatrix( matrix4 ) {
  4971. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4972. }
  4973. /**
  4974. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4975. *
  4976. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4977. * @return {Matrix3} A reference to this matrix.
  4978. */
  4979. transposeIntoArray( r ) {
  4980. const m = this.elements;
  4981. r[ 0 ] = m[ 0 ];
  4982. r[ 1 ] = m[ 3 ];
  4983. r[ 2 ] = m[ 6 ];
  4984. r[ 3 ] = m[ 1 ];
  4985. r[ 4 ] = m[ 4 ];
  4986. r[ 5 ] = m[ 7 ];
  4987. r[ 6 ] = m[ 2 ];
  4988. r[ 7 ] = m[ 5 ];
  4989. r[ 8 ] = m[ 8 ];
  4990. return this;
  4991. }
  4992. /**
  4993. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4994. *
  4995. * @param {number} tx - Offset x.
  4996. * @param {number} ty - Offset y.
  4997. * @param {number} sx - Repeat x.
  4998. * @param {number} sy - Repeat y.
  4999. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  5000. * @param {number} cx - Center x of rotation.
  5001. * @param {number} cy - Center y of rotation
  5002. * @return {Matrix3} A reference to this matrix.
  5003. */
  5004. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  5005. const c = Math.cos( rotation );
  5006. const s = Math.sin( rotation );
  5007. this.set(
  5008. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  5009. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  5010. 0, 0, 1
  5011. );
  5012. return this;
  5013. }
  5014. /**
  5015. * Scales this matrix with the given scalar values.
  5016. *
  5017. * @param {number} sx - The amount to scale in the X axis.
  5018. * @param {number} sy - The amount to scale in the Y axis.
  5019. * @return {Matrix3} A reference to this matrix.
  5020. */
  5021. scale( sx, sy ) {
  5022. this.premultiply( _m3.makeScale( sx, sy ) );
  5023. return this;
  5024. }
  5025. /**
  5026. * Rotates this matrix by the given angle.
  5027. *
  5028. * @param {number} theta - The rotation in radians.
  5029. * @return {Matrix3} A reference to this matrix.
  5030. */
  5031. rotate( theta ) {
  5032. this.premultiply( _m3.makeRotation( - theta ) );
  5033. return this;
  5034. }
  5035. /**
  5036. * Translates this matrix by the given scalar values.
  5037. *
  5038. * @param {number} tx - The amount to translate in the X axis.
  5039. * @param {number} ty - The amount to translate in the Y axis.
  5040. * @return {Matrix3} A reference to this matrix.
  5041. */
  5042. translate( tx, ty ) {
  5043. this.premultiply( _m3.makeTranslation( tx, ty ) );
  5044. return this;
  5045. }
  5046. // for 2D Transforms
  5047. /**
  5048. * Sets this matrix as a 2D translation transform.
  5049. *
  5050. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  5051. * @param {number} y - The amount to translate in the Y axis.
  5052. * @return {Matrix3} A reference to this matrix.
  5053. */
  5054. makeTranslation( x, y ) {
  5055. if ( x.isVector2 ) {
  5056. this.set(
  5057. 1, 0, x.x,
  5058. 0, 1, x.y,
  5059. 0, 0, 1
  5060. );
  5061. } else {
  5062. this.set(
  5063. 1, 0, x,
  5064. 0, 1, y,
  5065. 0, 0, 1
  5066. );
  5067. }
  5068. return this;
  5069. }
  5070. /**
  5071. * Sets this matrix as a 2D rotational transformation.
  5072. *
  5073. * @param {number} theta - The rotation in radians.
  5074. * @return {Matrix3} A reference to this matrix.
  5075. */
  5076. makeRotation( theta ) {
  5077. // counterclockwise
  5078. const c = Math.cos( theta );
  5079. const s = Math.sin( theta );
  5080. this.set(
  5081. c, - s, 0,
  5082. s, c, 0,
  5083. 0, 0, 1
  5084. );
  5085. return this;
  5086. }
  5087. /**
  5088. * Sets this matrix as a 2D scale transform.
  5089. *
  5090. * @param {number} x - The amount to scale in the X axis.
  5091. * @param {number} y - The amount to scale in the Y axis.
  5092. * @return {Matrix3} A reference to this matrix.
  5093. */
  5094. makeScale( x, y ) {
  5095. this.set(
  5096. x, 0, 0,
  5097. 0, y, 0,
  5098. 0, 0, 1
  5099. );
  5100. return this;
  5101. }
  5102. /**
  5103. * Returns `true` if this matrix is equal with the given one.
  5104. *
  5105. * @param {Matrix3} matrix - The matrix to test for equality.
  5106. * @return {boolean} Whether this matrix is equal with the given one.
  5107. */
  5108. equals( matrix ) {
  5109. const te = this.elements;
  5110. const me = matrix.elements;
  5111. for ( let i = 0; i < 9; i ++ ) {
  5112. if ( te[ i ] !== me[ i ] ) return false;
  5113. }
  5114. return true;
  5115. }
  5116. /**
  5117. * Sets the elements of the matrix from the given array.
  5118. *
  5119. * @param {Array<number>} array - The matrix elements in column-major order.
  5120. * @param {number} [offset=0] - Index of the first element in the array.
  5121. * @return {Matrix3} A reference to this matrix.
  5122. */
  5123. fromArray( array, offset = 0 ) {
  5124. for ( let i = 0; i < 9; i ++ ) {
  5125. this.elements[ i ] = array[ i + offset ];
  5126. }
  5127. return this;
  5128. }
  5129. /**
  5130. * Writes the elements of this matrix to the given array. If no array is provided,
  5131. * the method returns a new instance.
  5132. *
  5133. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  5134. * @param {number} [offset=0] - Index of the first element in the array.
  5135. * @return {Array<number>} The matrix elements in column-major order.
  5136. */
  5137. toArray( array = [], offset = 0 ) {
  5138. const te = this.elements;
  5139. array[ offset ] = te[ 0 ];
  5140. array[ offset + 1 ] = te[ 1 ];
  5141. array[ offset + 2 ] = te[ 2 ];
  5142. array[ offset + 3 ] = te[ 3 ];
  5143. array[ offset + 4 ] = te[ 4 ];
  5144. array[ offset + 5 ] = te[ 5 ];
  5145. array[ offset + 6 ] = te[ 6 ];
  5146. array[ offset + 7 ] = te[ 7 ];
  5147. array[ offset + 8 ] = te[ 8 ];
  5148. return array;
  5149. }
  5150. /**
  5151. * Returns a matrix with copied values from this instance.
  5152. *
  5153. * @return {Matrix3} A clone of this instance.
  5154. */
  5155. clone() {
  5156. return new this.constructor().fromArray( this.elements );
  5157. }
  5158. }
  5159. const _m3 = /*@__PURE__*/ new Matrix3();
  5160. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5161. 0.4123908, 0.3575843, 0.1804808,
  5162. 0.2126390, 0.7151687, 0.0721923,
  5163. 0.0193308, 0.1191948, 0.9505322
  5164. );
  5165. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5166. 3.2409699, -1.5373832, -0.4986108,
  5167. -0.9692436, 1.8759675, 0.0415551,
  5168. 0.0556301, -0.203977, 1.0569715
  5169. );
  5170. function createColorManagement() {
  5171. const ColorManagement = {
  5172. enabled: true,
  5173. workingColorSpace: LinearSRGBColorSpace,
  5174. /**
  5175. * Implementations of supported color spaces.
  5176. *
  5177. * Required:
  5178. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5179. * - whitePoint: reference white [ x y ]
  5180. * - transfer: transfer function (pre-defined)
  5181. * - toXYZ: Matrix3 RGB to XYZ transform
  5182. * - fromXYZ: Matrix3 XYZ to RGB transform
  5183. * - luminanceCoefficients: RGB luminance coefficients
  5184. *
  5185. * Optional:
  5186. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5187. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5188. *
  5189. * Reference:
  5190. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5191. */
  5192. spaces: {},
  5193. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5194. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5195. return color;
  5196. }
  5197. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5198. color.r = SRGBToLinear( color.r );
  5199. color.g = SRGBToLinear( color.g );
  5200. color.b = SRGBToLinear( color.b );
  5201. }
  5202. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5203. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5204. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5205. }
  5206. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5207. color.r = LinearToSRGB( color.r );
  5208. color.g = LinearToSRGB( color.g );
  5209. color.b = LinearToSRGB( color.b );
  5210. }
  5211. return color;
  5212. },
  5213. workingToColorSpace: function ( color, targetColorSpace ) {
  5214. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5215. },
  5216. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5217. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5218. },
  5219. getPrimaries: function ( colorSpace ) {
  5220. return this.spaces[ colorSpace ].primaries;
  5221. },
  5222. getTransfer: function ( colorSpace ) {
  5223. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5224. return this.spaces[ colorSpace ].transfer;
  5225. },
  5226. getToneMappingMode: function ( colorSpace ) {
  5227. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5228. },
  5229. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5230. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5231. },
  5232. define: function ( colorSpaces ) {
  5233. Object.assign( this.spaces, colorSpaces );
  5234. },
  5235. // Internal APIs
  5236. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5237. return targetMatrix
  5238. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5239. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5240. },
  5241. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5242. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5243. },
  5244. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5245. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5246. },
  5247. // Deprecated
  5248. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5249. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5250. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5251. },
  5252. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5253. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5254. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5255. },
  5256. };
  5257. /******************************************************************************
  5258. * sRGB definitions
  5259. */
  5260. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5261. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5262. const D65 = [ 0.3127, 0.3290 ];
  5263. ColorManagement.define( {
  5264. [ LinearSRGBColorSpace ]: {
  5265. primaries: REC709_PRIMARIES,
  5266. whitePoint: D65,
  5267. transfer: LinearTransfer,
  5268. toXYZ: LINEAR_REC709_TO_XYZ,
  5269. fromXYZ: XYZ_TO_LINEAR_REC709,
  5270. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5271. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5272. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5273. },
  5274. [ SRGBColorSpace ]: {
  5275. primaries: REC709_PRIMARIES,
  5276. whitePoint: D65,
  5277. transfer: SRGBTransfer,
  5278. toXYZ: LINEAR_REC709_TO_XYZ,
  5279. fromXYZ: XYZ_TO_LINEAR_REC709,
  5280. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5281. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5282. },
  5283. } );
  5284. return ColorManagement;
  5285. }
  5286. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5287. function SRGBToLinear( c ) {
  5288. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5289. }
  5290. function LinearToSRGB( c ) {
  5291. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5292. }
  5293. let _canvas;
  5294. /**
  5295. * A class containing utility functions for images.
  5296. *
  5297. * @hideconstructor
  5298. */
  5299. class ImageUtils {
  5300. /**
  5301. * Returns a data URI containing a representation of the given image.
  5302. *
  5303. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5304. * @param {string} [type='image/png'] - Indicates the image format.
  5305. * @return {string} The data URI.
  5306. */
  5307. static getDataURL( image, type = 'image/png' ) {
  5308. if ( /^data:/i.test( image.src ) ) {
  5309. return image.src;
  5310. }
  5311. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5312. return image.src;
  5313. }
  5314. let canvas;
  5315. if ( image instanceof HTMLCanvasElement ) {
  5316. canvas = image;
  5317. } else {
  5318. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5319. _canvas.width = image.width;
  5320. _canvas.height = image.height;
  5321. const context = _canvas.getContext( '2d' );
  5322. if ( image instanceof ImageData ) {
  5323. context.putImageData( image, 0, 0 );
  5324. } else {
  5325. context.drawImage( image, 0, 0, image.width, image.height );
  5326. }
  5327. canvas = _canvas;
  5328. }
  5329. return canvas.toDataURL( type );
  5330. }
  5331. /**
  5332. * Converts the given sRGB image data to linear color space.
  5333. *
  5334. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5335. * @return {HTMLCanvasElement|Object} The converted image.
  5336. */
  5337. static sRGBToLinear( image ) {
  5338. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5339. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5340. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5341. const canvas = createElementNS( 'canvas' );
  5342. canvas.width = image.width;
  5343. canvas.height = image.height;
  5344. const context = canvas.getContext( '2d' );
  5345. context.drawImage( image, 0, 0, image.width, image.height );
  5346. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5347. const data = imageData.data;
  5348. for ( let i = 0; i < data.length; i ++ ) {
  5349. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5350. }
  5351. context.putImageData( imageData, 0, 0 );
  5352. return canvas;
  5353. } else if ( image.data ) {
  5354. const data = image.data.slice( 0 );
  5355. for ( let i = 0; i < data.length; i ++ ) {
  5356. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5357. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5358. } else {
  5359. // assuming float
  5360. data[ i ] = SRGBToLinear( data[ i ] );
  5361. }
  5362. }
  5363. return {
  5364. data: data,
  5365. width: image.width,
  5366. height: image.height
  5367. };
  5368. } else {
  5369. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5370. return image;
  5371. }
  5372. }
  5373. }
  5374. let _sourceId = 0;
  5375. /**
  5376. * Represents the data source of a texture.
  5377. *
  5378. * The main purpose of this class is to decouple the data definition from the texture
  5379. * definition so the same data can be used with multiple texture instances.
  5380. */
  5381. class Source {
  5382. /**
  5383. * Constructs a new video texture.
  5384. *
  5385. * @param {any} [data=null] - The data definition of a texture.
  5386. */
  5387. constructor( data = null ) {
  5388. /**
  5389. * This flag can be used for type testing.
  5390. *
  5391. * @type {boolean}
  5392. * @readonly
  5393. * @default true
  5394. */
  5395. this.isSource = true;
  5396. /**
  5397. * The ID of the source.
  5398. *
  5399. * @name Source#id
  5400. * @type {number}
  5401. * @readonly
  5402. */
  5403. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5404. /**
  5405. * The UUID of the source.
  5406. *
  5407. * @type {string}
  5408. * @readonly
  5409. */
  5410. this.uuid = generateUUID();
  5411. /**
  5412. * The data definition of a texture.
  5413. *
  5414. * @type {any}
  5415. */
  5416. this.data = data;
  5417. /**
  5418. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5419. * provides more control on how texture data should be processed. When `dataReady` is set
  5420. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5421. * the data into the GPU memory.
  5422. *
  5423. * @type {boolean}
  5424. * @default true
  5425. */
  5426. this.dataReady = true;
  5427. /**
  5428. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5429. *
  5430. * @type {number}
  5431. * @readonly
  5432. * @default 0
  5433. */
  5434. this.version = 0;
  5435. }
  5436. /**
  5437. * Returns the dimensions of the source into the given target vector.
  5438. *
  5439. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5440. * @return {(Vector2|Vector3)} The dimensions of the source.
  5441. */
  5442. getSize( target ) {
  5443. const data = this.data;
  5444. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5445. target.set( data.videoWidth, data.videoHeight, 0 );
  5446. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5447. target.set( data.displayHeight, data.displayWidth, 0 );
  5448. } else if ( data !== null ) {
  5449. target.set( data.width, data.height, data.depth || 0 );
  5450. } else {
  5451. target.set( 0, 0, 0 );
  5452. }
  5453. return target;
  5454. }
  5455. /**
  5456. * When the property is set to `true`, the engine allocates the memory
  5457. * for the texture (if necessary) and triggers the actual texture upload
  5458. * to the GPU next time the source is used.
  5459. *
  5460. * @type {boolean}
  5461. * @default false
  5462. * @param {boolean} value
  5463. */
  5464. set needsUpdate( value ) {
  5465. if ( value === true ) this.version ++;
  5466. }
  5467. /**
  5468. * Serializes the source into JSON.
  5469. *
  5470. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5471. * @return {Object} A JSON object representing the serialized source.
  5472. * @see {@link ObjectLoader#parse}
  5473. */
  5474. toJSON( meta ) {
  5475. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5476. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5477. return meta.images[ this.uuid ];
  5478. }
  5479. const output = {
  5480. uuid: this.uuid,
  5481. url: ''
  5482. };
  5483. const data = this.data;
  5484. if ( data !== null ) {
  5485. let url;
  5486. if ( Array.isArray( data ) ) {
  5487. // cube texture
  5488. url = [];
  5489. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5490. if ( data[ i ].isDataTexture ) {
  5491. url.push( serializeImage( data[ i ].image ) );
  5492. } else {
  5493. url.push( serializeImage( data[ i ] ) );
  5494. }
  5495. }
  5496. } else {
  5497. // texture
  5498. url = serializeImage( data );
  5499. }
  5500. output.url = url;
  5501. }
  5502. if ( ! isRootObject ) {
  5503. meta.images[ this.uuid ] = output;
  5504. }
  5505. return output;
  5506. }
  5507. }
  5508. function serializeImage( image ) {
  5509. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5510. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5511. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5512. // default images
  5513. return ImageUtils.getDataURL( image );
  5514. } else {
  5515. if ( image.data ) {
  5516. // images of DataTexture
  5517. return {
  5518. data: Array.from( image.data ),
  5519. width: image.width,
  5520. height: image.height,
  5521. type: image.data.constructor.name
  5522. };
  5523. } else {
  5524. warn( 'Texture: Unable to serialize Texture.' );
  5525. return {};
  5526. }
  5527. }
  5528. }
  5529. let _textureId = 0;
  5530. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5531. /**
  5532. * Base class for all textures.
  5533. *
  5534. * Note: After the initial use of a texture, its dimensions, format, and type
  5535. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5536. *
  5537. * @augments EventDispatcher
  5538. */
  5539. class Texture extends EventDispatcher {
  5540. /**
  5541. * Constructs a new texture.
  5542. *
  5543. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5544. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5545. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5546. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5547. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5548. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5549. * @param {number} [format=RGBAFormat] - The texture format.
  5550. * @param {number} [type=UnsignedByteType] - The texture type.
  5551. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5552. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5553. */
  5554. 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 ) {
  5555. super();
  5556. /**
  5557. * This flag can be used for type testing.
  5558. *
  5559. * @type {boolean}
  5560. * @readonly
  5561. * @default true
  5562. */
  5563. this.isTexture = true;
  5564. /**
  5565. * The ID of the texture.
  5566. *
  5567. * @name Texture#id
  5568. * @type {number}
  5569. * @readonly
  5570. */
  5571. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5572. /**
  5573. * The UUID of the texture.
  5574. *
  5575. * @type {string}
  5576. * @readonly
  5577. */
  5578. this.uuid = generateUUID();
  5579. /**
  5580. * The name of the texture.
  5581. *
  5582. * @type {string}
  5583. */
  5584. this.name = '';
  5585. /**
  5586. * The data definition of a texture. A reference to the data source can be
  5587. * shared across textures. This is often useful in context of spritesheets
  5588. * where multiple textures render the same data but with different texture
  5589. * transformations.
  5590. *
  5591. * @type {Source}
  5592. */
  5593. this.source = new Source( image );
  5594. /**
  5595. * An array holding user-defined mipmaps.
  5596. *
  5597. * @type {Array<Object>}
  5598. */
  5599. this.mipmaps = [];
  5600. /**
  5601. * How the texture is applied to the object. The value `UVMapping`
  5602. * is the default, where texture or uv coordinates are used to apply the map.
  5603. *
  5604. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5605. * @default UVMapping
  5606. */
  5607. this.mapping = mapping;
  5608. /**
  5609. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5610. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5611. *
  5612. * @type {number}
  5613. * @default 0
  5614. */
  5615. this.channel = 0;
  5616. /**
  5617. * This defines how the texture is wrapped horizontally and corresponds to
  5618. * *U* in UV mapping.
  5619. *
  5620. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5621. * @default ClampToEdgeWrapping
  5622. */
  5623. this.wrapS = wrapS;
  5624. /**
  5625. * This defines how the texture is wrapped horizontally and corresponds to
  5626. * *V* in UV mapping.
  5627. *
  5628. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5629. * @default ClampToEdgeWrapping
  5630. */
  5631. this.wrapT = wrapT;
  5632. /**
  5633. * How the texture is sampled when a texel covers more than one pixel.
  5634. *
  5635. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5636. * @default LinearFilter
  5637. */
  5638. this.magFilter = magFilter;
  5639. /**
  5640. * How the texture is sampled when a texel covers less than one pixel.
  5641. *
  5642. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5643. * @default LinearMipmapLinearFilter
  5644. */
  5645. this.minFilter = minFilter;
  5646. /**
  5647. * The number of samples taken along the axis through the pixel that has the
  5648. * highest density of texels. By default, this value is `1`. A higher value
  5649. * gives a less blurry result than a basic mipmap, at the cost of more
  5650. * texture samples being used.
  5651. *
  5652. * @type {number}
  5653. * @default Texture.DEFAULT_ANISOTROPY
  5654. */
  5655. this.anisotropy = anisotropy;
  5656. /**
  5657. * The format of the texture.
  5658. *
  5659. * @type {number}
  5660. * @default RGBAFormat
  5661. */
  5662. this.format = format;
  5663. /**
  5664. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5665. * defines how the texture data is going to be stored on the GPU.
  5666. *
  5667. * This property allows to overwrite the default format.
  5668. *
  5669. * @type {?string}
  5670. * @default null
  5671. */
  5672. this.internalFormat = null;
  5673. /**
  5674. * The data type of the texture.
  5675. *
  5676. * @type {number}
  5677. * @default UnsignedByteType
  5678. */
  5679. this.type = type;
  5680. /**
  5681. * How much a single repetition of the texture is offset from the beginning,
  5682. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5683. *
  5684. * @type {Vector2}
  5685. * @default (0,0)
  5686. */
  5687. this.offset = new Vector2( 0, 0 );
  5688. /**
  5689. * How many times the texture is repeated across the surface, in each
  5690. * direction U and V. If repeat is set greater than `1` in either direction,
  5691. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5692. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5693. *
  5694. * @type {Vector2}
  5695. * @default (1,1)
  5696. */
  5697. this.repeat = new Vector2( 1, 1 );
  5698. /**
  5699. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5700. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5701. *
  5702. * @type {Vector2}
  5703. * @default (0,0)
  5704. */
  5705. this.center = new Vector2( 0, 0 );
  5706. /**
  5707. * How much the texture is rotated around the center point, in radians.
  5708. * Positive values are counter-clockwise.
  5709. *
  5710. * @type {number}
  5711. * @default 0
  5712. */
  5713. this.rotation = 0;
  5714. /**
  5715. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5716. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5717. * {@link Texture#rotation}, and {@link Texture#center}.
  5718. *
  5719. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5720. *
  5721. * @type {boolean}
  5722. * @default true
  5723. */
  5724. this.matrixAutoUpdate = true;
  5725. /**
  5726. * The uv-transformation matrix of the texture.
  5727. *
  5728. * @type {Matrix3}
  5729. */
  5730. this.matrix = new Matrix3();
  5731. /**
  5732. * Whether to generate mipmaps (if possible) for a texture.
  5733. *
  5734. * Set this to `false` if you are creating mipmaps manually.
  5735. *
  5736. * @type {boolean}
  5737. * @default true
  5738. */
  5739. this.generateMipmaps = true;
  5740. /**
  5741. * If set to `true`, the alpha channel, if present, is multiplied into the
  5742. * color channels when the texture is uploaded to the GPU.
  5743. *
  5744. * Note that this property has no effect when using `ImageBitmap`. You need to
  5745. * configure premultiply alpha on bitmap creation instead.
  5746. *
  5747. * @type {boolean}
  5748. * @default false
  5749. */
  5750. this.premultiplyAlpha = false;
  5751. /**
  5752. * If set to `true`, the texture is flipped along the vertical axis when
  5753. * uploaded to the GPU.
  5754. *
  5755. * Note that this property has no effect when using `ImageBitmap`. You need to
  5756. * configure the flip on bitmap creation instead.
  5757. *
  5758. * @type {boolean}
  5759. * @default true
  5760. */
  5761. this.flipY = true;
  5762. /**
  5763. * Specifies the alignment requirements for the start of each pixel row in memory.
  5764. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5765. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5766. *
  5767. * @type {number}
  5768. * @default 4
  5769. */
  5770. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5771. /**
  5772. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5773. *
  5774. * @type {string}
  5775. * @default NoColorSpace
  5776. */
  5777. this.colorSpace = colorSpace;
  5778. /**
  5779. * An object that can be used to store custom data about the texture. It
  5780. * should not hold references to functions as these will not be cloned.
  5781. *
  5782. * @type {Object}
  5783. */
  5784. this.userData = {};
  5785. /**
  5786. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5787. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5788. *
  5789. * @type {Array<Object>}
  5790. */
  5791. this.updateRanges = [];
  5792. /**
  5793. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5794. *
  5795. * @type {number}
  5796. * @readonly
  5797. * @default 0
  5798. */
  5799. this.version = 0;
  5800. /**
  5801. * A callback function, called when the texture is updated (e.g., when
  5802. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5803. *
  5804. * @type {?Function}
  5805. * @default null
  5806. */
  5807. this.onUpdate = null;
  5808. /**
  5809. * An optional back reference to the textures render target.
  5810. *
  5811. * @type {?(RenderTarget|WebGLRenderTarget)}
  5812. * @default null
  5813. */
  5814. this.renderTarget = null;
  5815. /**
  5816. * Indicates whether a texture belongs to a render target or not.
  5817. *
  5818. * @type {boolean}
  5819. * @readonly
  5820. * @default false
  5821. */
  5822. this.isRenderTargetTexture = false;
  5823. /**
  5824. * Indicates if a texture should be handled like a texture array.
  5825. *
  5826. * @type {boolean}
  5827. * @readonly
  5828. * @default false
  5829. */
  5830. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5831. /**
  5832. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5833. * (only relevant for render target textures).
  5834. *
  5835. * @type {number}
  5836. * @readonly
  5837. * @default 0
  5838. */
  5839. this.pmremVersion = 0;
  5840. }
  5841. /**
  5842. * The width of the texture in pixels.
  5843. */
  5844. get width() {
  5845. return this.source.getSize( _tempVec3 ).x;
  5846. }
  5847. /**
  5848. * The height of the texture in pixels.
  5849. */
  5850. get height() {
  5851. return this.source.getSize( _tempVec3 ).y;
  5852. }
  5853. /**
  5854. * The depth of the texture in pixels.
  5855. */
  5856. get depth() {
  5857. return this.source.getSize( _tempVec3 ).z;
  5858. }
  5859. /**
  5860. * The image object holding the texture data.
  5861. *
  5862. * @type {?Object}
  5863. */
  5864. get image() {
  5865. return this.source.data;
  5866. }
  5867. set image( value = null ) {
  5868. this.source.data = value;
  5869. }
  5870. /**
  5871. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5872. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5873. */
  5874. updateMatrix() {
  5875. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5876. }
  5877. /**
  5878. * Adds a range of data in the data texture to be updated on the GPU.
  5879. *
  5880. * @param {number} start - Position at which to start update.
  5881. * @param {number} count - The number of components to update.
  5882. */
  5883. addUpdateRange( start, count ) {
  5884. this.updateRanges.push( { start, count } );
  5885. }
  5886. /**
  5887. * Clears the update ranges.
  5888. */
  5889. clearUpdateRanges() {
  5890. this.updateRanges.length = 0;
  5891. }
  5892. /**
  5893. * Returns a new texture with copied values from this instance.
  5894. *
  5895. * @return {Texture} A clone of this instance.
  5896. */
  5897. clone() {
  5898. return new this.constructor().copy( this );
  5899. }
  5900. /**
  5901. * Copies the values of the given texture to this instance.
  5902. *
  5903. * @param {Texture} source - The texture to copy.
  5904. * @return {Texture} A reference to this instance.
  5905. */
  5906. copy( source ) {
  5907. this.name = source.name;
  5908. this.source = source.source;
  5909. this.mipmaps = source.mipmaps.slice( 0 );
  5910. this.mapping = source.mapping;
  5911. this.channel = source.channel;
  5912. this.wrapS = source.wrapS;
  5913. this.wrapT = source.wrapT;
  5914. this.magFilter = source.magFilter;
  5915. this.minFilter = source.minFilter;
  5916. this.anisotropy = source.anisotropy;
  5917. this.format = source.format;
  5918. this.internalFormat = source.internalFormat;
  5919. this.type = source.type;
  5920. this.offset.copy( source.offset );
  5921. this.repeat.copy( source.repeat );
  5922. this.center.copy( source.center );
  5923. this.rotation = source.rotation;
  5924. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5925. this.matrix.copy( source.matrix );
  5926. this.generateMipmaps = source.generateMipmaps;
  5927. this.premultiplyAlpha = source.premultiplyAlpha;
  5928. this.flipY = source.flipY;
  5929. this.unpackAlignment = source.unpackAlignment;
  5930. this.colorSpace = source.colorSpace;
  5931. this.renderTarget = source.renderTarget;
  5932. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5933. this.isArrayTexture = source.isArrayTexture;
  5934. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5935. this.needsUpdate = true;
  5936. return this;
  5937. }
  5938. /**
  5939. * Sets this texture's properties based on `values`.
  5940. * @param {Object} values - A container with texture parameters.
  5941. */
  5942. setValues( values ) {
  5943. for ( const key in values ) {
  5944. const newValue = values[ key ];
  5945. if ( newValue === undefined ) {
  5946. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5947. continue;
  5948. }
  5949. const currentValue = this[ key ];
  5950. if ( currentValue === undefined ) {
  5951. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  5952. continue;
  5953. }
  5954. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5955. currentValue.copy( newValue );
  5956. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5957. currentValue.copy( newValue );
  5958. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5959. currentValue.copy( newValue );
  5960. } else {
  5961. this[ key ] = newValue;
  5962. }
  5963. }
  5964. }
  5965. /**
  5966. * Serializes the texture into JSON.
  5967. *
  5968. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5969. * @return {Object} A JSON object representing the serialized texture.
  5970. * @see {@link ObjectLoader#parse}
  5971. */
  5972. toJSON( meta ) {
  5973. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5974. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5975. return meta.textures[ this.uuid ];
  5976. }
  5977. const output = {
  5978. metadata: {
  5979. version: 4.7,
  5980. type: 'Texture',
  5981. generator: 'Texture.toJSON'
  5982. },
  5983. uuid: this.uuid,
  5984. name: this.name,
  5985. image: this.source.toJSON( meta ).uuid,
  5986. mapping: this.mapping,
  5987. channel: this.channel,
  5988. repeat: [ this.repeat.x, this.repeat.y ],
  5989. offset: [ this.offset.x, this.offset.y ],
  5990. center: [ this.center.x, this.center.y ],
  5991. rotation: this.rotation,
  5992. wrap: [ this.wrapS, this.wrapT ],
  5993. format: this.format,
  5994. internalFormat: this.internalFormat,
  5995. type: this.type,
  5996. colorSpace: this.colorSpace,
  5997. minFilter: this.minFilter,
  5998. magFilter: this.magFilter,
  5999. anisotropy: this.anisotropy,
  6000. flipY: this.flipY,
  6001. generateMipmaps: this.generateMipmaps,
  6002. premultiplyAlpha: this.premultiplyAlpha,
  6003. unpackAlignment: this.unpackAlignment
  6004. };
  6005. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  6006. if ( ! isRootObject ) {
  6007. meta.textures[ this.uuid ] = output;
  6008. }
  6009. return output;
  6010. }
  6011. /**
  6012. * Frees the GPU-related resources allocated by this instance. Call this
  6013. * method whenever this instance is no longer used in your app.
  6014. *
  6015. * @fires Texture#dispose
  6016. */
  6017. dispose() {
  6018. /**
  6019. * Fires when the texture has been disposed of.
  6020. *
  6021. * @event Texture#dispose
  6022. * @type {Object}
  6023. */
  6024. this.dispatchEvent( { type: 'dispose' } );
  6025. }
  6026. /**
  6027. * Transforms the given uv vector with the textures uv transformation matrix.
  6028. *
  6029. * @param {Vector2} uv - The uv vector.
  6030. * @return {Vector2} The transformed uv vector.
  6031. */
  6032. transformUv( uv ) {
  6033. if ( this.mapping !== UVMapping ) return uv;
  6034. uv.applyMatrix3( this.matrix );
  6035. if ( uv.x < 0 || uv.x > 1 ) {
  6036. switch ( this.wrapS ) {
  6037. case RepeatWrapping:
  6038. uv.x = uv.x - Math.floor( uv.x );
  6039. break;
  6040. case ClampToEdgeWrapping:
  6041. uv.x = uv.x < 0 ? 0 : 1;
  6042. break;
  6043. case MirroredRepeatWrapping:
  6044. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6045. uv.x = Math.ceil( uv.x ) - uv.x;
  6046. } else {
  6047. uv.x = uv.x - Math.floor( uv.x );
  6048. }
  6049. break;
  6050. }
  6051. }
  6052. if ( uv.y < 0 || uv.y > 1 ) {
  6053. switch ( this.wrapT ) {
  6054. case RepeatWrapping:
  6055. uv.y = uv.y - Math.floor( uv.y );
  6056. break;
  6057. case ClampToEdgeWrapping:
  6058. uv.y = uv.y < 0 ? 0 : 1;
  6059. break;
  6060. case MirroredRepeatWrapping:
  6061. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6062. uv.y = Math.ceil( uv.y ) - uv.y;
  6063. } else {
  6064. uv.y = uv.y - Math.floor( uv.y );
  6065. }
  6066. break;
  6067. }
  6068. }
  6069. if ( this.flipY ) {
  6070. uv.y = 1 - uv.y;
  6071. }
  6072. return uv;
  6073. }
  6074. /**
  6075. * Setting this property to `true` indicates the engine the texture
  6076. * must be updated in the next render. This triggers a texture upload
  6077. * to the GPU and ensures correct texture parameter configuration.
  6078. *
  6079. * @type {boolean}
  6080. * @default false
  6081. * @param {boolean} value
  6082. */
  6083. set needsUpdate( value ) {
  6084. if ( value === true ) {
  6085. this.version ++;
  6086. this.source.needsUpdate = true;
  6087. }
  6088. }
  6089. /**
  6090. * Setting this property to `true` indicates the engine the PMREM
  6091. * must be regenerated.
  6092. *
  6093. * @type {boolean}
  6094. * @default false
  6095. * @param {boolean} value
  6096. */
  6097. set needsPMREMUpdate( value ) {
  6098. if ( value === true ) {
  6099. this.pmremVersion ++;
  6100. }
  6101. }
  6102. }
  6103. /**
  6104. * The default image for all textures.
  6105. *
  6106. * @static
  6107. * @type {?Image}
  6108. * @default null
  6109. */
  6110. Texture.DEFAULT_IMAGE = null;
  6111. /**
  6112. * The default mapping for all textures.
  6113. *
  6114. * @static
  6115. * @type {number}
  6116. * @default UVMapping
  6117. */
  6118. Texture.DEFAULT_MAPPING = UVMapping;
  6119. /**
  6120. * The default anisotropy value for all textures.
  6121. *
  6122. * @static
  6123. * @type {number}
  6124. * @default 1
  6125. */
  6126. Texture.DEFAULT_ANISOTROPY = 1;
  6127. /**
  6128. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  6129. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  6130. *
  6131. * - A point in 4D space.
  6132. * - A direction and length in 4D space. In three.js the length will
  6133. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  6134. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  6135. * - Any arbitrary ordered quadruplet of numbers.
  6136. *
  6137. * There are other things a 4D vector can be used to represent, however these
  6138. * are the most common uses in *three.js*.
  6139. *
  6140. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6141. * the corresponding order.
  6142. * ```js
  6143. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6144. *
  6145. * //no arguments; will be initialised to (0, 0, 0, 1)
  6146. * const b = new THREE.Vector4( );
  6147. *
  6148. * const d = a.dot( b );
  6149. * ```
  6150. */
  6151. class Vector4 {
  6152. /**
  6153. * Constructs a new 4D vector.
  6154. *
  6155. * @param {number} [x=0] - The x value of this vector.
  6156. * @param {number} [y=0] - The y value of this vector.
  6157. * @param {number} [z=0] - The z value of this vector.
  6158. * @param {number} [w=1] - The w value of this vector.
  6159. */
  6160. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6161. /**
  6162. * This flag can be used for type testing.
  6163. *
  6164. * @type {boolean}
  6165. * @readonly
  6166. * @default true
  6167. */
  6168. Vector4.prototype.isVector4 = true;
  6169. /**
  6170. * The x value of this vector.
  6171. *
  6172. * @type {number}
  6173. */
  6174. this.x = x;
  6175. /**
  6176. * The y value of this vector.
  6177. *
  6178. * @type {number}
  6179. */
  6180. this.y = y;
  6181. /**
  6182. * The z value of this vector.
  6183. *
  6184. * @type {number}
  6185. */
  6186. this.z = z;
  6187. /**
  6188. * The w value of this vector.
  6189. *
  6190. * @type {number}
  6191. */
  6192. this.w = w;
  6193. }
  6194. /**
  6195. * Alias for {@link Vector4#z}.
  6196. *
  6197. * @type {number}
  6198. */
  6199. get width() {
  6200. return this.z;
  6201. }
  6202. set width( value ) {
  6203. this.z = value;
  6204. }
  6205. /**
  6206. * Alias for {@link Vector4#w}.
  6207. *
  6208. * @type {number}
  6209. */
  6210. get height() {
  6211. return this.w;
  6212. }
  6213. set height( value ) {
  6214. this.w = value;
  6215. }
  6216. /**
  6217. * Sets the vector components.
  6218. *
  6219. * @param {number} x - The value of the x component.
  6220. * @param {number} y - The value of the y component.
  6221. * @param {number} z - The value of the z component.
  6222. * @param {number} w - The value of the w component.
  6223. * @return {Vector4} A reference to this vector.
  6224. */
  6225. set( x, y, z, w ) {
  6226. this.x = x;
  6227. this.y = y;
  6228. this.z = z;
  6229. this.w = w;
  6230. return this;
  6231. }
  6232. /**
  6233. * Sets the vector components to the same value.
  6234. *
  6235. * @param {number} scalar - The value to set for all vector components.
  6236. * @return {Vector4} A reference to this vector.
  6237. */
  6238. setScalar( scalar ) {
  6239. this.x = scalar;
  6240. this.y = scalar;
  6241. this.z = scalar;
  6242. this.w = scalar;
  6243. return this;
  6244. }
  6245. /**
  6246. * Sets the vector's x component to the given value
  6247. *
  6248. * @param {number} x - The value to set.
  6249. * @return {Vector4} A reference to this vector.
  6250. */
  6251. setX( x ) {
  6252. this.x = x;
  6253. return this;
  6254. }
  6255. /**
  6256. * Sets the vector's y component to the given value
  6257. *
  6258. * @param {number} y - The value to set.
  6259. * @return {Vector4} A reference to this vector.
  6260. */
  6261. setY( y ) {
  6262. this.y = y;
  6263. return this;
  6264. }
  6265. /**
  6266. * Sets the vector's z component to the given value
  6267. *
  6268. * @param {number} z - The value to set.
  6269. * @return {Vector4} A reference to this vector.
  6270. */
  6271. setZ( z ) {
  6272. this.z = z;
  6273. return this;
  6274. }
  6275. /**
  6276. * Sets the vector's w component to the given value
  6277. *
  6278. * @param {number} w - The value to set.
  6279. * @return {Vector4} A reference to this vector.
  6280. */
  6281. setW( w ) {
  6282. this.w = w;
  6283. return this;
  6284. }
  6285. /**
  6286. * Allows to set a vector component with an index.
  6287. *
  6288. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6289. * `2` equals to z, `3` equals to w.
  6290. * @param {number} value - The value to set.
  6291. * @return {Vector4} A reference to this vector.
  6292. */
  6293. setComponent( index, value ) {
  6294. switch ( index ) {
  6295. case 0: this.x = value; break;
  6296. case 1: this.y = value; break;
  6297. case 2: this.z = value; break;
  6298. case 3: this.w = value; break;
  6299. default: throw new Error( 'index is out of range: ' + index );
  6300. }
  6301. return this;
  6302. }
  6303. /**
  6304. * Returns the value of the vector component which matches the given index.
  6305. *
  6306. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6307. * `2` equals to z, `3` equals to w.
  6308. * @return {number} A vector component value.
  6309. */
  6310. getComponent( index ) {
  6311. switch ( index ) {
  6312. case 0: return this.x;
  6313. case 1: return this.y;
  6314. case 2: return this.z;
  6315. case 3: return this.w;
  6316. default: throw new Error( 'index is out of range: ' + index );
  6317. }
  6318. }
  6319. /**
  6320. * Returns a new vector with copied values from this instance.
  6321. *
  6322. * @return {Vector4} A clone of this instance.
  6323. */
  6324. clone() {
  6325. return new this.constructor( this.x, this.y, this.z, this.w );
  6326. }
  6327. /**
  6328. * Copies the values of the given vector to this instance.
  6329. *
  6330. * @param {Vector3|Vector4} v - The vector to copy.
  6331. * @return {Vector4} A reference to this vector.
  6332. */
  6333. copy( v ) {
  6334. this.x = v.x;
  6335. this.y = v.y;
  6336. this.z = v.z;
  6337. this.w = ( v.w !== undefined ) ? v.w : 1;
  6338. return this;
  6339. }
  6340. /**
  6341. * Adds the given vector to this instance.
  6342. *
  6343. * @param {Vector4} v - The vector to add.
  6344. * @return {Vector4} A reference to this vector.
  6345. */
  6346. add( v ) {
  6347. this.x += v.x;
  6348. this.y += v.y;
  6349. this.z += v.z;
  6350. this.w += v.w;
  6351. return this;
  6352. }
  6353. /**
  6354. * Adds the given scalar value to all components of this instance.
  6355. *
  6356. * @param {number} s - The scalar to add.
  6357. * @return {Vector4} A reference to this vector.
  6358. */
  6359. addScalar( s ) {
  6360. this.x += s;
  6361. this.y += s;
  6362. this.z += s;
  6363. this.w += s;
  6364. return this;
  6365. }
  6366. /**
  6367. * Adds the given vectors and stores the result in this instance.
  6368. *
  6369. * @param {Vector4} a - The first vector.
  6370. * @param {Vector4} b - The second vector.
  6371. * @return {Vector4} A reference to this vector.
  6372. */
  6373. addVectors( a, b ) {
  6374. this.x = a.x + b.x;
  6375. this.y = a.y + b.y;
  6376. this.z = a.z + b.z;
  6377. this.w = a.w + b.w;
  6378. return this;
  6379. }
  6380. /**
  6381. * Adds the given vector scaled by the given factor to this instance.
  6382. *
  6383. * @param {Vector4} v - The vector.
  6384. * @param {number} s - The factor that scales `v`.
  6385. * @return {Vector4} A reference to this vector.
  6386. */
  6387. addScaledVector( v, s ) {
  6388. this.x += v.x * s;
  6389. this.y += v.y * s;
  6390. this.z += v.z * s;
  6391. this.w += v.w * s;
  6392. return this;
  6393. }
  6394. /**
  6395. * Subtracts the given vector from this instance.
  6396. *
  6397. * @param {Vector4} v - The vector to subtract.
  6398. * @return {Vector4} A reference to this vector.
  6399. */
  6400. sub( v ) {
  6401. this.x -= v.x;
  6402. this.y -= v.y;
  6403. this.z -= v.z;
  6404. this.w -= v.w;
  6405. return this;
  6406. }
  6407. /**
  6408. * Subtracts the given scalar value from all components of this instance.
  6409. *
  6410. * @param {number} s - The scalar to subtract.
  6411. * @return {Vector4} A reference to this vector.
  6412. */
  6413. subScalar( s ) {
  6414. this.x -= s;
  6415. this.y -= s;
  6416. this.z -= s;
  6417. this.w -= s;
  6418. return this;
  6419. }
  6420. /**
  6421. * Subtracts the given vectors and stores the result in this instance.
  6422. *
  6423. * @param {Vector4} a - The first vector.
  6424. * @param {Vector4} b - The second vector.
  6425. * @return {Vector4} A reference to this vector.
  6426. */
  6427. subVectors( a, b ) {
  6428. this.x = a.x - b.x;
  6429. this.y = a.y - b.y;
  6430. this.z = a.z - b.z;
  6431. this.w = a.w - b.w;
  6432. return this;
  6433. }
  6434. /**
  6435. * Multiplies the given vector with this instance.
  6436. *
  6437. * @param {Vector4} v - The vector to multiply.
  6438. * @return {Vector4} A reference to this vector.
  6439. */
  6440. multiply( 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. * Multiplies the given scalar value with all components of this instance.
  6449. *
  6450. * @param {number} scalar - The scalar to multiply.
  6451. * @return {Vector4} A reference to this vector.
  6452. */
  6453. multiplyScalar( scalar ) {
  6454. this.x *= scalar;
  6455. this.y *= scalar;
  6456. this.z *= scalar;
  6457. this.w *= scalar;
  6458. return this;
  6459. }
  6460. /**
  6461. * Multiplies this vector with the given 4x4 matrix.
  6462. *
  6463. * @param {Matrix4} m - The 4x4 matrix.
  6464. * @return {Vector4} A reference to this vector.
  6465. */
  6466. applyMatrix4( m ) {
  6467. const x = this.x, y = this.y, z = this.z, w = this.w;
  6468. const e = m.elements;
  6469. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6470. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6471. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6472. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6473. return this;
  6474. }
  6475. /**
  6476. * Divides this instance by the given vector.
  6477. *
  6478. * @param {Vector4} v - The vector to divide.
  6479. * @return {Vector4} A reference to this vector.
  6480. */
  6481. divide( v ) {
  6482. this.x /= v.x;
  6483. this.y /= v.y;
  6484. this.z /= v.z;
  6485. this.w /= v.w;
  6486. return this;
  6487. }
  6488. /**
  6489. * Divides this vector by the given scalar.
  6490. *
  6491. * @param {number} scalar - The scalar to divide.
  6492. * @return {Vector4} A reference to this vector.
  6493. */
  6494. divideScalar( scalar ) {
  6495. return this.multiplyScalar( 1 / scalar );
  6496. }
  6497. /**
  6498. * Sets the x, y and z components of this
  6499. * vector to the quaternion's axis and w to the angle.
  6500. *
  6501. * @param {Quaternion} q - The Quaternion to set.
  6502. * @return {Vector4} A reference to this vector.
  6503. */
  6504. setAxisAngleFromQuaternion( q ) {
  6505. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6506. // q is assumed to be normalized
  6507. this.w = 2 * Math.acos( q.w );
  6508. const s = Math.sqrt( 1 - q.w * q.w );
  6509. if ( s < 0.0001 ) {
  6510. this.x = 1;
  6511. this.y = 0;
  6512. this.z = 0;
  6513. } else {
  6514. this.x = q.x / s;
  6515. this.y = q.y / s;
  6516. this.z = q.z / s;
  6517. }
  6518. return this;
  6519. }
  6520. /**
  6521. * Sets the x, y and z components of this
  6522. * vector to the axis of rotation and w to the angle.
  6523. *
  6524. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6525. * @return {Vector4} A reference to this vector.
  6526. */
  6527. setAxisAngleFromRotationMatrix( m ) {
  6528. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6529. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6530. let angle, x, y, z; // variables for result
  6531. const epsilon = 0.01, // margin to allow for rounding errors
  6532. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6533. te = m.elements,
  6534. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6535. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6536. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6537. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6538. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6539. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6540. // singularity found
  6541. // first check for identity matrix which must have +1 for all terms
  6542. // in leading diagonal and zero in other terms
  6543. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6544. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6545. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6546. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6547. // this singularity is identity matrix so angle = 0
  6548. this.set( 1, 0, 0, 0 );
  6549. return this; // zero angle, arbitrary axis
  6550. }
  6551. // otherwise this singularity is angle = 180
  6552. angle = Math.PI;
  6553. const xx = ( m11 + 1 ) / 2;
  6554. const yy = ( m22 + 1 ) / 2;
  6555. const zz = ( m33 + 1 ) / 2;
  6556. const xy = ( m12 + m21 ) / 4;
  6557. const xz = ( m13 + m31 ) / 4;
  6558. const yz = ( m23 + m32 ) / 4;
  6559. if ( ( xx > yy ) && ( xx > zz ) ) {
  6560. // m11 is the largest diagonal term
  6561. if ( xx < epsilon ) {
  6562. x = 0;
  6563. y = 0.707106781;
  6564. z = 0.707106781;
  6565. } else {
  6566. x = Math.sqrt( xx );
  6567. y = xy / x;
  6568. z = xz / x;
  6569. }
  6570. } else if ( yy > zz ) {
  6571. // m22 is the largest diagonal term
  6572. if ( yy < epsilon ) {
  6573. x = 0.707106781;
  6574. y = 0;
  6575. z = 0.707106781;
  6576. } else {
  6577. y = Math.sqrt( yy );
  6578. x = xy / y;
  6579. z = yz / y;
  6580. }
  6581. } else {
  6582. // m33 is the largest diagonal term so base result on this
  6583. if ( zz < epsilon ) {
  6584. x = 0.707106781;
  6585. y = 0.707106781;
  6586. z = 0;
  6587. } else {
  6588. z = Math.sqrt( zz );
  6589. x = xz / z;
  6590. y = yz / z;
  6591. }
  6592. }
  6593. this.set( x, y, z, angle );
  6594. return this; // return 180 deg rotation
  6595. }
  6596. // as we have reached here there are no singularities so we can handle normally
  6597. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6598. ( m13 - m31 ) * ( m13 - m31 ) +
  6599. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6600. if ( Math.abs( s ) < 0.001 ) s = 1;
  6601. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6602. // caught by singularity test above, but I've left it in just in case
  6603. this.x = ( m32 - m23 ) / s;
  6604. this.y = ( m13 - m31 ) / s;
  6605. this.z = ( m21 - m12 ) / s;
  6606. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6607. return this;
  6608. }
  6609. /**
  6610. * Sets the vector components to the position elements of the
  6611. * given transformation matrix.
  6612. *
  6613. * @param {Matrix4} m - The 4x4 matrix.
  6614. * @return {Vector4} A reference to this vector.
  6615. */
  6616. setFromMatrixPosition( m ) {
  6617. const e = m.elements;
  6618. this.x = e[ 12 ];
  6619. this.y = e[ 13 ];
  6620. this.z = e[ 14 ];
  6621. this.w = e[ 15 ];
  6622. return this;
  6623. }
  6624. /**
  6625. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6626. * value, replace that value with the corresponding min value.
  6627. *
  6628. * @param {Vector4} v - The vector.
  6629. * @return {Vector4} A reference to this vector.
  6630. */
  6631. min( v ) {
  6632. this.x = Math.min( this.x, v.x );
  6633. this.y = Math.min( this.y, v.y );
  6634. this.z = Math.min( this.z, v.z );
  6635. this.w = Math.min( this.w, v.w );
  6636. return this;
  6637. }
  6638. /**
  6639. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6640. * value, replace that value with the corresponding max value.
  6641. *
  6642. * @param {Vector4} v - The vector.
  6643. * @return {Vector4} A reference to this vector.
  6644. */
  6645. max( v ) {
  6646. this.x = Math.max( this.x, v.x );
  6647. this.y = Math.max( this.y, v.y );
  6648. this.z = Math.max( this.z, v.z );
  6649. this.w = Math.max( this.w, v.w );
  6650. return this;
  6651. }
  6652. /**
  6653. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6654. * value, it is replaced by the corresponding value.
  6655. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6656. * it is replaced by the corresponding value.
  6657. *
  6658. * @param {Vector4} min - The minimum x, y and z values.
  6659. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6660. * @return {Vector4} A reference to this vector.
  6661. */
  6662. clamp( min, max ) {
  6663. // assumes min < max, componentwise
  6664. this.x = clamp( this.x, min.x, max.x );
  6665. this.y = clamp( this.y, min.y, max.y );
  6666. this.z = clamp( this.z, min.z, max.z );
  6667. this.w = clamp( this.w, min.w, max.w );
  6668. return this;
  6669. }
  6670. /**
  6671. * If this vector's x, y, z or w values are greater than the max value, they are
  6672. * replaced by the max value.
  6673. * If this vector's x, y, z or w values are less than the min value, they are
  6674. * replaced by the min value.
  6675. *
  6676. * @param {number} minVal - The minimum value the components will be clamped to.
  6677. * @param {number} maxVal - The maximum value the components will be clamped to.
  6678. * @return {Vector4} A reference to this vector.
  6679. */
  6680. clampScalar( minVal, maxVal ) {
  6681. this.x = clamp( this.x, minVal, maxVal );
  6682. this.y = clamp( this.y, minVal, maxVal );
  6683. this.z = clamp( this.z, minVal, maxVal );
  6684. this.w = clamp( this.w, minVal, maxVal );
  6685. return this;
  6686. }
  6687. /**
  6688. * If this vector's length is greater than the max value, it is replaced by
  6689. * the max value.
  6690. * If this vector's length is less than the min value, it is replaced by the
  6691. * min value.
  6692. *
  6693. * @param {number} min - The minimum value the vector length will be clamped to.
  6694. * @param {number} max - The maximum value the vector length will be clamped to.
  6695. * @return {Vector4} A reference to this vector.
  6696. */
  6697. clampLength( min, max ) {
  6698. const length = this.length();
  6699. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6700. }
  6701. /**
  6702. * The components of this vector are rounded down to the nearest integer value.
  6703. *
  6704. * @return {Vector4} A reference to this vector.
  6705. */
  6706. floor() {
  6707. this.x = Math.floor( this.x );
  6708. this.y = Math.floor( this.y );
  6709. this.z = Math.floor( this.z );
  6710. this.w = Math.floor( this.w );
  6711. return this;
  6712. }
  6713. /**
  6714. * The components of this vector are rounded up to the nearest integer value.
  6715. *
  6716. * @return {Vector4} A reference to this vector.
  6717. */
  6718. ceil() {
  6719. this.x = Math.ceil( this.x );
  6720. this.y = Math.ceil( this.y );
  6721. this.z = Math.ceil( this.z );
  6722. this.w = Math.ceil( this.w );
  6723. return this;
  6724. }
  6725. /**
  6726. * The components of this vector are rounded to the nearest integer value
  6727. *
  6728. * @return {Vector4} A reference to this vector.
  6729. */
  6730. round() {
  6731. this.x = Math.round( this.x );
  6732. this.y = Math.round( this.y );
  6733. this.z = Math.round( this.z );
  6734. this.w = Math.round( this.w );
  6735. return this;
  6736. }
  6737. /**
  6738. * The components of this vector are rounded towards zero (up if negative,
  6739. * down if positive) to an integer value.
  6740. *
  6741. * @return {Vector4} A reference to this vector.
  6742. */
  6743. roundToZero() {
  6744. this.x = Math.trunc( this.x );
  6745. this.y = Math.trunc( this.y );
  6746. this.z = Math.trunc( this.z );
  6747. this.w = Math.trunc( this.w );
  6748. return this;
  6749. }
  6750. /**
  6751. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6752. *
  6753. * @return {Vector4} A reference to this vector.
  6754. */
  6755. negate() {
  6756. this.x = - this.x;
  6757. this.y = - this.y;
  6758. this.z = - this.z;
  6759. this.w = - this.w;
  6760. return this;
  6761. }
  6762. /**
  6763. * Calculates the dot product of the given vector with this instance.
  6764. *
  6765. * @param {Vector4} v - The vector to compute the dot product with.
  6766. * @return {number} The result of the dot product.
  6767. */
  6768. dot( v ) {
  6769. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6770. }
  6771. /**
  6772. * Computes the square of the Euclidean length (straight-line length) from
  6773. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6774. * compare the length squared instead as it is slightly more efficient to calculate.
  6775. *
  6776. * @return {number} The square length of this vector.
  6777. */
  6778. lengthSq() {
  6779. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6780. }
  6781. /**
  6782. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6783. *
  6784. * @return {number} The length of this vector.
  6785. */
  6786. length() {
  6787. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6788. }
  6789. /**
  6790. * Computes the Manhattan length of this vector.
  6791. *
  6792. * @return {number} The length of this vector.
  6793. */
  6794. manhattanLength() {
  6795. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6796. }
  6797. /**
  6798. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6799. * with the same direction as this one, but with a vector length of `1`.
  6800. *
  6801. * @return {Vector4} A reference to this vector.
  6802. */
  6803. normalize() {
  6804. return this.divideScalar( this.length() || 1 );
  6805. }
  6806. /**
  6807. * Sets this vector to a vector with the same direction as this one, but
  6808. * with the specified length.
  6809. *
  6810. * @param {number} length - The new length of this vector.
  6811. * @return {Vector4} A reference to this vector.
  6812. */
  6813. setLength( length ) {
  6814. return this.normalize().multiplyScalar( length );
  6815. }
  6816. /**
  6817. * Linearly interpolates between the given vector and this instance, where
  6818. * alpha is the percent distance along the line - alpha = 0 will be this
  6819. * vector, and alpha = 1 will be the given one.
  6820. *
  6821. * @param {Vector4} v - The vector to interpolate towards.
  6822. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6823. * @return {Vector4} A reference to this vector.
  6824. */
  6825. lerp( v, alpha ) {
  6826. this.x += ( v.x - this.x ) * alpha;
  6827. this.y += ( v.y - this.y ) * alpha;
  6828. this.z += ( v.z - this.z ) * alpha;
  6829. this.w += ( v.w - this.w ) * alpha;
  6830. return this;
  6831. }
  6832. /**
  6833. * Linearly interpolates between the given vectors, where alpha is the percent
  6834. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6835. * be the second one. The result is stored in this instance.
  6836. *
  6837. * @param {Vector4} v1 - The first vector.
  6838. * @param {Vector4} v2 - The second vector.
  6839. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6840. * @return {Vector4} A reference to this vector.
  6841. */
  6842. lerpVectors( v1, v2, alpha ) {
  6843. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6844. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6845. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6846. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6847. return this;
  6848. }
  6849. /**
  6850. * Returns `true` if this vector is equal with the given one.
  6851. *
  6852. * @param {Vector4} v - The vector to test for equality.
  6853. * @return {boolean} Whether this vector is equal with the given one.
  6854. */
  6855. equals( v ) {
  6856. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6857. }
  6858. /**
  6859. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6860. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6861. *
  6862. * @param {Array<number>} array - An array holding the vector component values.
  6863. * @param {number} [offset=0] - The offset into the array.
  6864. * @return {Vector4} A reference to this vector.
  6865. */
  6866. fromArray( array, offset = 0 ) {
  6867. this.x = array[ offset ];
  6868. this.y = array[ offset + 1 ];
  6869. this.z = array[ offset + 2 ];
  6870. this.w = array[ offset + 3 ];
  6871. return this;
  6872. }
  6873. /**
  6874. * Writes the components of this vector to the given array. If no array is provided,
  6875. * the method returns a new instance.
  6876. *
  6877. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6878. * @param {number} [offset=0] - Index of the first element in the array.
  6879. * @return {Array<number>} The vector components.
  6880. */
  6881. toArray( array = [], offset = 0 ) {
  6882. array[ offset ] = this.x;
  6883. array[ offset + 1 ] = this.y;
  6884. array[ offset + 2 ] = this.z;
  6885. array[ offset + 3 ] = this.w;
  6886. return array;
  6887. }
  6888. /**
  6889. * Sets the components of this vector from the given buffer attribute.
  6890. *
  6891. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6892. * @param {number} index - The index into the attribute.
  6893. * @return {Vector4} A reference to this vector.
  6894. */
  6895. fromBufferAttribute( attribute, index ) {
  6896. this.x = attribute.getX( index );
  6897. this.y = attribute.getY( index );
  6898. this.z = attribute.getZ( index );
  6899. this.w = attribute.getW( index );
  6900. return this;
  6901. }
  6902. /**
  6903. * Sets each component of this vector to a pseudo-random value between `0` and
  6904. * `1`, excluding `1`.
  6905. *
  6906. * @return {Vector4} A reference to this vector.
  6907. */
  6908. random() {
  6909. this.x = Math.random();
  6910. this.y = Math.random();
  6911. this.z = Math.random();
  6912. this.w = Math.random();
  6913. return this;
  6914. }
  6915. *[ Symbol.iterator ]() {
  6916. yield this.x;
  6917. yield this.y;
  6918. yield this.z;
  6919. yield this.w;
  6920. }
  6921. }
  6922. /**
  6923. * A render target is a buffer where the video card draws pixels for a scene
  6924. * that is being rendered in the background. It is used in different effects,
  6925. * such as applying postprocessing to a rendered image before displaying it
  6926. * on the screen.
  6927. *
  6928. * @augments EventDispatcher
  6929. */
  6930. class RenderTarget extends EventDispatcher {
  6931. /**
  6932. * Render target options.
  6933. *
  6934. * @typedef {Object} RenderTarget~Options
  6935. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6936. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6937. * @property {number} [minFilter=LinearFilter] - The min filter.
  6938. * @property {number} [format=RGBAFormat] - The texture format.
  6939. * @property {number} [type=UnsignedByteType] - The texture type.
  6940. * @property {?string} [internalFormat=null] - The texture's internal format.
  6941. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6942. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6943. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6944. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6945. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6946. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6947. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6948. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6949. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6950. * @property {number} [samples=0] - The MSAA samples count.
  6951. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6952. * @property {number} [depth=1] - The texture depth.
  6953. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6954. */
  6955. /**
  6956. * Constructs a new render target.
  6957. *
  6958. * @param {number} [width=1] - The width of the render target.
  6959. * @param {number} [height=1] - The height of the render target.
  6960. * @param {RenderTarget~Options} [options] - The configuration object.
  6961. */
  6962. constructor( width = 1, height = 1, options = {} ) {
  6963. super();
  6964. options = Object.assign( {
  6965. generateMipmaps: false,
  6966. internalFormat: null,
  6967. minFilter: LinearFilter,
  6968. depthBuffer: true,
  6969. stencilBuffer: false,
  6970. resolveDepthBuffer: true,
  6971. resolveStencilBuffer: true,
  6972. depthTexture: null,
  6973. samples: 0,
  6974. count: 1,
  6975. depth: 1,
  6976. multiview: false
  6977. }, options );
  6978. /**
  6979. * This flag can be used for type testing.
  6980. *
  6981. * @type {boolean}
  6982. * @readonly
  6983. * @default true
  6984. */
  6985. this.isRenderTarget = true;
  6986. /**
  6987. * The width of the render target.
  6988. *
  6989. * @type {number}
  6990. * @default 1
  6991. */
  6992. this.width = width;
  6993. /**
  6994. * The height of the render target.
  6995. *
  6996. * @type {number}
  6997. * @default 1
  6998. */
  6999. this.height = height;
  7000. /**
  7001. * The depth of the render target.
  7002. *
  7003. * @type {number}
  7004. * @default 1
  7005. */
  7006. this.depth = options.depth;
  7007. /**
  7008. * A rectangular area inside the render target's viewport. Fragments that are
  7009. * outside the area will be discarded.
  7010. *
  7011. * @type {Vector4}
  7012. * @default (0,0,width,height)
  7013. */
  7014. this.scissor = new Vector4( 0, 0, width, height );
  7015. /**
  7016. * Indicates whether the scissor test should be enabled when rendering into
  7017. * this render target or not.
  7018. *
  7019. * @type {boolean}
  7020. * @default false
  7021. */
  7022. this.scissorTest = false;
  7023. /**
  7024. * A rectangular area representing the render target's viewport.
  7025. *
  7026. * @type {Vector4}
  7027. * @default (0,0,width,height)
  7028. */
  7029. this.viewport = new Vector4( 0, 0, width, height );
  7030. const image = { width: width, height: height, depth: options.depth };
  7031. const texture = new Texture( image );
  7032. /**
  7033. * An array of textures. Each color attachment is represented as a separate texture.
  7034. * Has at least a single entry for the default color attachment.
  7035. *
  7036. * @type {Array<Texture>}
  7037. */
  7038. this.textures = [];
  7039. const count = options.count;
  7040. for ( let i = 0; i < count; i ++ ) {
  7041. this.textures[ i ] = texture.clone();
  7042. this.textures[ i ].isRenderTargetTexture = true;
  7043. this.textures[ i ].renderTarget = this;
  7044. }
  7045. this._setTextureOptions( options );
  7046. /**
  7047. * Whether to allocate a depth buffer or not.
  7048. *
  7049. * @type {boolean}
  7050. * @default true
  7051. */
  7052. this.depthBuffer = options.depthBuffer;
  7053. /**
  7054. * Whether to allocate a stencil buffer or not.
  7055. *
  7056. * @type {boolean}
  7057. * @default false
  7058. */
  7059. this.stencilBuffer = options.stencilBuffer;
  7060. /**
  7061. * Whether to resolve the depth buffer or not.
  7062. *
  7063. * @type {boolean}
  7064. * @default true
  7065. */
  7066. this.resolveDepthBuffer = options.resolveDepthBuffer;
  7067. /**
  7068. * Whether to resolve the stencil buffer or not.
  7069. *
  7070. * @type {boolean}
  7071. * @default true
  7072. */
  7073. this.resolveStencilBuffer = options.resolveStencilBuffer;
  7074. this._depthTexture = null;
  7075. this.depthTexture = options.depthTexture;
  7076. /**
  7077. * The number of MSAA samples.
  7078. *
  7079. * A value of `0` disables MSAA.
  7080. *
  7081. * @type {number}
  7082. * @default 0
  7083. */
  7084. this.samples = options.samples;
  7085. /**
  7086. * Whether to this target is used in multiview rendering.
  7087. *
  7088. * @type {boolean}
  7089. * @default false
  7090. */
  7091. this.multiview = options.multiview;
  7092. }
  7093. _setTextureOptions( options = {} ) {
  7094. const values = {
  7095. minFilter: LinearFilter,
  7096. generateMipmaps: false,
  7097. flipY: false,
  7098. internalFormat: null
  7099. };
  7100. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  7101. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  7102. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  7103. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  7104. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  7105. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  7106. if ( options.format !== undefined ) values.format = options.format;
  7107. if ( options.type !== undefined ) values.type = options.type;
  7108. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  7109. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  7110. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  7111. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  7112. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  7113. for ( let i = 0; i < this.textures.length; i ++ ) {
  7114. const texture = this.textures[ i ];
  7115. texture.setValues( values );
  7116. }
  7117. }
  7118. /**
  7119. * The texture representing the default color attachment.
  7120. *
  7121. * @type {Texture}
  7122. */
  7123. get texture() {
  7124. return this.textures[ 0 ];
  7125. }
  7126. set texture( value ) {
  7127. this.textures[ 0 ] = value;
  7128. }
  7129. set depthTexture( current ) {
  7130. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  7131. if ( current !== null ) current.renderTarget = this;
  7132. this._depthTexture = current;
  7133. }
  7134. /**
  7135. * Instead of saving the depth in a renderbuffer, a texture
  7136. * can be used instead which is useful for further processing
  7137. * e.g. in context of post-processing.
  7138. *
  7139. * @type {?DepthTexture}
  7140. * @default null
  7141. */
  7142. get depthTexture() {
  7143. return this._depthTexture;
  7144. }
  7145. /**
  7146. * Sets the size of this render target.
  7147. *
  7148. * @param {number} width - The width.
  7149. * @param {number} height - The height.
  7150. * @param {number} [depth=1] - The depth.
  7151. */
  7152. setSize( width, height, depth = 1 ) {
  7153. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7154. this.width = width;
  7155. this.height = height;
  7156. this.depth = depth;
  7157. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7158. this.textures[ i ].image.width = width;
  7159. this.textures[ i ].image.height = height;
  7160. this.textures[ i ].image.depth = depth;
  7161. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7162. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7163. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7164. // both are evaluated on each call?
  7165. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7166. }
  7167. }
  7168. this.dispose();
  7169. }
  7170. this.viewport.set( 0, 0, width, height );
  7171. this.scissor.set( 0, 0, width, height );
  7172. }
  7173. /**
  7174. * Returns a new render target with copied values from this instance.
  7175. *
  7176. * @return {RenderTarget} A clone of this instance.
  7177. */
  7178. clone() {
  7179. return new this.constructor().copy( this );
  7180. }
  7181. /**
  7182. * Copies the settings of the given render target. This is a structural copy so
  7183. * no resources are shared between render targets after the copy. That includes
  7184. * all MRT textures and the depth texture.
  7185. *
  7186. * @param {RenderTarget} source - The render target to copy.
  7187. * @return {RenderTarget} A reference to this instance.
  7188. */
  7189. copy( source ) {
  7190. this.width = source.width;
  7191. this.height = source.height;
  7192. this.depth = source.depth;
  7193. this.scissor.copy( source.scissor );
  7194. this.scissorTest = source.scissorTest;
  7195. this.viewport.copy( source.viewport );
  7196. this.textures.length = 0;
  7197. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7198. this.textures[ i ] = source.textures[ i ].clone();
  7199. this.textures[ i ].isRenderTargetTexture = true;
  7200. this.textures[ i ].renderTarget = this;
  7201. // ensure image object is not shared, see #20328
  7202. const image = Object.assign( {}, source.textures[ i ].image );
  7203. this.textures[ i ].source = new Source( image );
  7204. }
  7205. this.depthBuffer = source.depthBuffer;
  7206. this.stencilBuffer = source.stencilBuffer;
  7207. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7208. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7209. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7210. this.samples = source.samples;
  7211. return this;
  7212. }
  7213. /**
  7214. * Frees the GPU-related resources allocated by this instance. Call this
  7215. * method whenever this instance is no longer used in your app.
  7216. *
  7217. * @fires RenderTarget#dispose
  7218. */
  7219. dispose() {
  7220. this.dispatchEvent( { type: 'dispose' } );
  7221. }
  7222. }
  7223. /**
  7224. * A render target used in context of {@link WebGLRenderer}.
  7225. *
  7226. * @augments RenderTarget
  7227. */
  7228. class WebGLRenderTarget extends RenderTarget {
  7229. /**
  7230. * Constructs a new 3D render target.
  7231. *
  7232. * @param {number} [width=1] - The width of the render target.
  7233. * @param {number} [height=1] - The height of the render target.
  7234. * @param {RenderTarget~Options} [options] - The configuration object.
  7235. */
  7236. constructor( width = 1, height = 1, options = {} ) {
  7237. super( width, height, options );
  7238. /**
  7239. * This flag can be used for type testing.
  7240. *
  7241. * @type {boolean}
  7242. * @readonly
  7243. * @default true
  7244. */
  7245. this.isWebGLRenderTarget = true;
  7246. }
  7247. }
  7248. /**
  7249. * Creates an array of textures directly from raw buffer data.
  7250. *
  7251. * @augments Texture
  7252. */
  7253. class DataArrayTexture extends Texture {
  7254. /**
  7255. * Constructs a new data array texture.
  7256. *
  7257. * @param {?TypedArray} [data=null] - The buffer data.
  7258. * @param {number} [width=1] - The width of the texture.
  7259. * @param {number} [height=1] - The height of the texture.
  7260. * @param {number} [depth=1] - The depth of the texture.
  7261. */
  7262. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7263. super( null );
  7264. /**
  7265. * This flag can be used for type testing.
  7266. *
  7267. * @type {boolean}
  7268. * @readonly
  7269. * @default true
  7270. */
  7271. this.isDataArrayTexture = true;
  7272. /**
  7273. * The image definition of a data texture.
  7274. *
  7275. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7276. */
  7277. this.image = { data, width, height, depth };
  7278. /**
  7279. * How the texture is sampled when a texel covers more than one pixel.
  7280. *
  7281. * Overwritten and set to `NearestFilter` by default.
  7282. *
  7283. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7284. * @default NearestFilter
  7285. */
  7286. this.magFilter = NearestFilter;
  7287. /**
  7288. * How the texture is sampled when a texel covers less than one pixel.
  7289. *
  7290. * Overwritten and set to `NearestFilter` by default.
  7291. *
  7292. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7293. * @default NearestFilter
  7294. */
  7295. this.minFilter = NearestFilter;
  7296. /**
  7297. * This defines how the texture is wrapped in the depth and corresponds to
  7298. * *W* in UVW mapping.
  7299. *
  7300. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7301. * @default ClampToEdgeWrapping
  7302. */
  7303. this.wrapR = ClampToEdgeWrapping;
  7304. /**
  7305. * Whether to generate mipmaps (if possible) for a texture.
  7306. *
  7307. * Overwritten and set to `false` by default.
  7308. *
  7309. * @type {boolean}
  7310. * @default false
  7311. */
  7312. this.generateMipmaps = false;
  7313. /**
  7314. * If set to `true`, the texture is flipped along the vertical axis when
  7315. * uploaded to the GPU.
  7316. *
  7317. * Overwritten and set to `false` by default.
  7318. *
  7319. * @type {boolean}
  7320. * @default false
  7321. */
  7322. this.flipY = false;
  7323. /**
  7324. * Specifies the alignment requirements for the start of each pixel row in memory.
  7325. *
  7326. * Overwritten and set to `1` by default.
  7327. *
  7328. * @type {boolean}
  7329. * @default 1
  7330. */
  7331. this.unpackAlignment = 1;
  7332. /**
  7333. * A set of all layers which need to be updated in the texture.
  7334. *
  7335. * @type {Set<number>}
  7336. */
  7337. this.layerUpdates = new Set();
  7338. }
  7339. /**
  7340. * Describes that a specific layer of the texture needs to be updated.
  7341. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7342. * entire data texture array is sent to the GPU. Marking specific
  7343. * layers will only transmit subsets of all mipmaps associated with a
  7344. * specific depth in the array which is often much more performant.
  7345. *
  7346. * @param {number} layerIndex - The layer index that should be updated.
  7347. */
  7348. addLayerUpdate( layerIndex ) {
  7349. this.layerUpdates.add( layerIndex );
  7350. }
  7351. /**
  7352. * Resets the layer updates registry.
  7353. */
  7354. clearLayerUpdates() {
  7355. this.layerUpdates.clear();
  7356. }
  7357. }
  7358. /**
  7359. * An array render target used in context of {@link WebGLRenderer}.
  7360. *
  7361. * @augments WebGLRenderTarget
  7362. */
  7363. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7364. /**
  7365. * Constructs a new array render target.
  7366. *
  7367. * @param {number} [width=1] - The width of the render target.
  7368. * @param {number} [height=1] - The height of the render target.
  7369. * @param {number} [depth=1] - The height of the render target.
  7370. * @param {RenderTarget~Options} [options] - The configuration object.
  7371. */
  7372. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7373. super( width, height, options );
  7374. /**
  7375. * This flag can be used for type testing.
  7376. *
  7377. * @type {boolean}
  7378. * @readonly
  7379. * @default true
  7380. */
  7381. this.isWebGLArrayRenderTarget = true;
  7382. this.depth = depth;
  7383. /**
  7384. * Overwritten with a different texture type.
  7385. *
  7386. * @type {DataArrayTexture}
  7387. */
  7388. this.texture = new DataArrayTexture( null, width, height, depth );
  7389. this._setTextureOptions( options );
  7390. this.texture.isRenderTargetTexture = true;
  7391. }
  7392. }
  7393. /**
  7394. * Creates a three-dimensional texture from raw data, with parameters to
  7395. * divide it into width, height, and depth.
  7396. *
  7397. * @augments Texture
  7398. */
  7399. class Data3DTexture extends Texture {
  7400. /**
  7401. * Constructs a new data array texture.
  7402. *
  7403. * @param {?TypedArray} [data=null] - The buffer data.
  7404. * @param {number} [width=1] - The width of the texture.
  7405. * @param {number} [height=1] - The height of the texture.
  7406. * @param {number} [depth=1] - The depth of the texture.
  7407. */
  7408. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7409. // We're going to add .setXXX() methods for setting properties later.
  7410. // Users can still set in Data3DTexture directly.
  7411. //
  7412. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7413. // texture.anisotropy = 16;
  7414. //
  7415. // See #14839
  7416. super( null );
  7417. /**
  7418. * This flag can be used for type testing.
  7419. *
  7420. * @type {boolean}
  7421. * @readonly
  7422. * @default true
  7423. */
  7424. this.isData3DTexture = true;
  7425. /**
  7426. * The image definition of a data texture.
  7427. *
  7428. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7429. */
  7430. this.image = { data, width, height, depth };
  7431. /**
  7432. * How the texture is sampled when a texel covers more than one pixel.
  7433. *
  7434. * Overwritten and set to `NearestFilter` by default.
  7435. *
  7436. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7437. * @default NearestFilter
  7438. */
  7439. this.magFilter = NearestFilter;
  7440. /**
  7441. * How the texture is sampled when a texel covers less than one pixel.
  7442. *
  7443. * Overwritten and set to `NearestFilter` by default.
  7444. *
  7445. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7446. * @default NearestFilter
  7447. */
  7448. this.minFilter = NearestFilter;
  7449. /**
  7450. * This defines how the texture is wrapped in the depth and corresponds to
  7451. * *W* in UVW mapping.
  7452. *
  7453. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7454. * @default ClampToEdgeWrapping
  7455. */
  7456. this.wrapR = ClampToEdgeWrapping;
  7457. /**
  7458. * Whether to generate mipmaps (if possible) for a texture.
  7459. *
  7460. * Overwritten and set to `false` by default.
  7461. *
  7462. * @type {boolean}
  7463. * @default false
  7464. */
  7465. this.generateMipmaps = false;
  7466. /**
  7467. * If set to `true`, the texture is flipped along the vertical axis when
  7468. * uploaded to the GPU.
  7469. *
  7470. * Overwritten and set to `false` by default.
  7471. *
  7472. * @type {boolean}
  7473. * @default false
  7474. */
  7475. this.flipY = false;
  7476. /**
  7477. * Specifies the alignment requirements for the start of each pixel row in memory.
  7478. *
  7479. * Overwritten and set to `1` by default.
  7480. *
  7481. * @type {boolean}
  7482. * @default 1
  7483. */
  7484. this.unpackAlignment = 1;
  7485. }
  7486. }
  7487. /**
  7488. * A 3D render target used in context of {@link WebGLRenderer}.
  7489. *
  7490. * @augments WebGLRenderTarget
  7491. */
  7492. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7493. /**
  7494. * Constructs a new 3D render target.
  7495. *
  7496. * @param {number} [width=1] - The width of the render target.
  7497. * @param {number} [height=1] - The height of the render target.
  7498. * @param {number} [depth=1] - The height of the render target.
  7499. * @param {RenderTarget~Options} [options] - The configuration object.
  7500. */
  7501. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7502. super( width, height, options );
  7503. /**
  7504. * This flag can be used for type testing.
  7505. *
  7506. * @type {boolean}
  7507. * @readonly
  7508. * @default true
  7509. */
  7510. this.isWebGL3DRenderTarget = true;
  7511. this.depth = depth;
  7512. /**
  7513. * Overwritten with a different texture type.
  7514. *
  7515. * @type {Data3DTexture}
  7516. */
  7517. this.texture = new Data3DTexture( null, width, height, depth );
  7518. this._setTextureOptions( options );
  7519. this.texture.isRenderTargetTexture = true;
  7520. }
  7521. }
  7522. /**
  7523. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7524. */
  7525. class Box3 {
  7526. /**
  7527. * Constructs a new bounding box.
  7528. *
  7529. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7530. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7531. */
  7532. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7533. /**
  7534. * This flag can be used for type testing.
  7535. *
  7536. * @type {boolean}
  7537. * @readonly
  7538. * @default true
  7539. */
  7540. this.isBox3 = true;
  7541. /**
  7542. * The lower boundary of the box.
  7543. *
  7544. * @type {Vector3}
  7545. */
  7546. this.min = min;
  7547. /**
  7548. * The upper boundary of the box.
  7549. *
  7550. * @type {Vector3}
  7551. */
  7552. this.max = max;
  7553. }
  7554. /**
  7555. * Sets the lower and upper boundaries of this box.
  7556. * Please note that this method only copies the values from the given objects.
  7557. *
  7558. * @param {Vector3} min - The lower boundary of the box.
  7559. * @param {Vector3} max - The upper boundary of the box.
  7560. * @return {Box3} A reference to this bounding box.
  7561. */
  7562. set( min, max ) {
  7563. this.min.copy( min );
  7564. this.max.copy( max );
  7565. return this;
  7566. }
  7567. /**
  7568. * Sets the upper and lower bounds of this box so it encloses the position data
  7569. * in the given array.
  7570. *
  7571. * @param {Array<number>} array - An array holding 3D position data.
  7572. * @return {Box3} A reference to this bounding box.
  7573. */
  7574. setFromArray( array ) {
  7575. this.makeEmpty();
  7576. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7577. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7578. }
  7579. return this;
  7580. }
  7581. /**
  7582. * Sets the upper and lower bounds of this box so it encloses the position data
  7583. * in the given buffer attribute.
  7584. *
  7585. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7586. * @return {Box3} A reference to this bounding box.
  7587. */
  7588. setFromBufferAttribute( attribute ) {
  7589. this.makeEmpty();
  7590. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7591. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7592. }
  7593. return this;
  7594. }
  7595. /**
  7596. * Sets the upper and lower bounds of this box so it encloses the position data
  7597. * in the given array.
  7598. *
  7599. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7600. * @return {Box3} A reference to this bounding box.
  7601. */
  7602. setFromPoints( points ) {
  7603. this.makeEmpty();
  7604. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7605. this.expandByPoint( points[ i ] );
  7606. }
  7607. return this;
  7608. }
  7609. /**
  7610. * Centers this box on the given center vector and sets this box's width, height and
  7611. * depth to the given size values.
  7612. *
  7613. * @param {Vector3} center - The center of the box.
  7614. * @param {Vector3} size - The x, y and z dimensions of the box.
  7615. * @return {Box3} A reference to this bounding box.
  7616. */
  7617. setFromCenterAndSize( center, size ) {
  7618. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7619. this.min.copy( center ).sub( halfSize );
  7620. this.max.copy( center ).add( halfSize );
  7621. return this;
  7622. }
  7623. /**
  7624. * Computes the world-axis-aligned bounding box for the given 3D object
  7625. * (including its children), accounting for the object's, and children's,
  7626. * world transforms. The function may result in a larger box than strictly necessary.
  7627. *
  7628. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7629. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7630. * world-axis-aligned bounding box at the expense of more computation.
  7631. * @return {Box3} A reference to this bounding box.
  7632. */
  7633. setFromObject( object, precise = false ) {
  7634. this.makeEmpty();
  7635. return this.expandByObject( object, precise );
  7636. }
  7637. /**
  7638. * Returns a new box with copied values from this instance.
  7639. *
  7640. * @return {Box3} A clone of this instance.
  7641. */
  7642. clone() {
  7643. return new this.constructor().copy( this );
  7644. }
  7645. /**
  7646. * Copies the values of the given box to this instance.
  7647. *
  7648. * @param {Box3} box - The box to copy.
  7649. * @return {Box3} A reference to this bounding box.
  7650. */
  7651. copy( box ) {
  7652. this.min.copy( box.min );
  7653. this.max.copy( box.max );
  7654. return this;
  7655. }
  7656. /**
  7657. * Makes this box empty which means in encloses a zero space in 3D.
  7658. *
  7659. * @return {Box3} A reference to this bounding box.
  7660. */
  7661. makeEmpty() {
  7662. this.min.x = this.min.y = this.min.z = + Infinity;
  7663. this.max.x = this.max.y = this.max.z = - Infinity;
  7664. return this;
  7665. }
  7666. /**
  7667. * Returns true if this box includes zero points within its bounds.
  7668. * Note that a box with equal lower and upper bounds still includes one
  7669. * point, the one both bounds share.
  7670. *
  7671. * @return {boolean} Whether this box is empty or not.
  7672. */
  7673. isEmpty() {
  7674. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7675. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7676. }
  7677. /**
  7678. * Returns the center point of this box.
  7679. *
  7680. * @param {Vector3} target - The target vector that is used to store the method's result.
  7681. * @return {Vector3} The center point.
  7682. */
  7683. getCenter( target ) {
  7684. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7685. }
  7686. /**
  7687. * Returns the dimensions of this box.
  7688. *
  7689. * @param {Vector3} target - The target vector that is used to store the method's result.
  7690. * @return {Vector3} The size.
  7691. */
  7692. getSize( target ) {
  7693. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7694. }
  7695. /**
  7696. * Expands the boundaries of this box to include the given point.
  7697. *
  7698. * @param {Vector3} point - The point that should be included by the bounding box.
  7699. * @return {Box3} A reference to this bounding box.
  7700. */
  7701. expandByPoint( point ) {
  7702. this.min.min( point );
  7703. this.max.max( point );
  7704. return this;
  7705. }
  7706. /**
  7707. * Expands this box equilaterally by the given vector. The width of this
  7708. * box will be expanded by the x component of the vector in both
  7709. * directions. The height of this box will be expanded by the y component of
  7710. * the vector in both directions. The depth of this box will be
  7711. * expanded by the z component of the vector in both directions.
  7712. *
  7713. * @param {Vector3} vector - The vector that should expand the bounding box.
  7714. * @return {Box3} A reference to this bounding box.
  7715. */
  7716. expandByVector( vector ) {
  7717. this.min.sub( vector );
  7718. this.max.add( vector );
  7719. return this;
  7720. }
  7721. /**
  7722. * Expands each dimension of the box by the given scalar. If negative, the
  7723. * dimensions of the box will be contracted.
  7724. *
  7725. * @param {number} scalar - The scalar value that should expand the bounding box.
  7726. * @return {Box3} A reference to this bounding box.
  7727. */
  7728. expandByScalar( scalar ) {
  7729. this.min.addScalar( - scalar );
  7730. this.max.addScalar( scalar );
  7731. return this;
  7732. }
  7733. /**
  7734. * Expands the boundaries of this box to include the given 3D object and
  7735. * its children, accounting for the object's, and children's, world
  7736. * transforms. The function may result in a larger box than strictly
  7737. * necessary (unless the precise parameter is set to true).
  7738. *
  7739. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7740. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7741. * as little as necessary at the expense of more computation.
  7742. * @return {Box3} A reference to this bounding box.
  7743. */
  7744. expandByObject( object, precise = false ) {
  7745. // Computes the world-axis-aligned bounding box of an object (including its children),
  7746. // accounting for both the object's, and children's, world transforms
  7747. object.updateWorldMatrix( false, false );
  7748. const geometry = object.geometry;
  7749. if ( geometry !== undefined ) {
  7750. const positionAttribute = geometry.getAttribute( 'position' );
  7751. // precise AABB computation based on vertex data requires at least a position attribute.
  7752. // instancing isn't supported so far and uses the normal (conservative) code path.
  7753. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7754. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7755. if ( object.isMesh === true ) {
  7756. object.getVertexPosition( i, _vector$b );
  7757. } else {
  7758. _vector$b.fromBufferAttribute( positionAttribute, i );
  7759. }
  7760. _vector$b.applyMatrix4( object.matrixWorld );
  7761. this.expandByPoint( _vector$b );
  7762. }
  7763. } else {
  7764. if ( object.boundingBox !== undefined ) {
  7765. // object-level bounding box
  7766. if ( object.boundingBox === null ) {
  7767. object.computeBoundingBox();
  7768. }
  7769. _box$4.copy( object.boundingBox );
  7770. } else {
  7771. // geometry-level bounding box
  7772. if ( geometry.boundingBox === null ) {
  7773. geometry.computeBoundingBox();
  7774. }
  7775. _box$4.copy( geometry.boundingBox );
  7776. }
  7777. _box$4.applyMatrix4( object.matrixWorld );
  7778. this.union( _box$4 );
  7779. }
  7780. }
  7781. const children = object.children;
  7782. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7783. this.expandByObject( children[ i ], precise );
  7784. }
  7785. return this;
  7786. }
  7787. /**
  7788. * Returns `true` if the given point lies within or on the boundaries of this box.
  7789. *
  7790. * @param {Vector3} point - The point to test.
  7791. * @return {boolean} Whether the bounding box contains the given point or not.
  7792. */
  7793. containsPoint( point ) {
  7794. return point.x >= this.min.x && point.x <= this.max.x &&
  7795. point.y >= this.min.y && point.y <= this.max.y &&
  7796. point.z >= this.min.z && point.z <= this.max.z;
  7797. }
  7798. /**
  7799. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7800. * If this box and the given one are identical, this function also returns `true`.
  7801. *
  7802. * @param {Box3} box - The bounding box to test.
  7803. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7804. */
  7805. containsBox( box ) {
  7806. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7807. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7808. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7809. }
  7810. /**
  7811. * Returns a point as a proportion of this box's width, height and depth.
  7812. *
  7813. * @param {Vector3} point - A point in 3D space.
  7814. * @param {Vector3} target - The target vector that is used to store the method's result.
  7815. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7816. */
  7817. getParameter( point, target ) {
  7818. // This can potentially have a divide by zero if the box
  7819. // has a size dimension of 0.
  7820. return target.set(
  7821. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7822. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7823. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7824. );
  7825. }
  7826. /**
  7827. * Returns `true` if the given bounding box intersects with this bounding box.
  7828. *
  7829. * @param {Box3} box - The bounding box to test.
  7830. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7831. */
  7832. intersectsBox( box ) {
  7833. // using 6 splitting planes to rule out intersections.
  7834. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7835. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7836. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7837. }
  7838. /**
  7839. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7840. *
  7841. * @param {Sphere} sphere - The bounding sphere to test.
  7842. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7843. */
  7844. intersectsSphere( sphere ) {
  7845. // Find the point on the AABB closest to the sphere center.
  7846. this.clampPoint( sphere.center, _vector$b );
  7847. // If that point is inside the sphere, the AABB and sphere intersect.
  7848. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7849. }
  7850. /**
  7851. * Returns `true` if the given plane intersects with this bounding box.
  7852. *
  7853. * @param {Plane} plane - The plane to test.
  7854. * @return {boolean} Whether the given plane intersects with this bounding box.
  7855. */
  7856. intersectsPlane( plane ) {
  7857. // We compute the minimum and maximum dot product values. If those values
  7858. // are on the same side (back or front) of the plane, then there is no intersection.
  7859. let min, max;
  7860. if ( plane.normal.x > 0 ) {
  7861. min = plane.normal.x * this.min.x;
  7862. max = plane.normal.x * this.max.x;
  7863. } else {
  7864. min = plane.normal.x * this.max.x;
  7865. max = plane.normal.x * this.min.x;
  7866. }
  7867. if ( plane.normal.y > 0 ) {
  7868. min += plane.normal.y * this.min.y;
  7869. max += plane.normal.y * this.max.y;
  7870. } else {
  7871. min += plane.normal.y * this.max.y;
  7872. max += plane.normal.y * this.min.y;
  7873. }
  7874. if ( plane.normal.z > 0 ) {
  7875. min += plane.normal.z * this.min.z;
  7876. max += plane.normal.z * this.max.z;
  7877. } else {
  7878. min += plane.normal.z * this.max.z;
  7879. max += plane.normal.z * this.min.z;
  7880. }
  7881. return ( min <= - plane.constant && max >= - plane.constant );
  7882. }
  7883. /**
  7884. * Returns `true` if the given triangle intersects with this bounding box.
  7885. *
  7886. * @param {Triangle} triangle - The triangle to test.
  7887. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7888. */
  7889. intersectsTriangle( triangle ) {
  7890. if ( this.isEmpty() ) {
  7891. return false;
  7892. }
  7893. // compute box center and extents
  7894. this.getCenter( _center );
  7895. _extents.subVectors( this.max, _center );
  7896. // translate triangle to aabb origin
  7897. _v0$2.subVectors( triangle.a, _center );
  7898. _v1$7.subVectors( triangle.b, _center );
  7899. _v2$4.subVectors( triangle.c, _center );
  7900. // compute edge vectors for triangle
  7901. _f0.subVectors( _v1$7, _v0$2 );
  7902. _f1.subVectors( _v2$4, _v1$7 );
  7903. _f2.subVectors( _v0$2, _v2$4 );
  7904. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7905. // 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
  7906. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7907. let axes = [
  7908. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7909. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7910. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7911. ];
  7912. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7913. return false;
  7914. }
  7915. // test 3 face normals from the aabb
  7916. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7917. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7918. return false;
  7919. }
  7920. // finally testing the face normal of the triangle
  7921. // use already existing triangle edge vectors here
  7922. _triangleNormal.crossVectors( _f0, _f1 );
  7923. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7924. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  7925. }
  7926. /**
  7927. * Clamps the given point within the bounds of this box.
  7928. *
  7929. * @param {Vector3} point - The point to clamp.
  7930. * @param {Vector3} target - The target vector that is used to store the method's result.
  7931. * @return {Vector3} The clamped point.
  7932. */
  7933. clampPoint( point, target ) {
  7934. return target.copy( point ).clamp( this.min, this.max );
  7935. }
  7936. /**
  7937. * Returns the euclidean distance from any edge of this box to the specified point. If
  7938. * the given point lies inside of this box, the distance will be `0`.
  7939. *
  7940. * @param {Vector3} point - The point to compute the distance to.
  7941. * @return {number} The euclidean distance.
  7942. */
  7943. distanceToPoint( point ) {
  7944. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7945. }
  7946. /**
  7947. * Returns a bounding sphere that encloses this bounding box.
  7948. *
  7949. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7950. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7951. */
  7952. getBoundingSphere( target ) {
  7953. if ( this.isEmpty() ) {
  7954. target.makeEmpty();
  7955. } else {
  7956. this.getCenter( target.center );
  7957. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7958. }
  7959. return target;
  7960. }
  7961. /**
  7962. * Computes the intersection of this bounding box and the given one, setting the upper
  7963. * bound of this box to the lesser of the two boxes' upper bounds and the
  7964. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7965. * there's no overlap, makes this box empty.
  7966. *
  7967. * @param {Box3} box - The bounding box to intersect with.
  7968. * @return {Box3} A reference to this bounding box.
  7969. */
  7970. intersect( box ) {
  7971. this.min.max( box.min );
  7972. this.max.min( box.max );
  7973. // 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.
  7974. if ( this.isEmpty() ) this.makeEmpty();
  7975. return this;
  7976. }
  7977. /**
  7978. * Computes the union of this box and another and the given one, setting the upper
  7979. * bound of this box to the greater of the two boxes' upper bounds and the
  7980. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7981. *
  7982. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7983. * @return {Box3} A reference to this bounding box.
  7984. */
  7985. union( box ) {
  7986. this.min.min( box.min );
  7987. this.max.max( box.max );
  7988. return this;
  7989. }
  7990. /**
  7991. * Transforms this bounding box by the given 4x4 transformation matrix.
  7992. *
  7993. * @param {Matrix4} matrix - The transformation matrix.
  7994. * @return {Box3} A reference to this bounding box.
  7995. */
  7996. applyMatrix4( matrix ) {
  7997. // transform of empty box is an empty box.
  7998. if ( this.isEmpty() ) return this;
  7999. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  8000. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  8001. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  8002. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  8003. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  8004. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  8005. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  8006. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  8007. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  8008. this.setFromPoints( _points );
  8009. return this;
  8010. }
  8011. /**
  8012. * Adds the given offset to both the upper and lower bounds of this bounding box,
  8013. * effectively moving it in 3D space.
  8014. *
  8015. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  8016. * @return {Box3} A reference to this bounding box.
  8017. */
  8018. translate( offset ) {
  8019. this.min.add( offset );
  8020. this.max.add( offset );
  8021. return this;
  8022. }
  8023. /**
  8024. * Returns `true` if this bounding box is equal with the given one.
  8025. *
  8026. * @param {Box3} box - The box to test for equality.
  8027. * @return {boolean} Whether this bounding box is equal with the given one.
  8028. */
  8029. equals( box ) {
  8030. return box.min.equals( this.min ) && box.max.equals( this.max );
  8031. }
  8032. /**
  8033. * Returns a serialized structure of the bounding box.
  8034. *
  8035. * @return {Object} Serialized structure with fields representing the object state.
  8036. */
  8037. toJSON() {
  8038. return {
  8039. min: this.min.toArray(),
  8040. max: this.max.toArray()
  8041. };
  8042. }
  8043. /**
  8044. * Returns a serialized structure of the bounding box.
  8045. *
  8046. * @param {Object} json - The serialized json to set the box from.
  8047. * @return {Box3} A reference to this bounding box.
  8048. */
  8049. fromJSON( json ) {
  8050. this.min.fromArray( json.min );
  8051. this.max.fromArray( json.max );
  8052. return this;
  8053. }
  8054. }
  8055. const _points = [
  8056. /*@__PURE__*/ new Vector3(),
  8057. /*@__PURE__*/ new Vector3(),
  8058. /*@__PURE__*/ new Vector3(),
  8059. /*@__PURE__*/ new Vector3(),
  8060. /*@__PURE__*/ new Vector3(),
  8061. /*@__PURE__*/ new Vector3(),
  8062. /*@__PURE__*/ new Vector3(),
  8063. /*@__PURE__*/ new Vector3()
  8064. ];
  8065. const _vector$b = /*@__PURE__*/ new Vector3();
  8066. const _box$4 = /*@__PURE__*/ new Box3();
  8067. // triangle centered vertices
  8068. const _v0$2 = /*@__PURE__*/ new Vector3();
  8069. const _v1$7 = /*@__PURE__*/ new Vector3();
  8070. const _v2$4 = /*@__PURE__*/ new Vector3();
  8071. // triangle edge vectors
  8072. const _f0 = /*@__PURE__*/ new Vector3();
  8073. const _f1 = /*@__PURE__*/ new Vector3();
  8074. const _f2 = /*@__PURE__*/ new Vector3();
  8075. const _center = /*@__PURE__*/ new Vector3();
  8076. const _extents = /*@__PURE__*/ new Vector3();
  8077. const _triangleNormal = /*@__PURE__*/ new Vector3();
  8078. const _testAxis = /*@__PURE__*/ new Vector3();
  8079. function satForAxes( axes, v0, v1, v2, extents ) {
  8080. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  8081. _testAxis.fromArray( axes, i );
  8082. // project the aabb onto the separating axis
  8083. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  8084. // project all 3 vertices of the triangle onto the separating axis
  8085. const p0 = v0.dot( _testAxis );
  8086. const p1 = v1.dot( _testAxis );
  8087. const p2 = v2.dot( _testAxis );
  8088. // actual test, basically see if either of the most extreme of the triangle points intersects r
  8089. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  8090. // points of the projected triangle are outside the projected half-length of the aabb
  8091. // the axis is separating and we can exit
  8092. return false;
  8093. }
  8094. }
  8095. return true;
  8096. }
  8097. const _box$3 = /*@__PURE__*/ new Box3();
  8098. const _v1$6 = /*@__PURE__*/ new Vector3();
  8099. const _v2$3 = /*@__PURE__*/ new Vector3();
  8100. /**
  8101. * An analytical 3D sphere defined by a center and radius. This class is mainly
  8102. * used as a Bounding Sphere for 3D objects.
  8103. */
  8104. class Sphere {
  8105. /**
  8106. * Constructs a new sphere.
  8107. *
  8108. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  8109. * @param {number} [radius=-1] - The radius of the sphere.
  8110. */
  8111. constructor( center = new Vector3(), radius = -1 ) {
  8112. /**
  8113. * This flag can be used for type testing.
  8114. *
  8115. * @type {boolean}
  8116. * @readonly
  8117. * @default true
  8118. */
  8119. this.isSphere = true;
  8120. /**
  8121. * The center of the sphere
  8122. *
  8123. * @type {Vector3}
  8124. */
  8125. this.center = center;
  8126. /**
  8127. * The radius of the sphere.
  8128. *
  8129. * @type {number}
  8130. */
  8131. this.radius = radius;
  8132. }
  8133. /**
  8134. * Sets the sphere's components by copying the given values.
  8135. *
  8136. * @param {Vector3} center - The center.
  8137. * @param {number} radius - The radius.
  8138. * @return {Sphere} A reference to this sphere.
  8139. */
  8140. set( center, radius ) {
  8141. this.center.copy( center );
  8142. this.radius = radius;
  8143. return this;
  8144. }
  8145. /**
  8146. * Computes the minimum bounding sphere for list of points.
  8147. * If the optional center point is given, it is used as the sphere's
  8148. * center. Otherwise, the center of the axis-aligned bounding box
  8149. * encompassing the points is calculated.
  8150. *
  8151. * @param {Array<Vector3>} points - A list of points in 3D space.
  8152. * @param {Vector3} [optionalCenter] - The center of the sphere.
  8153. * @return {Sphere} A reference to this sphere.
  8154. */
  8155. setFromPoints( points, optionalCenter ) {
  8156. const center = this.center;
  8157. if ( optionalCenter !== undefined ) {
  8158. center.copy( optionalCenter );
  8159. } else {
  8160. _box$3.setFromPoints( points ).getCenter( center );
  8161. }
  8162. let maxRadiusSq = 0;
  8163. for ( let i = 0, il = points.length; i < il; i ++ ) {
  8164. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  8165. }
  8166. this.radius = Math.sqrt( maxRadiusSq );
  8167. return this;
  8168. }
  8169. /**
  8170. * Copies the values of the given sphere to this instance.
  8171. *
  8172. * @param {Sphere} sphere - The sphere to copy.
  8173. * @return {Sphere} A reference to this sphere.
  8174. */
  8175. copy( sphere ) {
  8176. this.center.copy( sphere.center );
  8177. this.radius = sphere.radius;
  8178. return this;
  8179. }
  8180. /**
  8181. * Returns `true` if the sphere is empty (the radius set to a negative number).
  8182. *
  8183. * Spheres with a radius of `0` contain only their center point and are not
  8184. * considered to be empty.
  8185. *
  8186. * @return {boolean} Whether this sphere is empty or not.
  8187. */
  8188. isEmpty() {
  8189. return ( this.radius < 0 );
  8190. }
  8191. /**
  8192. * Makes this sphere empty which means in encloses a zero space in 3D.
  8193. *
  8194. * @return {Sphere} A reference to this sphere.
  8195. */
  8196. makeEmpty() {
  8197. this.center.set( 0, 0, 0 );
  8198. this.radius = -1;
  8199. return this;
  8200. }
  8201. /**
  8202. * Returns `true` if this sphere contains the given point inclusive of
  8203. * the surface of the sphere.
  8204. *
  8205. * @param {Vector3} point - The point to check.
  8206. * @return {boolean} Whether this sphere contains the given point or not.
  8207. */
  8208. containsPoint( point ) {
  8209. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  8210. }
  8211. /**
  8212. * Returns the closest distance from the boundary of the sphere to the
  8213. * given point. If the sphere contains the point, the distance will
  8214. * be negative.
  8215. *
  8216. * @param {Vector3} point - The point to compute the distance to.
  8217. * @return {number} The distance to the point.
  8218. */
  8219. distanceToPoint( point ) {
  8220. return ( point.distanceTo( this.center ) - this.radius );
  8221. }
  8222. /**
  8223. * Returns `true` if this sphere intersects with the given one.
  8224. *
  8225. * @param {Sphere} sphere - The sphere to test.
  8226. * @return {boolean} Whether this sphere intersects with the given one or not.
  8227. */
  8228. intersectsSphere( sphere ) {
  8229. const radiusSum = this.radius + sphere.radius;
  8230. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8231. }
  8232. /**
  8233. * Returns `true` if this sphere intersects with the given box.
  8234. *
  8235. * @param {Box3} box - The box to test.
  8236. * @return {boolean} Whether this sphere intersects with the given box or not.
  8237. */
  8238. intersectsBox( box ) {
  8239. return box.intersectsSphere( this );
  8240. }
  8241. /**
  8242. * Returns `true` if this sphere intersects with the given plane.
  8243. *
  8244. * @param {Plane} plane - The plane to test.
  8245. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8246. */
  8247. intersectsPlane( plane ) {
  8248. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8249. }
  8250. /**
  8251. * Clamps a point within the sphere. If the point is outside the sphere, it
  8252. * will clamp it to the closest point on the edge of the sphere. Points
  8253. * already inside the sphere will not be affected.
  8254. *
  8255. * @param {Vector3} point - The plane to clamp.
  8256. * @param {Vector3} target - The target vector that is used to store the method's result.
  8257. * @return {Vector3} The clamped point.
  8258. */
  8259. clampPoint( point, target ) {
  8260. const deltaLengthSq = this.center.distanceToSquared( point );
  8261. target.copy( point );
  8262. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8263. target.sub( this.center ).normalize();
  8264. target.multiplyScalar( this.radius ).add( this.center );
  8265. }
  8266. return target;
  8267. }
  8268. /**
  8269. * Returns a bounding box that encloses this sphere.
  8270. *
  8271. * @param {Box3} target - The target box that is used to store the method's result.
  8272. * @return {Box3} The bounding box that encloses this sphere.
  8273. */
  8274. getBoundingBox( target ) {
  8275. if ( this.isEmpty() ) {
  8276. // Empty sphere produces empty bounding box
  8277. target.makeEmpty();
  8278. return target;
  8279. }
  8280. target.set( this.center, this.center );
  8281. target.expandByScalar( this.radius );
  8282. return target;
  8283. }
  8284. /**
  8285. * Transforms this sphere with the given 4x4 transformation matrix.
  8286. *
  8287. * @param {Matrix4} matrix - The transformation matrix.
  8288. * @return {Sphere} A reference to this sphere.
  8289. */
  8290. applyMatrix4( matrix ) {
  8291. this.center.applyMatrix4( matrix );
  8292. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8293. return this;
  8294. }
  8295. /**
  8296. * Translates the sphere's center by the given offset.
  8297. *
  8298. * @param {Vector3} offset - The offset.
  8299. * @return {Sphere} A reference to this sphere.
  8300. */
  8301. translate( offset ) {
  8302. this.center.add( offset );
  8303. return this;
  8304. }
  8305. /**
  8306. * Expands the boundaries of this sphere to include the given point.
  8307. *
  8308. * @param {Vector3} point - The point to include.
  8309. * @return {Sphere} A reference to this sphere.
  8310. */
  8311. expandByPoint( point ) {
  8312. if ( this.isEmpty() ) {
  8313. this.center.copy( point );
  8314. this.radius = 0;
  8315. return this;
  8316. }
  8317. _v1$6.subVectors( point, this.center );
  8318. const lengthSq = _v1$6.lengthSq();
  8319. if ( lengthSq > ( this.radius * this.radius ) ) {
  8320. // calculate the minimal sphere
  8321. const length = Math.sqrt( lengthSq );
  8322. const delta = ( length - this.radius ) * 0.5;
  8323. this.center.addScaledVector( _v1$6, delta / length );
  8324. this.radius += delta;
  8325. }
  8326. return this;
  8327. }
  8328. /**
  8329. * Expands this sphere to enclose both the original sphere and the given sphere.
  8330. *
  8331. * @param {Sphere} sphere - The sphere to include.
  8332. * @return {Sphere} A reference to this sphere.
  8333. */
  8334. union( sphere ) {
  8335. if ( sphere.isEmpty() ) {
  8336. return this;
  8337. }
  8338. if ( this.isEmpty() ) {
  8339. this.copy( sphere );
  8340. return this;
  8341. }
  8342. if ( this.center.equals( sphere.center ) === true ) {
  8343. this.radius = Math.max( this.radius, sphere.radius );
  8344. } else {
  8345. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8346. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8347. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8348. }
  8349. return this;
  8350. }
  8351. /**
  8352. * Returns `true` if this sphere is equal with the given one.
  8353. *
  8354. * @param {Sphere} sphere - The sphere to test for equality.
  8355. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8356. */
  8357. equals( sphere ) {
  8358. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8359. }
  8360. /**
  8361. * Returns a new sphere with copied values from this instance.
  8362. *
  8363. * @return {Sphere} A clone of this instance.
  8364. */
  8365. clone() {
  8366. return new this.constructor().copy( this );
  8367. }
  8368. /**
  8369. * Returns a serialized structure of the bounding sphere.
  8370. *
  8371. * @return {Object} Serialized structure with fields representing the object state.
  8372. */
  8373. toJSON() {
  8374. return {
  8375. radius: this.radius,
  8376. center: this.center.toArray()
  8377. };
  8378. }
  8379. /**
  8380. * Returns a serialized structure of the bounding sphere.
  8381. *
  8382. * @param {Object} json - The serialized json to set the sphere from.
  8383. * @return {Sphere} A reference to this bounding sphere.
  8384. */
  8385. fromJSON( json ) {
  8386. this.radius = json.radius;
  8387. this.center.fromArray( json.center );
  8388. return this;
  8389. }
  8390. }
  8391. const _vector$a = /*@__PURE__*/ new Vector3();
  8392. const _segCenter = /*@__PURE__*/ new Vector3();
  8393. const _segDir = /*@__PURE__*/ new Vector3();
  8394. const _diff = /*@__PURE__*/ new Vector3();
  8395. const _edge1 = /*@__PURE__*/ new Vector3();
  8396. const _edge2 = /*@__PURE__*/ new Vector3();
  8397. const _normal$1 = /*@__PURE__*/ new Vector3();
  8398. /**
  8399. * A ray that emits from an origin in a certain direction. The class is used by
  8400. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8401. * mouse picking (working out what objects in the 3D space the mouse is over)
  8402. * amongst other things.
  8403. */
  8404. class Ray {
  8405. /**
  8406. * Constructs a new ray.
  8407. *
  8408. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8409. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8410. */
  8411. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8412. /**
  8413. * The origin of the ray.
  8414. *
  8415. * @type {Vector3}
  8416. */
  8417. this.origin = origin;
  8418. /**
  8419. * The (normalized) direction of the ray.
  8420. *
  8421. * @type {Vector3}
  8422. */
  8423. this.direction = direction;
  8424. }
  8425. /**
  8426. * Sets the ray's components by copying the given values.
  8427. *
  8428. * @param {Vector3} origin - The origin.
  8429. * @param {Vector3} direction - The direction.
  8430. * @return {Ray} A reference to this ray.
  8431. */
  8432. set( origin, direction ) {
  8433. this.origin.copy( origin );
  8434. this.direction.copy( direction );
  8435. return this;
  8436. }
  8437. /**
  8438. * Copies the values of the given ray to this instance.
  8439. *
  8440. * @param {Ray} ray - The ray to copy.
  8441. * @return {Ray} A reference to this ray.
  8442. */
  8443. copy( ray ) {
  8444. this.origin.copy( ray.origin );
  8445. this.direction.copy( ray.direction );
  8446. return this;
  8447. }
  8448. /**
  8449. * Returns a vector that is located at a given distance along this ray.
  8450. *
  8451. * @param {number} t - The distance along the ray to retrieve a position for.
  8452. * @param {Vector3} target - The target vector that is used to store the method's result.
  8453. * @return {Vector3} A position on the ray.
  8454. */
  8455. at( t, target ) {
  8456. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8457. }
  8458. /**
  8459. * Adjusts the direction of the ray to point at the given vector in world space.
  8460. *
  8461. * @param {Vector3} v - The target position.
  8462. * @return {Ray} A reference to this ray.
  8463. */
  8464. lookAt( v ) {
  8465. this.direction.copy( v ).sub( this.origin ).normalize();
  8466. return this;
  8467. }
  8468. /**
  8469. * Shift the origin of this ray along its direction by the given distance.
  8470. *
  8471. * @param {number} t - The distance along the ray to interpolate.
  8472. * @return {Ray} A reference to this ray.
  8473. */
  8474. recast( t ) {
  8475. this.origin.copy( this.at( t, _vector$a ) );
  8476. return this;
  8477. }
  8478. /**
  8479. * Returns the point along this ray that is closest to the given point.
  8480. *
  8481. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8482. * @param {Vector3} target - The target vector that is used to store the method's result.
  8483. * @return {Vector3} The closest point on this ray.
  8484. */
  8485. closestPointToPoint( point, target ) {
  8486. target.subVectors( point, this.origin );
  8487. const directionDistance = target.dot( this.direction );
  8488. if ( directionDistance < 0 ) {
  8489. return target.copy( this.origin );
  8490. }
  8491. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8492. }
  8493. /**
  8494. * Returns the distance of the closest approach between this ray and the given point.
  8495. *
  8496. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8497. * @return {number} The distance.
  8498. */
  8499. distanceToPoint( point ) {
  8500. return Math.sqrt( this.distanceSqToPoint( point ) );
  8501. }
  8502. /**
  8503. * Returns the squared distance of the closest approach between this ray and the given point.
  8504. *
  8505. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8506. * @return {number} The squared distance.
  8507. */
  8508. distanceSqToPoint( point ) {
  8509. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8510. // point behind the ray
  8511. if ( directionDistance < 0 ) {
  8512. return this.origin.distanceToSquared( point );
  8513. }
  8514. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8515. return _vector$a.distanceToSquared( point );
  8516. }
  8517. /**
  8518. * Returns the squared distance between this ray and the given line segment.
  8519. *
  8520. * @param {Vector3} v0 - The start point of the line segment.
  8521. * @param {Vector3} v1 - The end point of the line segment.
  8522. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8523. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8524. * @return {number} The squared distance.
  8525. */
  8526. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8527. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8528. // It returns the min distance between the ray and the segment
  8529. // defined by v0 and v1
  8530. // It can also set two optional targets :
  8531. // - The closest point on the ray
  8532. // - The closest point on the segment
  8533. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8534. _segDir.copy( v1 ).sub( v0 ).normalize();
  8535. _diff.copy( this.origin ).sub( _segCenter );
  8536. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8537. const a01 = - this.direction.dot( _segDir );
  8538. const b0 = _diff.dot( this.direction );
  8539. const b1 = - _diff.dot( _segDir );
  8540. const c = _diff.lengthSq();
  8541. const det = Math.abs( 1 - a01 * a01 );
  8542. let s0, s1, sqrDist, extDet;
  8543. if ( det > 0 ) {
  8544. // The ray and segment are not parallel.
  8545. s0 = a01 * b1 - b0;
  8546. s1 = a01 * b0 - b1;
  8547. extDet = segExtent * det;
  8548. if ( s0 >= 0 ) {
  8549. if ( s1 >= - extDet ) {
  8550. if ( s1 <= extDet ) {
  8551. // region 0
  8552. // Minimum at interior points of ray and segment.
  8553. const invDet = 1 / det;
  8554. s0 *= invDet;
  8555. s1 *= invDet;
  8556. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8557. } else {
  8558. // region 1
  8559. s1 = segExtent;
  8560. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8561. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8562. }
  8563. } else {
  8564. // region 5
  8565. s1 = - segExtent;
  8566. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8567. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8568. }
  8569. } else {
  8570. if ( s1 <= - extDet ) {
  8571. // region 4
  8572. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8573. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8574. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8575. } else if ( s1 <= extDet ) {
  8576. // region 3
  8577. s0 = 0;
  8578. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8579. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8580. } else {
  8581. // region 2
  8582. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8583. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8584. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8585. }
  8586. }
  8587. } else {
  8588. // Ray and segment are parallel.
  8589. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8590. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8591. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8592. }
  8593. if ( optionalPointOnRay ) {
  8594. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8595. }
  8596. if ( optionalPointOnSegment ) {
  8597. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8598. }
  8599. return sqrDist;
  8600. }
  8601. /**
  8602. * Intersects this ray with the given sphere, returning the intersection
  8603. * point or `null` if there is no intersection.
  8604. *
  8605. * @param {Sphere} sphere - The sphere to intersect.
  8606. * @param {Vector3} target - The target vector that is used to store the method's result.
  8607. * @return {?Vector3} The intersection point.
  8608. */
  8609. intersectSphere( sphere, target ) {
  8610. _vector$a.subVectors( sphere.center, this.origin );
  8611. const tca = _vector$a.dot( this.direction );
  8612. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8613. const radius2 = sphere.radius * sphere.radius;
  8614. if ( d2 > radius2 ) return null;
  8615. const thc = Math.sqrt( radius2 - d2 );
  8616. // t0 = first intersect point - entrance on front of sphere
  8617. const t0 = tca - thc;
  8618. // t1 = second intersect point - exit point on back of sphere
  8619. const t1 = tca + thc;
  8620. // test to see if t1 is behind the ray - if so, return null
  8621. if ( t1 < 0 ) return null;
  8622. // test to see if t0 is behind the ray:
  8623. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8624. // in order to always return an intersect point that is in front of the ray.
  8625. if ( t0 < 0 ) return this.at( t1, target );
  8626. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8627. return this.at( t0, target );
  8628. }
  8629. /**
  8630. * Returns `true` if this ray intersects with the given sphere.
  8631. *
  8632. * @param {Sphere} sphere - The sphere to intersect.
  8633. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8634. */
  8635. intersectsSphere( sphere ) {
  8636. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8637. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8638. }
  8639. /**
  8640. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8641. * does not intersect with the plane.
  8642. *
  8643. * @param {Plane} plane - The plane to compute the distance to.
  8644. * @return {?number} Whether this ray intersects with the given sphere or not.
  8645. */
  8646. distanceToPlane( plane ) {
  8647. const denominator = plane.normal.dot( this.direction );
  8648. if ( denominator === 0 ) {
  8649. // line is coplanar, return origin
  8650. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8651. return 0;
  8652. }
  8653. // Null is preferable to undefined since undefined means.... it is undefined
  8654. return null;
  8655. }
  8656. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8657. // Return if the ray never intersects the plane
  8658. return t >= 0 ? t : null;
  8659. }
  8660. /**
  8661. * Intersects this ray with the given plane, returning the intersection
  8662. * point or `null` if there is no intersection.
  8663. *
  8664. * @param {Plane} plane - The plane to intersect.
  8665. * @param {Vector3} target - The target vector that is used to store the method's result.
  8666. * @return {?Vector3} The intersection point.
  8667. */
  8668. intersectPlane( plane, target ) {
  8669. const t = this.distanceToPlane( plane );
  8670. if ( t === null ) {
  8671. return null;
  8672. }
  8673. return this.at( t, target );
  8674. }
  8675. /**
  8676. * Returns `true` if this ray intersects with the given plane.
  8677. *
  8678. * @param {Plane} plane - The plane to intersect.
  8679. * @return {boolean} Whether this ray intersects with the given plane or not.
  8680. */
  8681. intersectsPlane( plane ) {
  8682. // check if the ray lies on the plane first
  8683. const distToPoint = plane.distanceToPoint( this.origin );
  8684. if ( distToPoint === 0 ) {
  8685. return true;
  8686. }
  8687. const denominator = plane.normal.dot( this.direction );
  8688. if ( denominator * distToPoint < 0 ) {
  8689. return true;
  8690. }
  8691. // ray origin is behind the plane (and is pointing behind it)
  8692. return false;
  8693. }
  8694. /**
  8695. * Intersects this ray with the given bounding box, returning the intersection
  8696. * point or `null` if there is no intersection.
  8697. *
  8698. * @param {Box3} box - The box to intersect.
  8699. * @param {Vector3} target - The target vector that is used to store the method's result.
  8700. * @return {?Vector3} The intersection point.
  8701. */
  8702. intersectBox( box, target ) {
  8703. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8704. const invdirx = 1 / this.direction.x,
  8705. invdiry = 1 / this.direction.y,
  8706. invdirz = 1 / this.direction.z;
  8707. const origin = this.origin;
  8708. if ( invdirx >= 0 ) {
  8709. tmin = ( box.min.x - origin.x ) * invdirx;
  8710. tmax = ( box.max.x - origin.x ) * invdirx;
  8711. } else {
  8712. tmin = ( box.max.x - origin.x ) * invdirx;
  8713. tmax = ( box.min.x - origin.x ) * invdirx;
  8714. }
  8715. if ( invdiry >= 0 ) {
  8716. tymin = ( box.min.y - origin.y ) * invdiry;
  8717. tymax = ( box.max.y - origin.y ) * invdiry;
  8718. } else {
  8719. tymin = ( box.max.y - origin.y ) * invdiry;
  8720. tymax = ( box.min.y - origin.y ) * invdiry;
  8721. }
  8722. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8723. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8724. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8725. if ( invdirz >= 0 ) {
  8726. tzmin = ( box.min.z - origin.z ) * invdirz;
  8727. tzmax = ( box.max.z - origin.z ) * invdirz;
  8728. } else {
  8729. tzmin = ( box.max.z - origin.z ) * invdirz;
  8730. tzmax = ( box.min.z - origin.z ) * invdirz;
  8731. }
  8732. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8733. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8734. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8735. //return point closest to the ray (positive side)
  8736. if ( tmax < 0 ) return null;
  8737. return this.at( tmin >= 0 ? tmin : tmax, target );
  8738. }
  8739. /**
  8740. * Returns `true` if this ray intersects with the given box.
  8741. *
  8742. * @param {Box3} box - The box to intersect.
  8743. * @return {boolean} Whether this ray intersects with the given box or not.
  8744. */
  8745. intersectsBox( box ) {
  8746. return this.intersectBox( box, _vector$a ) !== null;
  8747. }
  8748. /**
  8749. * Intersects this ray with the given triangle, returning the intersection
  8750. * point or `null` if there is no intersection.
  8751. *
  8752. * @param {Vector3} a - The first vertex of the triangle.
  8753. * @param {Vector3} b - The second vertex of the triangle.
  8754. * @param {Vector3} c - The third vertex of the triangle.
  8755. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8756. * @param {Vector3} target - The target vector that is used to store the method's result.
  8757. * @return {?Vector3} The intersection point.
  8758. */
  8759. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8760. // Compute the offset origin, edges, and normal.
  8761. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8762. _edge1.subVectors( b, a );
  8763. _edge2.subVectors( c, a );
  8764. _normal$1.crossVectors( _edge1, _edge2 );
  8765. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8766. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8767. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8768. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8769. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8770. let DdN = this.direction.dot( _normal$1 );
  8771. let sign;
  8772. if ( DdN > 0 ) {
  8773. if ( backfaceCulling ) return null;
  8774. sign = 1;
  8775. } else if ( DdN < 0 ) {
  8776. sign = -1;
  8777. DdN = - DdN;
  8778. } else {
  8779. return null;
  8780. }
  8781. _diff.subVectors( this.origin, a );
  8782. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8783. // b1 < 0, no intersection
  8784. if ( DdQxE2 < 0 ) {
  8785. return null;
  8786. }
  8787. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8788. // b2 < 0, no intersection
  8789. if ( DdE1xQ < 0 ) {
  8790. return null;
  8791. }
  8792. // b1+b2 > 1, no intersection
  8793. if ( DdQxE2 + DdE1xQ > DdN ) {
  8794. return null;
  8795. }
  8796. // Line intersects triangle, check if ray does.
  8797. const QdN = - sign * _diff.dot( _normal$1 );
  8798. // t < 0, no intersection
  8799. if ( QdN < 0 ) {
  8800. return null;
  8801. }
  8802. // Ray intersects triangle.
  8803. return this.at( QdN / DdN, target );
  8804. }
  8805. /**
  8806. * Transforms this ray with the given 4x4 transformation matrix.
  8807. *
  8808. * @param {Matrix4} matrix4 - The transformation matrix.
  8809. * @return {Ray} A reference to this ray.
  8810. */
  8811. applyMatrix4( matrix4 ) {
  8812. this.origin.applyMatrix4( matrix4 );
  8813. this.direction.transformDirection( matrix4 );
  8814. return this;
  8815. }
  8816. /**
  8817. * Returns `true` if this ray is equal with the given one.
  8818. *
  8819. * @param {Ray} ray - The ray to test for equality.
  8820. * @return {boolean} Whether this ray is equal with the given one.
  8821. */
  8822. equals( ray ) {
  8823. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8824. }
  8825. /**
  8826. * Returns a new ray with copied values from this instance.
  8827. *
  8828. * @return {Ray} A clone of this instance.
  8829. */
  8830. clone() {
  8831. return new this.constructor().copy( this );
  8832. }
  8833. }
  8834. /**
  8835. * Represents a 4x4 matrix.
  8836. *
  8837. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8838. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  8839. *
  8840. * This allows a 3D vector representing a point in 3D space to undergo
  8841. * transformations such as translation, rotation, shear, scale, reflection,
  8842. * orthogonal or perspective projection and so on, by being multiplied by the
  8843. * matrix. This is known as `applying` the matrix to the vector.
  8844. *
  8845. * A Note on Row-Major and Column-Major Ordering:
  8846. *
  8847. * The constructor and {@link Matrix3#set} method take arguments in
  8848. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  8849. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8850. * This means that calling:
  8851. * ```js
  8852. * const m = new THREE.Matrix4();
  8853. * m.set( 11, 12, 13, 14,
  8854. * 21, 22, 23, 24,
  8855. * 31, 32, 33, 34,
  8856. * 41, 42, 43, 44 );
  8857. * ```
  8858. * will result in the elements array containing:
  8859. * ```js
  8860. * m.elements = [ 11, 21, 31, 41,
  8861. * 12, 22, 32, 42,
  8862. * 13, 23, 33, 43,
  8863. * 14, 24, 34, 44 ];
  8864. * ```
  8865. * and internally all calculations are performed using column-major ordering.
  8866. * However, as the actual ordering makes no difference mathematically and
  8867. * most people are used to thinking about matrices in row-major order, the
  8868. * three.js documentation shows matrices in row-major order. Just bear in
  8869. * mind that if you are reading the source code, you'll have to take the
  8870. * transpose of any matrices outlined here to make sense of the calculations.
  8871. */
  8872. class Matrix4 {
  8873. /**
  8874. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8875. * in row-major order. If no arguments are provided, the constructor
  8876. * initializes the matrix as an identity matrix.
  8877. *
  8878. * @param {number} [n11] - 1-1 matrix element.
  8879. * @param {number} [n12] - 1-2 matrix element.
  8880. * @param {number} [n13] - 1-3 matrix element.
  8881. * @param {number} [n14] - 1-4 matrix element.
  8882. * @param {number} [n21] - 2-1 matrix element.
  8883. * @param {number} [n22] - 2-2 matrix element.
  8884. * @param {number} [n23] - 2-3 matrix element.
  8885. * @param {number} [n24] - 2-4 matrix element.
  8886. * @param {number} [n31] - 3-1 matrix element.
  8887. * @param {number} [n32] - 3-2 matrix element.
  8888. * @param {number} [n33] - 3-3 matrix element.
  8889. * @param {number} [n34] - 3-4 matrix element.
  8890. * @param {number} [n41] - 4-1 matrix element.
  8891. * @param {number} [n42] - 4-2 matrix element.
  8892. * @param {number} [n43] - 4-3 matrix element.
  8893. * @param {number} [n44] - 4-4 matrix element.
  8894. */
  8895. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8896. /**
  8897. * This flag can be used for type testing.
  8898. *
  8899. * @type {boolean}
  8900. * @readonly
  8901. * @default true
  8902. */
  8903. Matrix4.prototype.isMatrix4 = true;
  8904. /**
  8905. * A column-major list of matrix values.
  8906. *
  8907. * @type {Array<number>}
  8908. */
  8909. this.elements = [
  8910. 1, 0, 0, 0,
  8911. 0, 1, 0, 0,
  8912. 0, 0, 1, 0,
  8913. 0, 0, 0, 1
  8914. ];
  8915. if ( n11 !== undefined ) {
  8916. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8917. }
  8918. }
  8919. /**
  8920. * Sets the elements of the matrix.The arguments are supposed to be
  8921. * in row-major order.
  8922. *
  8923. * @param {number} [n11] - 1-1 matrix element.
  8924. * @param {number} [n12] - 1-2 matrix element.
  8925. * @param {number} [n13] - 1-3 matrix element.
  8926. * @param {number} [n14] - 1-4 matrix element.
  8927. * @param {number} [n21] - 2-1 matrix element.
  8928. * @param {number} [n22] - 2-2 matrix element.
  8929. * @param {number} [n23] - 2-3 matrix element.
  8930. * @param {number} [n24] - 2-4 matrix element.
  8931. * @param {number} [n31] - 3-1 matrix element.
  8932. * @param {number} [n32] - 3-2 matrix element.
  8933. * @param {number} [n33] - 3-3 matrix element.
  8934. * @param {number} [n34] - 3-4 matrix element.
  8935. * @param {number} [n41] - 4-1 matrix element.
  8936. * @param {number} [n42] - 4-2 matrix element.
  8937. * @param {number} [n43] - 4-3 matrix element.
  8938. * @param {number} [n44] - 4-4 matrix element.
  8939. * @return {Matrix4} A reference to this matrix.
  8940. */
  8941. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8942. const te = this.elements;
  8943. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8944. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8945. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8946. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8947. return this;
  8948. }
  8949. /**
  8950. * Sets this matrix to the 4x4 identity matrix.
  8951. *
  8952. * @return {Matrix4} A reference to this matrix.
  8953. */
  8954. identity() {
  8955. this.set(
  8956. 1, 0, 0, 0,
  8957. 0, 1, 0, 0,
  8958. 0, 0, 1, 0,
  8959. 0, 0, 0, 1
  8960. );
  8961. return this;
  8962. }
  8963. /**
  8964. * Returns a matrix with copied values from this instance.
  8965. *
  8966. * @return {Matrix4} A clone of this instance.
  8967. */
  8968. clone() {
  8969. return new Matrix4().fromArray( this.elements );
  8970. }
  8971. /**
  8972. * Copies the values of the given matrix to this instance.
  8973. *
  8974. * @param {Matrix4} m - The matrix to copy.
  8975. * @return {Matrix4} A reference to this matrix.
  8976. */
  8977. copy( m ) {
  8978. const te = this.elements;
  8979. const me = m.elements;
  8980. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8981. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8982. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8983. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8984. return this;
  8985. }
  8986. /**
  8987. * Copies the translation component of the given matrix
  8988. * into this matrix's translation component.
  8989. *
  8990. * @param {Matrix4} m - The matrix to copy the translation component.
  8991. * @return {Matrix4} A reference to this matrix.
  8992. */
  8993. copyPosition( m ) {
  8994. const te = this.elements, me = m.elements;
  8995. te[ 12 ] = me[ 12 ];
  8996. te[ 13 ] = me[ 13 ];
  8997. te[ 14 ] = me[ 14 ];
  8998. return this;
  8999. }
  9000. /**
  9001. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  9002. *
  9003. * @param {Matrix3} m - The 3x3 matrix.
  9004. * @return {Matrix4} A reference to this matrix.
  9005. */
  9006. setFromMatrix3( m ) {
  9007. const me = m.elements;
  9008. this.set(
  9009. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  9010. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  9011. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  9012. 0, 0, 0, 1
  9013. );
  9014. return this;
  9015. }
  9016. /**
  9017. * Extracts the basis of this matrix into the three axis vectors provided.
  9018. *
  9019. * @param {Vector3} xAxis - The basis's x axis.
  9020. * @param {Vector3} yAxis - The basis's y axis.
  9021. * @param {Vector3} zAxis - The basis's z axis.
  9022. * @return {Matrix4} A reference to this matrix.
  9023. */
  9024. extractBasis( xAxis, yAxis, zAxis ) {
  9025. if ( this.determinant() === 0 ) {
  9026. xAxis.set( 1, 0, 0 );
  9027. yAxis.set( 0, 1, 0 );
  9028. zAxis.set( 0, 0, 1 );
  9029. return this;
  9030. }
  9031. xAxis.setFromMatrixColumn( this, 0 );
  9032. yAxis.setFromMatrixColumn( this, 1 );
  9033. zAxis.setFromMatrixColumn( this, 2 );
  9034. return this;
  9035. }
  9036. /**
  9037. * Sets the given basis vectors to this matrix.
  9038. *
  9039. * @param {Vector3} xAxis - The basis's x axis.
  9040. * @param {Vector3} yAxis - The basis's y axis.
  9041. * @param {Vector3} zAxis - The basis's z axis.
  9042. * @return {Matrix4} A reference to this matrix.
  9043. */
  9044. makeBasis( xAxis, yAxis, zAxis ) {
  9045. this.set(
  9046. xAxis.x, yAxis.x, zAxis.x, 0,
  9047. xAxis.y, yAxis.y, zAxis.y, 0,
  9048. xAxis.z, yAxis.z, zAxis.z, 0,
  9049. 0, 0, 0, 1
  9050. );
  9051. return this;
  9052. }
  9053. /**
  9054. * Extracts the rotation component of the given matrix
  9055. * into this matrix's rotation component.
  9056. *
  9057. * Note: This method does not support reflection matrices.
  9058. *
  9059. * @param {Matrix4} m - The matrix.
  9060. * @return {Matrix4} A reference to this matrix.
  9061. */
  9062. extractRotation( m ) {
  9063. if ( m.determinant() === 0 ) {
  9064. return this.identity();
  9065. }
  9066. const te = this.elements;
  9067. const me = m.elements;
  9068. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  9069. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  9070. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  9071. te[ 0 ] = me[ 0 ] * scaleX;
  9072. te[ 1 ] = me[ 1 ] * scaleX;
  9073. te[ 2 ] = me[ 2 ] * scaleX;
  9074. te[ 3 ] = 0;
  9075. te[ 4 ] = me[ 4 ] * scaleY;
  9076. te[ 5 ] = me[ 5 ] * scaleY;
  9077. te[ 6 ] = me[ 6 ] * scaleY;
  9078. te[ 7 ] = 0;
  9079. te[ 8 ] = me[ 8 ] * scaleZ;
  9080. te[ 9 ] = me[ 9 ] * scaleZ;
  9081. te[ 10 ] = me[ 10 ] * scaleZ;
  9082. te[ 11 ] = 0;
  9083. te[ 12 ] = 0;
  9084. te[ 13 ] = 0;
  9085. te[ 14 ] = 0;
  9086. te[ 15 ] = 1;
  9087. return this;
  9088. }
  9089. /**
  9090. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  9091. * the rotation specified by the given Euler angles. The rest of
  9092. * the matrix is set to the identity. Depending on the {@link Euler#order},
  9093. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  9094. * for a complete list.
  9095. *
  9096. * @param {Euler} euler - The Euler angles.
  9097. * @return {Matrix4} A reference to this matrix.
  9098. */
  9099. makeRotationFromEuler( euler ) {
  9100. const te = this.elements;
  9101. const x = euler.x, y = euler.y, z = euler.z;
  9102. const a = Math.cos( x ), b = Math.sin( x );
  9103. const c = Math.cos( y ), d = Math.sin( y );
  9104. const e = Math.cos( z ), f = Math.sin( z );
  9105. if ( euler.order === 'XYZ' ) {
  9106. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  9107. te[ 0 ] = c * e;
  9108. te[ 4 ] = - c * f;
  9109. te[ 8 ] = d;
  9110. te[ 1 ] = af + be * d;
  9111. te[ 5 ] = ae - bf * d;
  9112. te[ 9 ] = - b * c;
  9113. te[ 2 ] = bf - ae * d;
  9114. te[ 6 ] = be + af * d;
  9115. te[ 10 ] = a * c;
  9116. } else if ( euler.order === 'YXZ' ) {
  9117. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  9118. te[ 0 ] = ce + df * b;
  9119. te[ 4 ] = de * b - cf;
  9120. te[ 8 ] = a * d;
  9121. te[ 1 ] = a * f;
  9122. te[ 5 ] = a * e;
  9123. te[ 9 ] = - b;
  9124. te[ 2 ] = cf * b - de;
  9125. te[ 6 ] = df + ce * b;
  9126. te[ 10 ] = a * c;
  9127. } else if ( euler.order === 'ZXY' ) {
  9128. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  9129. te[ 0 ] = ce - df * b;
  9130. te[ 4 ] = - a * f;
  9131. te[ 8 ] = de + cf * b;
  9132. te[ 1 ] = cf + de * b;
  9133. te[ 5 ] = a * e;
  9134. te[ 9 ] = df - ce * b;
  9135. te[ 2 ] = - a * d;
  9136. te[ 6 ] = b;
  9137. te[ 10 ] = a * c;
  9138. } else if ( euler.order === 'ZYX' ) {
  9139. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  9140. te[ 0 ] = c * e;
  9141. te[ 4 ] = be * d - af;
  9142. te[ 8 ] = ae * d + bf;
  9143. te[ 1 ] = c * f;
  9144. te[ 5 ] = bf * d + ae;
  9145. te[ 9 ] = af * d - be;
  9146. te[ 2 ] = - d;
  9147. te[ 6 ] = b * c;
  9148. te[ 10 ] = a * c;
  9149. } else if ( euler.order === 'YZX' ) {
  9150. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9151. te[ 0 ] = c * e;
  9152. te[ 4 ] = bd - ac * f;
  9153. te[ 8 ] = bc * f + ad;
  9154. te[ 1 ] = f;
  9155. te[ 5 ] = a * e;
  9156. te[ 9 ] = - b * e;
  9157. te[ 2 ] = - d * e;
  9158. te[ 6 ] = ad * f + bc;
  9159. te[ 10 ] = ac - bd * f;
  9160. } else if ( euler.order === 'XZY' ) {
  9161. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9162. te[ 0 ] = c * e;
  9163. te[ 4 ] = - f;
  9164. te[ 8 ] = d * e;
  9165. te[ 1 ] = ac * f + bd;
  9166. te[ 5 ] = a * e;
  9167. te[ 9 ] = ad * f - bc;
  9168. te[ 2 ] = bc * f - ad;
  9169. te[ 6 ] = b * e;
  9170. te[ 10 ] = bd * f + ac;
  9171. }
  9172. // bottom row
  9173. te[ 3 ] = 0;
  9174. te[ 7 ] = 0;
  9175. te[ 11 ] = 0;
  9176. // last column
  9177. te[ 12 ] = 0;
  9178. te[ 13 ] = 0;
  9179. te[ 14 ] = 0;
  9180. te[ 15 ] = 1;
  9181. return this;
  9182. }
  9183. /**
  9184. * Sets the rotation component of this matrix to the rotation specified by
  9185. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  9186. * The rest of the matrix is set to the identity.
  9187. *
  9188. * @param {Quaternion} q - The Quaternion.
  9189. * @return {Matrix4} A reference to this matrix.
  9190. */
  9191. makeRotationFromQuaternion( q ) {
  9192. return this.compose( _zero, q, _one );
  9193. }
  9194. /**
  9195. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  9196. * `target`, and oriented by the up-direction.
  9197. *
  9198. * @param {Vector3} eye - The eye vector.
  9199. * @param {Vector3} target - The target vector.
  9200. * @param {Vector3} up - The up vector.
  9201. * @return {Matrix4} A reference to this matrix.
  9202. */
  9203. lookAt( eye, target, up ) {
  9204. const te = this.elements;
  9205. _z.subVectors( eye, target );
  9206. if ( _z.lengthSq() === 0 ) {
  9207. // eye and target are in the same position
  9208. _z.z = 1;
  9209. }
  9210. _z.normalize();
  9211. _x.crossVectors( up, _z );
  9212. if ( _x.lengthSq() === 0 ) {
  9213. // up and z are parallel
  9214. if ( Math.abs( up.z ) === 1 ) {
  9215. _z.x += 0.0001;
  9216. } else {
  9217. _z.z += 0.0001;
  9218. }
  9219. _z.normalize();
  9220. _x.crossVectors( up, _z );
  9221. }
  9222. _x.normalize();
  9223. _y.crossVectors( _z, _x );
  9224. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  9225. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  9226. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  9227. return this;
  9228. }
  9229. /**
  9230. * Post-multiplies this matrix by the given 4x4 matrix.
  9231. *
  9232. * @param {Matrix4} m - The matrix to multiply with.
  9233. * @return {Matrix4} A reference to this matrix.
  9234. */
  9235. multiply( m ) {
  9236. return this.multiplyMatrices( this, m );
  9237. }
  9238. /**
  9239. * Pre-multiplies this matrix by the given 4x4 matrix.
  9240. *
  9241. * @param {Matrix4} m - The matrix to multiply with.
  9242. * @return {Matrix4} A reference to this matrix.
  9243. */
  9244. premultiply( m ) {
  9245. return this.multiplyMatrices( m, this );
  9246. }
  9247. /**
  9248. * Multiples the given 4x4 matrices and stores the result
  9249. * in this matrix.
  9250. *
  9251. * @param {Matrix4} a - The first matrix.
  9252. * @param {Matrix4} b - The second matrix.
  9253. * @return {Matrix4} A reference to this matrix.
  9254. */
  9255. multiplyMatrices( a, b ) {
  9256. const ae = a.elements;
  9257. const be = b.elements;
  9258. const te = this.elements;
  9259. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9260. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9261. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9262. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9263. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9264. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9265. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9266. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9267. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9268. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9269. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9270. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9271. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9272. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9273. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9274. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9275. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9276. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9277. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9278. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9279. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9280. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9281. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9282. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9283. return this;
  9284. }
  9285. /**
  9286. * Multiplies every component of the matrix by the given scalar.
  9287. *
  9288. * @param {number} s - The scalar.
  9289. * @return {Matrix4} A reference to this matrix.
  9290. */
  9291. multiplyScalar( s ) {
  9292. const te = this.elements;
  9293. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9294. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9295. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9296. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9297. return this;
  9298. }
  9299. /**
  9300. * Computes and returns the determinant of this matrix.
  9301. *
  9302. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  9303. *
  9304. * @return {number} The determinant.
  9305. */
  9306. determinant() {
  9307. const te = this.elements;
  9308. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9309. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9310. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9311. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9312. const t11 = n23 * n34 - n24 * n33;
  9313. const t12 = n22 * n34 - n24 * n32;
  9314. const t13 = n22 * n33 - n23 * n32;
  9315. const t21 = n21 * n34 - n24 * n31;
  9316. const t22 = n21 * n33 - n23 * n31;
  9317. const t23 = n21 * n32 - n22 * n31;
  9318. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  9319. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  9320. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  9321. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  9322. }
  9323. /**
  9324. * Transposes this matrix in place.
  9325. *
  9326. * @return {Matrix4} A reference to this matrix.
  9327. */
  9328. transpose() {
  9329. const te = this.elements;
  9330. let tmp;
  9331. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9332. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9333. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9334. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9335. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9336. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9337. return this;
  9338. }
  9339. /**
  9340. * Sets the position component for this matrix from the given vector,
  9341. * without affecting the rest of the matrix.
  9342. *
  9343. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9344. * @param {number} y - The y component of the vector.
  9345. * @param {number} z - The z component of the vector.
  9346. * @return {Matrix4} A reference to this matrix.
  9347. */
  9348. setPosition( x, y, z ) {
  9349. const te = this.elements;
  9350. if ( x.isVector3 ) {
  9351. te[ 12 ] = x.x;
  9352. te[ 13 ] = x.y;
  9353. te[ 14 ] = x.z;
  9354. } else {
  9355. te[ 12 ] = x;
  9356. te[ 13 ] = y;
  9357. te[ 14 ] = z;
  9358. }
  9359. return this;
  9360. }
  9361. /**
  9362. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  9363. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9364. * a zero matrix instead.
  9365. *
  9366. * @return {Matrix4} A reference to this matrix.
  9367. */
  9368. invert() {
  9369. // based on https://github.com/toji/gl-matrix
  9370. const te = this.elements,
  9371. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9372. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9373. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9374. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9375. t1 = n11 * n22 - n21 * n12,
  9376. t2 = n11 * n32 - n31 * n12,
  9377. t3 = n11 * n42 - n41 * n12,
  9378. t4 = n21 * n32 - n31 * n22,
  9379. t5 = n21 * n42 - n41 * n22,
  9380. t6 = n31 * n42 - n41 * n32,
  9381. t7 = n13 * n24 - n23 * n14,
  9382. t8 = n13 * n34 - n33 * n14,
  9383. t9 = n13 * n44 - n43 * n14,
  9384. t10 = n23 * n34 - n33 * n24,
  9385. t11 = n23 * n44 - n43 * n24,
  9386. t12 = n33 * n44 - n43 * n34;
  9387. const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7;
  9388. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9389. const detInv = 1 / det;
  9390. te[ 0 ] = ( n22 * t12 - n32 * t11 + n42 * t10 ) * detInv;
  9391. te[ 1 ] = ( n31 * t11 - n21 * t12 - n41 * t10 ) * detInv;
  9392. te[ 2 ] = ( n24 * t6 - n34 * t5 + n44 * t4 ) * detInv;
  9393. te[ 3 ] = ( n33 * t5 - n23 * t6 - n43 * t4 ) * detInv;
  9394. te[ 4 ] = ( n32 * t9 - n12 * t12 - n42 * t8 ) * detInv;
  9395. te[ 5 ] = ( n11 * t12 - n31 * t9 + n41 * t8 ) * detInv;
  9396. te[ 6 ] = ( n34 * t3 - n14 * t6 - n44 * t2 ) * detInv;
  9397. te[ 7 ] = ( n13 * t6 - n33 * t3 + n43 * t2 ) * detInv;
  9398. te[ 8 ] = ( n12 * t11 - n22 * t9 + n42 * t7 ) * detInv;
  9399. te[ 9 ] = ( n21 * t9 - n11 * t11 - n41 * t7 ) * detInv;
  9400. te[ 10 ] = ( n14 * t5 - n24 * t3 + n44 * t1 ) * detInv;
  9401. te[ 11 ] = ( n23 * t3 - n13 * t5 - n43 * t1 ) * detInv;
  9402. te[ 12 ] = ( n22 * t8 - n12 * t10 - n32 * t7 ) * detInv;
  9403. te[ 13 ] = ( n11 * t10 - n21 * t8 + n31 * t7 ) * detInv;
  9404. te[ 14 ] = ( n24 * t2 - n14 * t4 - n34 * t1 ) * detInv;
  9405. te[ 15 ] = ( n13 * t4 - n23 * t2 + n33 * t1 ) * detInv;
  9406. return this;
  9407. }
  9408. /**
  9409. * Multiplies the columns of this matrix by the given vector.
  9410. *
  9411. * @param {Vector3} v - The scale vector.
  9412. * @return {Matrix4} A reference to this matrix.
  9413. */
  9414. scale( v ) {
  9415. const te = this.elements;
  9416. const x = v.x, y = v.y, z = v.z;
  9417. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9418. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9419. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9420. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9421. return this;
  9422. }
  9423. /**
  9424. * Gets the maximum scale value of the three axes.
  9425. *
  9426. * @return {number} The maximum scale.
  9427. */
  9428. getMaxScaleOnAxis() {
  9429. const te = this.elements;
  9430. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9431. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9432. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9433. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9434. }
  9435. /**
  9436. * Sets this matrix as a translation transform from the given vector.
  9437. *
  9438. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9439. * @param {number} y - The amount to translate in the Y axis.
  9440. * @param {number} z - The amount to translate in the z axis.
  9441. * @return {Matrix4} A reference to this matrix.
  9442. */
  9443. makeTranslation( x, y, z ) {
  9444. if ( x.isVector3 ) {
  9445. this.set(
  9446. 1, 0, 0, x.x,
  9447. 0, 1, 0, x.y,
  9448. 0, 0, 1, x.z,
  9449. 0, 0, 0, 1
  9450. );
  9451. } else {
  9452. this.set(
  9453. 1, 0, 0, x,
  9454. 0, 1, 0, y,
  9455. 0, 0, 1, z,
  9456. 0, 0, 0, 1
  9457. );
  9458. }
  9459. return this;
  9460. }
  9461. /**
  9462. * Sets this matrix as a rotational transformation around the X axis by
  9463. * the given angle.
  9464. *
  9465. * @param {number} theta - The rotation in radians.
  9466. * @return {Matrix4} A reference to this matrix.
  9467. */
  9468. makeRotationX( theta ) {
  9469. const c = Math.cos( theta ), s = Math.sin( theta );
  9470. this.set(
  9471. 1, 0, 0, 0,
  9472. 0, c, - s, 0,
  9473. 0, s, c, 0,
  9474. 0, 0, 0, 1
  9475. );
  9476. return this;
  9477. }
  9478. /**
  9479. * Sets this matrix as a rotational transformation around the Y axis by
  9480. * the given angle.
  9481. *
  9482. * @param {number} theta - The rotation in radians.
  9483. * @return {Matrix4} A reference to this matrix.
  9484. */
  9485. makeRotationY( theta ) {
  9486. const c = Math.cos( theta ), s = Math.sin( theta );
  9487. this.set(
  9488. c, 0, s, 0,
  9489. 0, 1, 0, 0,
  9490. - s, 0, c, 0,
  9491. 0, 0, 0, 1
  9492. );
  9493. return this;
  9494. }
  9495. /**
  9496. * Sets this matrix as a rotational transformation around the Z axis by
  9497. * the given angle.
  9498. *
  9499. * @param {number} theta - The rotation in radians.
  9500. * @return {Matrix4} A reference to this matrix.
  9501. */
  9502. makeRotationZ( theta ) {
  9503. const c = Math.cos( theta ), s = Math.sin( theta );
  9504. this.set(
  9505. c, - s, 0, 0,
  9506. s, c, 0, 0,
  9507. 0, 0, 1, 0,
  9508. 0, 0, 0, 1
  9509. );
  9510. return this;
  9511. }
  9512. /**
  9513. * Sets this matrix as a rotational transformation around the given axis by
  9514. * the given angle.
  9515. *
  9516. * This is a somewhat controversial but mathematically sound alternative to
  9517. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  9518. *
  9519. * @param {Vector3} axis - The normalized rotation axis.
  9520. * @param {number} angle - The rotation in radians.
  9521. * @return {Matrix4} A reference to this matrix.
  9522. */
  9523. makeRotationAxis( axis, angle ) {
  9524. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9525. const c = Math.cos( angle );
  9526. const s = Math.sin( angle );
  9527. const t = 1 - c;
  9528. const x = axis.x, y = axis.y, z = axis.z;
  9529. const tx = t * x, ty = t * y;
  9530. this.set(
  9531. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9532. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9533. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9534. 0, 0, 0, 1
  9535. );
  9536. return this;
  9537. }
  9538. /**
  9539. * Sets this matrix as a scale transformation.
  9540. *
  9541. * @param {number} x - The amount to scale in the X axis.
  9542. * @param {number} y - The amount to scale in the Y axis.
  9543. * @param {number} z - The amount to scale in the Z axis.
  9544. * @return {Matrix4} A reference to this matrix.
  9545. */
  9546. makeScale( x, y, z ) {
  9547. this.set(
  9548. x, 0, 0, 0,
  9549. 0, y, 0, 0,
  9550. 0, 0, z, 0,
  9551. 0, 0, 0, 1
  9552. );
  9553. return this;
  9554. }
  9555. /**
  9556. * Sets this matrix as a shear transformation.
  9557. *
  9558. * @param {number} xy - The amount to shear X by Y.
  9559. * @param {number} xz - The amount to shear X by Z.
  9560. * @param {number} yx - The amount to shear Y by X.
  9561. * @param {number} yz - The amount to shear Y by Z.
  9562. * @param {number} zx - The amount to shear Z by X.
  9563. * @param {number} zy - The amount to shear Z by Y.
  9564. * @return {Matrix4} A reference to this matrix.
  9565. */
  9566. makeShear( xy, xz, yx, yz, zx, zy ) {
  9567. this.set(
  9568. 1, yx, zx, 0,
  9569. xy, 1, zy, 0,
  9570. xz, yz, 1, 0,
  9571. 0, 0, 0, 1
  9572. );
  9573. return this;
  9574. }
  9575. /**
  9576. * Sets this matrix to the transformation composed of the given position,
  9577. * rotation (Quaternion) and scale.
  9578. *
  9579. * @param {Vector3} position - The position vector.
  9580. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9581. * @param {Vector3} scale - The scale vector.
  9582. * @return {Matrix4} A reference to this matrix.
  9583. */
  9584. compose( position, quaternion, scale ) {
  9585. const te = this.elements;
  9586. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9587. const x2 = x + x, y2 = y + y, z2 = z + z;
  9588. const xx = x * x2, xy = x * y2, xz = x * z2;
  9589. const yy = y * y2, yz = y * z2, zz = z * z2;
  9590. const wx = w * x2, wy = w * y2, wz = w * z2;
  9591. const sx = scale.x, sy = scale.y, sz = scale.z;
  9592. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9593. te[ 1 ] = ( xy + wz ) * sx;
  9594. te[ 2 ] = ( xz - wy ) * sx;
  9595. te[ 3 ] = 0;
  9596. te[ 4 ] = ( xy - wz ) * sy;
  9597. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9598. te[ 6 ] = ( yz + wx ) * sy;
  9599. te[ 7 ] = 0;
  9600. te[ 8 ] = ( xz + wy ) * sz;
  9601. te[ 9 ] = ( yz - wx ) * sz;
  9602. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9603. te[ 11 ] = 0;
  9604. te[ 12 ] = position.x;
  9605. te[ 13 ] = position.y;
  9606. te[ 14 ] = position.z;
  9607. te[ 15 ] = 1;
  9608. return this;
  9609. }
  9610. /**
  9611. * Decomposes this matrix into its position, rotation and scale components
  9612. * and provides the result in the given objects.
  9613. *
  9614. * Note: Not all matrices are decomposable in this way. For example, if an
  9615. * object has a non-uniformly scaled parent, then the object's world matrix
  9616. * may not be decomposable, and this method may not be appropriate.
  9617. *
  9618. * @param {Vector3} position - The position vector.
  9619. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9620. * @param {Vector3} scale - The scale vector.
  9621. * @return {Matrix4} A reference to this matrix.
  9622. */
  9623. decompose( position, quaternion, scale ) {
  9624. const te = this.elements;
  9625. position.x = te[ 12 ];
  9626. position.y = te[ 13 ];
  9627. position.z = te[ 14 ];
  9628. const det = this.determinant();
  9629. if ( det === 0 ) {
  9630. scale.set( 1, 1, 1 );
  9631. quaternion.identity();
  9632. return this;
  9633. }
  9634. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9635. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9636. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9637. // if determinant is negative, we need to invert one scale
  9638. if ( det < 0 ) sx = - sx;
  9639. // scale the rotation part
  9640. _m1$2.copy( this );
  9641. const invSX = 1 / sx;
  9642. const invSY = 1 / sy;
  9643. const invSZ = 1 / sz;
  9644. _m1$2.elements[ 0 ] *= invSX;
  9645. _m1$2.elements[ 1 ] *= invSX;
  9646. _m1$2.elements[ 2 ] *= invSX;
  9647. _m1$2.elements[ 4 ] *= invSY;
  9648. _m1$2.elements[ 5 ] *= invSY;
  9649. _m1$2.elements[ 6 ] *= invSY;
  9650. _m1$2.elements[ 8 ] *= invSZ;
  9651. _m1$2.elements[ 9 ] *= invSZ;
  9652. _m1$2.elements[ 10 ] *= invSZ;
  9653. quaternion.setFromRotationMatrix( _m1$2 );
  9654. scale.x = sx;
  9655. scale.y = sy;
  9656. scale.z = sz;
  9657. return this;
  9658. }
  9659. /**
  9660. * Creates a perspective projection matrix. This is used internally by
  9661. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9662. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9663. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9664. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9665. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9666. * @param {number} near - The distance from the camera to the near plane.
  9667. * @param {number} far - The distance from the camera to the far plane.
  9668. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9669. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9670. * @return {Matrix4} A reference to this matrix.
  9671. */
  9672. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9673. const te = this.elements;
  9674. const x = 2 * near / ( right - left );
  9675. const y = 2 * near / ( top - bottom );
  9676. const a = ( right + left ) / ( right - left );
  9677. const b = ( top + bottom ) / ( top - bottom );
  9678. let c, d;
  9679. if ( reversedDepth ) {
  9680. c = near / ( far - near );
  9681. d = ( far * near ) / ( far - near );
  9682. } else {
  9683. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9684. c = - ( far + near ) / ( far - near );
  9685. d = ( -2 * far * near ) / ( far - near );
  9686. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9687. c = - far / ( far - near );
  9688. d = ( - far * near ) / ( far - near );
  9689. } else {
  9690. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9691. }
  9692. }
  9693. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9694. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9695. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9696. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9697. return this;
  9698. }
  9699. /**
  9700. * Creates a orthographic projection matrix. This is used internally by
  9701. * {@link OrthographicCamera#updateProjectionMatrix}.
  9702. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9703. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9704. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9705. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9706. * @param {number} near - The distance from the camera to the near plane.
  9707. * @param {number} far - The distance from the camera to the far plane.
  9708. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9709. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9710. * @return {Matrix4} A reference to this matrix.
  9711. */
  9712. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9713. const te = this.elements;
  9714. const x = 2 / ( right - left );
  9715. const y = 2 / ( top - bottom );
  9716. const a = - ( right + left ) / ( right - left );
  9717. const b = - ( top + bottom ) / ( top - bottom );
  9718. let c, d;
  9719. if ( reversedDepth ) {
  9720. c = 1 / ( far - near );
  9721. d = far / ( far - near );
  9722. } else {
  9723. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9724. c = -2 / ( far - near );
  9725. d = - ( far + near ) / ( far - near );
  9726. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9727. c = -1 / ( far - near );
  9728. d = - near / ( far - near );
  9729. } else {
  9730. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9731. }
  9732. }
  9733. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9734. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9735. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9736. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9737. return this;
  9738. }
  9739. /**
  9740. * Returns `true` if this matrix is equal with the given one.
  9741. *
  9742. * @param {Matrix4} matrix - The matrix to test for equality.
  9743. * @return {boolean} Whether this matrix is equal with the given one.
  9744. */
  9745. equals( matrix ) {
  9746. const te = this.elements;
  9747. const me = matrix.elements;
  9748. for ( let i = 0; i < 16; i ++ ) {
  9749. if ( te[ i ] !== me[ i ] ) return false;
  9750. }
  9751. return true;
  9752. }
  9753. /**
  9754. * Sets the elements of the matrix from the given array.
  9755. *
  9756. * @param {Array<number>} array - The matrix elements in column-major order.
  9757. * @param {number} [offset=0] - Index of the first element in the array.
  9758. * @return {Matrix4} A reference to this matrix.
  9759. */
  9760. fromArray( array, offset = 0 ) {
  9761. for ( let i = 0; i < 16; i ++ ) {
  9762. this.elements[ i ] = array[ i + offset ];
  9763. }
  9764. return this;
  9765. }
  9766. /**
  9767. * Writes the elements of this matrix to the given array. If no array is provided,
  9768. * the method returns a new instance.
  9769. *
  9770. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9771. * @param {number} [offset=0] - Index of the first element in the array.
  9772. * @return {Array<number>} The matrix elements in column-major order.
  9773. */
  9774. toArray( array = [], offset = 0 ) {
  9775. const te = this.elements;
  9776. array[ offset ] = te[ 0 ];
  9777. array[ offset + 1 ] = te[ 1 ];
  9778. array[ offset + 2 ] = te[ 2 ];
  9779. array[ offset + 3 ] = te[ 3 ];
  9780. array[ offset + 4 ] = te[ 4 ];
  9781. array[ offset + 5 ] = te[ 5 ];
  9782. array[ offset + 6 ] = te[ 6 ];
  9783. array[ offset + 7 ] = te[ 7 ];
  9784. array[ offset + 8 ] = te[ 8 ];
  9785. array[ offset + 9 ] = te[ 9 ];
  9786. array[ offset + 10 ] = te[ 10 ];
  9787. array[ offset + 11 ] = te[ 11 ];
  9788. array[ offset + 12 ] = te[ 12 ];
  9789. array[ offset + 13 ] = te[ 13 ];
  9790. array[ offset + 14 ] = te[ 14 ];
  9791. array[ offset + 15 ] = te[ 15 ];
  9792. return array;
  9793. }
  9794. }
  9795. const _v1$5 = /*@__PURE__*/ new Vector3();
  9796. const _m1$2 = /*@__PURE__*/ new Matrix4();
  9797. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9798. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9799. const _x = /*@__PURE__*/ new Vector3();
  9800. const _y = /*@__PURE__*/ new Vector3();
  9801. const _z = /*@__PURE__*/ new Vector3();
  9802. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9803. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9804. /**
  9805. * A class representing Euler angles.
  9806. *
  9807. * Euler angles describe a rotational transformation by rotating an object on
  9808. * its various axes in specified amounts per axis, and a specified axis
  9809. * order.
  9810. *
  9811. * Iterating through an instance will yield its components (x, y, z,
  9812. * order) in the corresponding order.
  9813. *
  9814. * ```js
  9815. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9816. * const b = new THREE.Vector3( 1, 0, 1 );
  9817. * b.applyEuler(a);
  9818. * ```
  9819. */
  9820. class Euler {
  9821. /**
  9822. * Constructs a new euler instance.
  9823. *
  9824. * @param {number} [x=0] - The angle of the x axis in radians.
  9825. * @param {number} [y=0] - The angle of the y axis in radians.
  9826. * @param {number} [z=0] - The angle of the z axis in radians.
  9827. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9828. */
  9829. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9830. /**
  9831. * This flag can be used for type testing.
  9832. *
  9833. * @type {boolean}
  9834. * @readonly
  9835. * @default true
  9836. */
  9837. this.isEuler = true;
  9838. this._x = x;
  9839. this._y = y;
  9840. this._z = z;
  9841. this._order = order;
  9842. }
  9843. /**
  9844. * The angle of the x axis in radians.
  9845. *
  9846. * @type {number}
  9847. * @default 0
  9848. */
  9849. get x() {
  9850. return this._x;
  9851. }
  9852. set x( value ) {
  9853. this._x = value;
  9854. this._onChangeCallback();
  9855. }
  9856. /**
  9857. * The angle of the y axis in radians.
  9858. *
  9859. * @type {number}
  9860. * @default 0
  9861. */
  9862. get y() {
  9863. return this._y;
  9864. }
  9865. set y( value ) {
  9866. this._y = value;
  9867. this._onChangeCallback();
  9868. }
  9869. /**
  9870. * The angle of the z axis in radians.
  9871. *
  9872. * @type {number}
  9873. * @default 0
  9874. */
  9875. get z() {
  9876. return this._z;
  9877. }
  9878. set z( value ) {
  9879. this._z = value;
  9880. this._onChangeCallback();
  9881. }
  9882. /**
  9883. * A string representing the order that the rotations are applied.
  9884. *
  9885. * @type {string}
  9886. * @default 'XYZ'
  9887. */
  9888. get order() {
  9889. return this._order;
  9890. }
  9891. set order( value ) {
  9892. this._order = value;
  9893. this._onChangeCallback();
  9894. }
  9895. /**
  9896. * Sets the Euler components.
  9897. *
  9898. * @param {number} x - The angle of the x axis in radians.
  9899. * @param {number} y - The angle of the y axis in radians.
  9900. * @param {number} z - The angle of the z axis in radians.
  9901. * @param {string} [order] - A string representing the order that the rotations are applied.
  9902. * @return {Euler} A reference to this Euler instance.
  9903. */
  9904. set( x, y, z, order = this._order ) {
  9905. this._x = x;
  9906. this._y = y;
  9907. this._z = z;
  9908. this._order = order;
  9909. this._onChangeCallback();
  9910. return this;
  9911. }
  9912. /**
  9913. * Returns a new Euler instance with copied values from this instance.
  9914. *
  9915. * @return {Euler} A clone of this instance.
  9916. */
  9917. clone() {
  9918. return new this.constructor( this._x, this._y, this._z, this._order );
  9919. }
  9920. /**
  9921. * Copies the values of the given Euler instance to this instance.
  9922. *
  9923. * @param {Euler} euler - The Euler instance to copy.
  9924. * @return {Euler} A reference to this Euler instance.
  9925. */
  9926. copy( euler ) {
  9927. this._x = euler._x;
  9928. this._y = euler._y;
  9929. this._z = euler._z;
  9930. this._order = euler._order;
  9931. this._onChangeCallback();
  9932. return this;
  9933. }
  9934. /**
  9935. * Sets the angles of this Euler instance from a pure rotation matrix.
  9936. *
  9937. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9938. * @param {string} [order] - A string representing the order that the rotations are applied.
  9939. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9940. * @return {Euler} A reference to this Euler instance.
  9941. */
  9942. setFromRotationMatrix( m, order = this._order, update = true ) {
  9943. const te = m.elements;
  9944. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9945. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9946. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9947. switch ( order ) {
  9948. case 'XYZ':
  9949. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9950. if ( Math.abs( m13 ) < 0.9999999 ) {
  9951. this._x = Math.atan2( - m23, m33 );
  9952. this._z = Math.atan2( - m12, m11 );
  9953. } else {
  9954. this._x = Math.atan2( m32, m22 );
  9955. this._z = 0;
  9956. }
  9957. break;
  9958. case 'YXZ':
  9959. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9960. if ( Math.abs( m23 ) < 0.9999999 ) {
  9961. this._y = Math.atan2( m13, m33 );
  9962. this._z = Math.atan2( m21, m22 );
  9963. } else {
  9964. this._y = Math.atan2( - m31, m11 );
  9965. this._z = 0;
  9966. }
  9967. break;
  9968. case 'ZXY':
  9969. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9970. if ( Math.abs( m32 ) < 0.9999999 ) {
  9971. this._y = Math.atan2( - m31, m33 );
  9972. this._z = Math.atan2( - m12, m22 );
  9973. } else {
  9974. this._y = 0;
  9975. this._z = Math.atan2( m21, m11 );
  9976. }
  9977. break;
  9978. case 'ZYX':
  9979. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9980. if ( Math.abs( m31 ) < 0.9999999 ) {
  9981. this._x = Math.atan2( m32, m33 );
  9982. this._z = Math.atan2( m21, m11 );
  9983. } else {
  9984. this._x = 0;
  9985. this._z = Math.atan2( - m12, m22 );
  9986. }
  9987. break;
  9988. case 'YZX':
  9989. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9990. if ( Math.abs( m21 ) < 0.9999999 ) {
  9991. this._x = Math.atan2( - m23, m22 );
  9992. this._y = Math.atan2( - m31, m11 );
  9993. } else {
  9994. this._x = 0;
  9995. this._y = Math.atan2( m13, m33 );
  9996. }
  9997. break;
  9998. case 'XZY':
  9999. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  10000. if ( Math.abs( m12 ) < 0.9999999 ) {
  10001. this._x = Math.atan2( m32, m22 );
  10002. this._y = Math.atan2( m13, m11 );
  10003. } else {
  10004. this._x = Math.atan2( - m23, m33 );
  10005. this._y = 0;
  10006. }
  10007. break;
  10008. default:
  10009. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  10010. }
  10011. this._order = order;
  10012. if ( update === true ) this._onChangeCallback();
  10013. return this;
  10014. }
  10015. /**
  10016. * Sets the angles of this Euler instance from a normalized quaternion.
  10017. *
  10018. * @param {Quaternion} q - A normalized Quaternion.
  10019. * @param {string} [order] - A string representing the order that the rotations are applied.
  10020. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  10021. * @return {Euler} A reference to this Euler instance.
  10022. */
  10023. setFromQuaternion( q, order, update ) {
  10024. _matrix$2.makeRotationFromQuaternion( q );
  10025. return this.setFromRotationMatrix( _matrix$2, order, update );
  10026. }
  10027. /**
  10028. * Sets the angles of this Euler instance from the given vector.
  10029. *
  10030. * @param {Vector3} v - The vector.
  10031. * @param {string} [order] - A string representing the order that the rotations are applied.
  10032. * @return {Euler} A reference to this Euler instance.
  10033. */
  10034. setFromVector3( v, order = this._order ) {
  10035. return this.set( v.x, v.y, v.z, order );
  10036. }
  10037. /**
  10038. * Resets the euler angle with a new order by creating a quaternion from this
  10039. * euler angle and then setting this euler angle with the quaternion and the
  10040. * new order.
  10041. *
  10042. * Warning: This discards revolution information.
  10043. *
  10044. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  10045. * @return {Euler} A reference to this Euler instance.
  10046. */
  10047. reorder( newOrder ) {
  10048. _quaternion$3.setFromEuler( this );
  10049. return this.setFromQuaternion( _quaternion$3, newOrder );
  10050. }
  10051. /**
  10052. * Returns `true` if this Euler instance is equal with the given one.
  10053. *
  10054. * @param {Euler} euler - The Euler instance to test for equality.
  10055. * @return {boolean} Whether this Euler instance is equal with the given one.
  10056. */
  10057. equals( euler ) {
  10058. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  10059. }
  10060. /**
  10061. * Sets this Euler instance's components to values from the given array. The first three
  10062. * entries of the array are assign to the x,y and z components. An optional fourth entry
  10063. * defines the Euler order.
  10064. *
  10065. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  10066. * @return {Euler} A reference to this Euler instance.
  10067. */
  10068. fromArray( array ) {
  10069. this._x = array[ 0 ];
  10070. this._y = array[ 1 ];
  10071. this._z = array[ 2 ];
  10072. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  10073. this._onChangeCallback();
  10074. return this;
  10075. }
  10076. /**
  10077. * Writes the components of this Euler instance to the given array. If no array is provided,
  10078. * the method returns a new instance.
  10079. *
  10080. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  10081. * @param {number} [offset=0] - Index of the first element in the array.
  10082. * @return {Array<number,number,number,string>} The Euler components.
  10083. */
  10084. toArray( array = [], offset = 0 ) {
  10085. array[ offset ] = this._x;
  10086. array[ offset + 1 ] = this._y;
  10087. array[ offset + 2 ] = this._z;
  10088. array[ offset + 3 ] = this._order;
  10089. return array;
  10090. }
  10091. _onChange( callback ) {
  10092. this._onChangeCallback = callback;
  10093. return this;
  10094. }
  10095. _onChangeCallback() {}
  10096. *[ Symbol.iterator ]() {
  10097. yield this._x;
  10098. yield this._y;
  10099. yield this._z;
  10100. yield this._order;
  10101. }
  10102. }
  10103. /**
  10104. * The default Euler angle order.
  10105. *
  10106. * @static
  10107. * @type {string}
  10108. * @default 'XYZ'
  10109. */
  10110. Euler.DEFAULT_ORDER = 'XYZ';
  10111. /**
  10112. * A layers object assigns an 3D object to 1 or more of 32
  10113. * layers numbered `0` to `31` - internally the layers are stored as a
  10114. * bit mask], and by default all 3D objects are a member of layer `0`.
  10115. *
  10116. * This can be used to control visibility - an object must share a layer with
  10117. * a camera to be visible when that camera's view is
  10118. * rendered.
  10119. *
  10120. * All classes that inherit from {@link Object3D} have an `layers` property which
  10121. * is an instance of this class.
  10122. */
  10123. class Layers {
  10124. /**
  10125. * Constructs a new layers instance, with membership
  10126. * initially set to layer `0`.
  10127. */
  10128. constructor() {
  10129. /**
  10130. * A bit mask storing which of the 32 layers this layers object is currently
  10131. * a member of.
  10132. *
  10133. * @type {number}
  10134. */
  10135. this.mask = 1 | 0;
  10136. }
  10137. /**
  10138. * Sets membership to the given layer, and remove membership all other layers.
  10139. *
  10140. * @param {number} layer - The layer to set.
  10141. */
  10142. set( layer ) {
  10143. this.mask = ( 1 << layer | 0 ) >>> 0;
  10144. }
  10145. /**
  10146. * Adds membership of the given layer.
  10147. *
  10148. * @param {number} layer - The layer to enable.
  10149. */
  10150. enable( layer ) {
  10151. this.mask |= 1 << layer | 0;
  10152. }
  10153. /**
  10154. * Adds membership to all layers.
  10155. */
  10156. enableAll() {
  10157. this.mask = 0xffffffff | 0;
  10158. }
  10159. /**
  10160. * Toggles the membership of the given layer.
  10161. *
  10162. * @param {number} layer - The layer to toggle.
  10163. */
  10164. toggle( layer ) {
  10165. this.mask ^= 1 << layer | 0;
  10166. }
  10167. /**
  10168. * Removes membership of the given layer.
  10169. *
  10170. * @param {number} layer - The layer to enable.
  10171. */
  10172. disable( layer ) {
  10173. this.mask &= ~ ( 1 << layer | 0 );
  10174. }
  10175. /**
  10176. * Removes the membership from all layers.
  10177. */
  10178. disableAll() {
  10179. this.mask = 0;
  10180. }
  10181. /**
  10182. * Returns `true` if this and the given layers object have at least one
  10183. * layer in common.
  10184. *
  10185. * @param {Layers} layers - The layers to test.
  10186. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  10187. */
  10188. test( layers ) {
  10189. return ( this.mask & layers.mask ) !== 0;
  10190. }
  10191. /**
  10192. * Returns `true` if the given layer is enabled.
  10193. *
  10194. * @param {number} layer - The layer to test.
  10195. * @return {boolean } Whether the given layer is enabled or not.
  10196. */
  10197. isEnabled( layer ) {
  10198. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  10199. }
  10200. }
  10201. let _object3DId = 0;
  10202. const _v1$4 = /*@__PURE__*/ new Vector3();
  10203. const _q1 = /*@__PURE__*/ new Quaternion();
  10204. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10205. const _target = /*@__PURE__*/ new Vector3();
  10206. const _position$3 = /*@__PURE__*/ new Vector3();
  10207. const _scale$2 = /*@__PURE__*/ new Vector3();
  10208. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  10209. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  10210. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10211. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  10212. /**
  10213. * Fires when the object has been added to its parent object.
  10214. *
  10215. * @event Object3D#added
  10216. * @type {Object}
  10217. */
  10218. const _addedEvent = { type: 'added' };
  10219. /**
  10220. * Fires when the object has been removed from its parent object.
  10221. *
  10222. * @event Object3D#removed
  10223. * @type {Object}
  10224. */
  10225. const _removedEvent = { type: 'removed' };
  10226. /**
  10227. * Fires when a new child object has been added.
  10228. *
  10229. * @event Object3D#childadded
  10230. * @type {Object}
  10231. */
  10232. const _childaddedEvent = { type: 'childadded', child: null };
  10233. /**
  10234. * Fires when a child object has been removed.
  10235. *
  10236. * @event Object3D#childremoved
  10237. * @type {Object}
  10238. */
  10239. const _childremovedEvent = { type: 'childremoved', child: null };
  10240. /**
  10241. * This is the base class for most objects in three.js and provides a set of
  10242. * properties and methods for manipulating objects in 3D space.
  10243. *
  10244. * @augments EventDispatcher
  10245. */
  10246. class Object3D extends EventDispatcher {
  10247. /**
  10248. * Constructs a new 3D object.
  10249. */
  10250. constructor() {
  10251. super();
  10252. /**
  10253. * This flag can be used for type testing.
  10254. *
  10255. * @type {boolean}
  10256. * @readonly
  10257. * @default true
  10258. */
  10259. this.isObject3D = true;
  10260. /**
  10261. * The ID of the 3D object.
  10262. *
  10263. * @name Object3D#id
  10264. * @type {number}
  10265. * @readonly
  10266. */
  10267. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10268. /**
  10269. * The UUID of the 3D object.
  10270. *
  10271. * @type {string}
  10272. * @readonly
  10273. */
  10274. this.uuid = generateUUID();
  10275. /**
  10276. * The name of the 3D object.
  10277. *
  10278. * @type {string}
  10279. */
  10280. this.name = '';
  10281. /**
  10282. * The type property is used for detecting the object type
  10283. * in context of serialization/deserialization.
  10284. *
  10285. * @type {string}
  10286. * @readonly
  10287. */
  10288. this.type = 'Object3D';
  10289. /**
  10290. * A reference to the parent object.
  10291. *
  10292. * @type {?Object3D}
  10293. * @default null
  10294. */
  10295. this.parent = null;
  10296. /**
  10297. * An array holding the child 3D objects of this instance.
  10298. *
  10299. * @type {Array<Object3D>}
  10300. */
  10301. this.children = [];
  10302. /**
  10303. * Defines the `up` direction of the 3D object which influences
  10304. * the orientation via methods like {@link Object3D#lookAt}.
  10305. *
  10306. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10307. *
  10308. * @type {Vector3}
  10309. */
  10310. this.up = Object3D.DEFAULT_UP.clone();
  10311. const position = new Vector3();
  10312. const rotation = new Euler();
  10313. const quaternion = new Quaternion();
  10314. const scale = new Vector3( 1, 1, 1 );
  10315. function onRotationChange() {
  10316. quaternion.setFromEuler( rotation, false );
  10317. }
  10318. function onQuaternionChange() {
  10319. rotation.setFromQuaternion( quaternion, undefined, false );
  10320. }
  10321. rotation._onChange( onRotationChange );
  10322. quaternion._onChange( onQuaternionChange );
  10323. Object.defineProperties( this, {
  10324. /**
  10325. * Represents the object's local position.
  10326. *
  10327. * @name Object3D#position
  10328. * @type {Vector3}
  10329. * @default (0,0,0)
  10330. */
  10331. position: {
  10332. configurable: true,
  10333. enumerable: true,
  10334. value: position
  10335. },
  10336. /**
  10337. * Represents the object's local rotation as Euler angles, in radians.
  10338. *
  10339. * @name Object3D#rotation
  10340. * @type {Euler}
  10341. * @default (0,0,0)
  10342. */
  10343. rotation: {
  10344. configurable: true,
  10345. enumerable: true,
  10346. value: rotation
  10347. },
  10348. /**
  10349. * Represents the object's local rotation as Quaternions.
  10350. *
  10351. * @name Object3D#quaternion
  10352. * @type {Quaternion}
  10353. */
  10354. quaternion: {
  10355. configurable: true,
  10356. enumerable: true,
  10357. value: quaternion
  10358. },
  10359. /**
  10360. * Represents the object's local scale.
  10361. *
  10362. * @name Object3D#scale
  10363. * @type {Vector3}
  10364. * @default (1,1,1)
  10365. */
  10366. scale: {
  10367. configurable: true,
  10368. enumerable: true,
  10369. value: scale
  10370. },
  10371. /**
  10372. * Represents the object's model-view matrix.
  10373. *
  10374. * @name Object3D#modelViewMatrix
  10375. * @type {Matrix4}
  10376. */
  10377. modelViewMatrix: {
  10378. value: new Matrix4()
  10379. },
  10380. /**
  10381. * Represents the object's normal matrix.
  10382. *
  10383. * @name Object3D#normalMatrix
  10384. * @type {Matrix3}
  10385. */
  10386. normalMatrix: {
  10387. value: new Matrix3()
  10388. }
  10389. } );
  10390. /**
  10391. * Represents the object's transformation matrix in local space.
  10392. *
  10393. * @type {Matrix4}
  10394. */
  10395. this.matrix = new Matrix4();
  10396. /**
  10397. * Represents the object's transformation matrix in world space.
  10398. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10399. *
  10400. * @type {Matrix4}
  10401. */
  10402. this.matrixWorld = new Matrix4();
  10403. /**
  10404. * When set to `true`, the engine automatically computes the local matrix from position,
  10405. * rotation and scale every frame.
  10406. *
  10407. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10408. *
  10409. * @type {boolean}
  10410. * @default true
  10411. */
  10412. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10413. /**
  10414. * When set to `true`, the engine automatically computes the world matrix from the current local
  10415. * matrix and the object's transformation hierarchy.
  10416. *
  10417. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10418. *
  10419. * @type {boolean}
  10420. * @default true
  10421. */
  10422. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10423. /**
  10424. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10425. * to `false`.
  10426. *
  10427. * @type {boolean}
  10428. * @default false
  10429. */
  10430. this.matrixWorldNeedsUpdate = false;
  10431. /**
  10432. * The layer membership of the 3D object. The 3D object is only visible if it has
  10433. * at least one layer in common with the camera in use. This property can also be
  10434. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10435. *
  10436. * @type {Layers}
  10437. */
  10438. this.layers = new Layers();
  10439. /**
  10440. * When set to `true`, the 3D object gets rendered.
  10441. *
  10442. * @type {boolean}
  10443. * @default true
  10444. */
  10445. this.visible = true;
  10446. /**
  10447. * When set to `true`, the 3D object gets rendered into shadow maps.
  10448. *
  10449. * @type {boolean}
  10450. * @default false
  10451. */
  10452. this.castShadow = false;
  10453. /**
  10454. * When set to `true`, the 3D object is affected by shadows in the scene.
  10455. *
  10456. * @type {boolean}
  10457. * @default false
  10458. */
  10459. this.receiveShadow = false;
  10460. /**
  10461. * When set to `true`, the 3D object is honored by view frustum culling.
  10462. *
  10463. * @type {boolean}
  10464. * @default true
  10465. */
  10466. this.frustumCulled = true;
  10467. /**
  10468. * This value allows the default rendering order of scene graph objects to be
  10469. * overridden although opaque and transparent objects remain sorted independently.
  10470. * When this property is set for an instance of {@link Group},all descendants
  10471. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10472. * render order.
  10473. *
  10474. * @type {number}
  10475. * @default 0
  10476. */
  10477. this.renderOrder = 0;
  10478. /**
  10479. * An array holding the animation clips of the 3D object.
  10480. *
  10481. * @type {Array<AnimationClip>}
  10482. */
  10483. this.animations = [];
  10484. /**
  10485. * Custom depth material to be used when rendering to the depth map. Can only be used
  10486. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10487. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10488. * material for proper shadows.
  10489. *
  10490. * Only relevant in context of {@link WebGLRenderer}.
  10491. *
  10492. * @type {(Material|undefined)}
  10493. * @default undefined
  10494. */
  10495. this.customDepthMaterial = undefined;
  10496. /**
  10497. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10498. *
  10499. * Only relevant in context of {@link WebGLRenderer}.
  10500. *
  10501. * @type {(Material|undefined)}
  10502. * @default undefined
  10503. */
  10504. this.customDistanceMaterial = undefined;
  10505. /**
  10506. * Whether the 3D object is supposed to be static or not. If set to `true`, it means
  10507. * the 3D object is not going to be changed after the initial renderer. This includes
  10508. * geometry and material settings. A static 3D object can be processed by the renderer
  10509. * slightly faster since certain state checks can be bypassed.
  10510. *
  10511. * Only relevant in context of {@link WebGPURenderer}.
  10512. *
  10513. * @type {boolean}
  10514. * @default false
  10515. */
  10516. this.static = false;
  10517. /**
  10518. * An object that can be used to store custom data about the 3D object. It
  10519. * should not hold references to functions as these will not be cloned.
  10520. *
  10521. * @type {Object}
  10522. */
  10523. this.userData = {};
  10524. /**
  10525. * The pivot point for rotation and scale transformations.
  10526. * When set, rotation and scale are applied around this point
  10527. * instead of the object's origin.
  10528. *
  10529. * @type {?Vector3}
  10530. * @default null
  10531. */
  10532. this.pivot = null;
  10533. }
  10534. /**
  10535. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10536. *
  10537. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10538. * @param {Object3D} object - The 3D object.
  10539. * @param {Camera} camera - The camera that is used to render the scene.
  10540. * @param {Camera} shadowCamera - The shadow camera.
  10541. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10542. * @param {Material} depthMaterial - The depth material.
  10543. * @param {Object} group - The geometry group data.
  10544. */
  10545. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10546. /**
  10547. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10548. *
  10549. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10550. * @param {Object3D} object - The 3D object.
  10551. * @param {Camera} camera - The camera that is used to render the scene.
  10552. * @param {Camera} shadowCamera - The shadow camera.
  10553. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10554. * @param {Material} depthMaterial - The depth material.
  10555. * @param {Object} group - The geometry group data.
  10556. */
  10557. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10558. /**
  10559. * A callback that is executed immediately before a 3D object is rendered.
  10560. *
  10561. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10562. * @param {Object3D} object - The 3D object.
  10563. * @param {Camera} camera - The camera that is used to render the scene.
  10564. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10565. * @param {Material} material - The 3D object's material.
  10566. * @param {Object} group - The geometry group data.
  10567. */
  10568. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10569. /**
  10570. * A callback that is executed immediately after a 3D object is rendered.
  10571. *
  10572. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10573. * @param {Object3D} object - The 3D object.
  10574. * @param {Camera} camera - The camera that is used to render the scene.
  10575. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10576. * @param {Material} material - The 3D object's material.
  10577. * @param {Object} group - The geometry group data.
  10578. */
  10579. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10580. /**
  10581. * Applies the given transformation matrix to the object and updates the object's position,
  10582. * rotation and scale.
  10583. *
  10584. * @param {Matrix4} matrix - The transformation matrix.
  10585. */
  10586. applyMatrix4( matrix ) {
  10587. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10588. this.matrix.premultiply( matrix );
  10589. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10590. }
  10591. /**
  10592. * Applies a rotation represented by given the quaternion to the 3D object.
  10593. *
  10594. * @param {Quaternion} q - The quaternion.
  10595. * @return {Object3D} A reference to this instance.
  10596. */
  10597. applyQuaternion( q ) {
  10598. this.quaternion.premultiply( q );
  10599. return this;
  10600. }
  10601. /**
  10602. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10603. *
  10604. * @param {Vector3} axis - The (normalized) axis vector.
  10605. * @param {number} angle - The angle in radians.
  10606. */
  10607. setRotationFromAxisAngle( axis, angle ) {
  10608. // assumes axis is normalized
  10609. this.quaternion.setFromAxisAngle( axis, angle );
  10610. }
  10611. /**
  10612. * Sets the given rotation represented as Euler angles to the 3D object.
  10613. *
  10614. * @param {Euler} euler - The Euler angles.
  10615. */
  10616. setRotationFromEuler( euler ) {
  10617. this.quaternion.setFromEuler( euler, true );
  10618. }
  10619. /**
  10620. * Sets the given rotation represented as rotation matrix to the 3D object.
  10621. *
  10622. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10623. * a pure rotation matrix (i.e, unscaled).
  10624. */
  10625. setRotationFromMatrix( m ) {
  10626. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10627. this.quaternion.setFromRotationMatrix( m );
  10628. }
  10629. /**
  10630. * Sets the given rotation represented as a Quaternion to the 3D object.
  10631. *
  10632. * @param {Quaternion} q - The Quaternion
  10633. */
  10634. setRotationFromQuaternion( q ) {
  10635. // assumes q is normalized
  10636. this.quaternion.copy( q );
  10637. }
  10638. /**
  10639. * Rotates the 3D object along an axis in local space.
  10640. *
  10641. * @param {Vector3} axis - The (normalized) axis vector.
  10642. * @param {number} angle - The angle in radians.
  10643. * @return {Object3D} A reference to this instance.
  10644. */
  10645. rotateOnAxis( axis, angle ) {
  10646. // rotate object on axis in object space
  10647. // axis is assumed to be normalized
  10648. _q1.setFromAxisAngle( axis, angle );
  10649. this.quaternion.multiply( _q1 );
  10650. return this;
  10651. }
  10652. /**
  10653. * Rotates the 3D object along an axis in world space.
  10654. *
  10655. * @param {Vector3} axis - The (normalized) axis vector.
  10656. * @param {number} angle - The angle in radians.
  10657. * @return {Object3D} A reference to this instance.
  10658. */
  10659. rotateOnWorldAxis( axis, angle ) {
  10660. // rotate object on axis in world space
  10661. // axis is assumed to be normalized
  10662. // method assumes no rotated parent
  10663. _q1.setFromAxisAngle( axis, angle );
  10664. this.quaternion.premultiply( _q1 );
  10665. return this;
  10666. }
  10667. /**
  10668. * Rotates the 3D object around its X axis in local space.
  10669. *
  10670. * @param {number} angle - The angle in radians.
  10671. * @return {Object3D} A reference to this instance.
  10672. */
  10673. rotateX( angle ) {
  10674. return this.rotateOnAxis( _xAxis, angle );
  10675. }
  10676. /**
  10677. * Rotates the 3D object around its Y axis in local space.
  10678. *
  10679. * @param {number} angle - The angle in radians.
  10680. * @return {Object3D} A reference to this instance.
  10681. */
  10682. rotateY( angle ) {
  10683. return this.rotateOnAxis( _yAxis, angle );
  10684. }
  10685. /**
  10686. * Rotates the 3D object around its Z axis in local space.
  10687. *
  10688. * @param {number} angle - The angle in radians.
  10689. * @return {Object3D} A reference to this instance.
  10690. */
  10691. rotateZ( angle ) {
  10692. return this.rotateOnAxis( _zAxis, angle );
  10693. }
  10694. /**
  10695. * Translate the 3D object by a distance along the given axis in local space.
  10696. *
  10697. * @param {Vector3} axis - The (normalized) axis vector.
  10698. * @param {number} distance - The distance in world units.
  10699. * @return {Object3D} A reference to this instance.
  10700. */
  10701. translateOnAxis( axis, distance ) {
  10702. // translate object by distance along axis in object space
  10703. // axis is assumed to be normalized
  10704. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10705. this.position.add( _v1$4.multiplyScalar( distance ) );
  10706. return this;
  10707. }
  10708. /**
  10709. * Translate the 3D object by a distance along its X-axis in local space.
  10710. *
  10711. * @param {number} distance - The distance in world units.
  10712. * @return {Object3D} A reference to this instance.
  10713. */
  10714. translateX( distance ) {
  10715. return this.translateOnAxis( _xAxis, distance );
  10716. }
  10717. /**
  10718. * Translate the 3D object by a distance along its Y-axis in local space.
  10719. *
  10720. * @param {number} distance - The distance in world units.
  10721. * @return {Object3D} A reference to this instance.
  10722. */
  10723. translateY( distance ) {
  10724. return this.translateOnAxis( _yAxis, distance );
  10725. }
  10726. /**
  10727. * Translate the 3D object by a distance along its Z-axis in local space.
  10728. *
  10729. * @param {number} distance - The distance in world units.
  10730. * @return {Object3D} A reference to this instance.
  10731. */
  10732. translateZ( distance ) {
  10733. return this.translateOnAxis( _zAxis, distance );
  10734. }
  10735. /**
  10736. * Converts the given vector from this 3D object's local space to world space.
  10737. *
  10738. * @param {Vector3} vector - The vector to convert.
  10739. * @return {Vector3} The converted vector.
  10740. */
  10741. localToWorld( vector ) {
  10742. this.updateWorldMatrix( true, false );
  10743. return vector.applyMatrix4( this.matrixWorld );
  10744. }
  10745. /**
  10746. * Converts the given vector from this 3D object's world space to local space.
  10747. *
  10748. * @param {Vector3} vector - The vector to convert.
  10749. * @return {Vector3} The converted vector.
  10750. */
  10751. worldToLocal( vector ) {
  10752. this.updateWorldMatrix( true, false );
  10753. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  10754. }
  10755. /**
  10756. * Rotates the object to face a point in world space.
  10757. *
  10758. * This method does not support objects having non-uniformly-scaled parent(s).
  10759. *
  10760. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10761. * @param {number} [y] - The y coordinate in world space.
  10762. * @param {number} [z] - The z coordinate in world space.
  10763. */
  10764. lookAt( x, y, z ) {
  10765. // This method does not support objects having non-uniformly-scaled parent(s)
  10766. if ( x.isVector3 ) {
  10767. _target.copy( x );
  10768. } else {
  10769. _target.set( x, y, z );
  10770. }
  10771. const parent = this.parent;
  10772. this.updateWorldMatrix( true, false );
  10773. _position$3.setFromMatrixPosition( this.matrixWorld );
  10774. if ( this.isCamera || this.isLight ) {
  10775. _m1$1.lookAt( _position$3, _target, this.up );
  10776. } else {
  10777. _m1$1.lookAt( _target, _position$3, this.up );
  10778. }
  10779. this.quaternion.setFromRotationMatrix( _m1$1 );
  10780. if ( parent ) {
  10781. _m1$1.extractRotation( parent.matrixWorld );
  10782. _q1.setFromRotationMatrix( _m1$1 );
  10783. this.quaternion.premultiply( _q1.invert() );
  10784. }
  10785. }
  10786. /**
  10787. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10788. * objects may be added. Any current parent on an object passed in here will be
  10789. * removed, since an object can have at most one parent.
  10790. *
  10791. * @fires Object3D#added
  10792. * @fires Object3D#childadded
  10793. * @param {Object3D} object - The 3D object to add.
  10794. * @return {Object3D} A reference to this instance.
  10795. */
  10796. add( object ) {
  10797. if ( arguments.length > 1 ) {
  10798. for ( let i = 0; i < arguments.length; i ++ ) {
  10799. this.add( arguments[ i ] );
  10800. }
  10801. return this;
  10802. }
  10803. if ( object === this ) {
  10804. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  10805. return this;
  10806. }
  10807. if ( object && object.isObject3D ) {
  10808. object.removeFromParent();
  10809. object.parent = this;
  10810. this.children.push( object );
  10811. object.dispatchEvent( _addedEvent );
  10812. _childaddedEvent.child = object;
  10813. this.dispatchEvent( _childaddedEvent );
  10814. _childaddedEvent.child = null;
  10815. } else {
  10816. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  10817. }
  10818. return this;
  10819. }
  10820. /**
  10821. * Removes the given 3D object as child from this 3D object.
  10822. * An arbitrary number of objects may be removed.
  10823. *
  10824. * @fires Object3D#removed
  10825. * @fires Object3D#childremoved
  10826. * @param {Object3D} object - The 3D object to remove.
  10827. * @return {Object3D} A reference to this instance.
  10828. */
  10829. remove( object ) {
  10830. if ( arguments.length > 1 ) {
  10831. for ( let i = 0; i < arguments.length; i ++ ) {
  10832. this.remove( arguments[ i ] );
  10833. }
  10834. return this;
  10835. }
  10836. const index = this.children.indexOf( object );
  10837. if ( index !== -1 ) {
  10838. object.parent = null;
  10839. this.children.splice( index, 1 );
  10840. object.dispatchEvent( _removedEvent );
  10841. _childremovedEvent.child = object;
  10842. this.dispatchEvent( _childremovedEvent );
  10843. _childremovedEvent.child = null;
  10844. }
  10845. return this;
  10846. }
  10847. /**
  10848. * Removes this 3D object from its current parent.
  10849. *
  10850. * @fires Object3D#removed
  10851. * @fires Object3D#childremoved
  10852. * @return {Object3D} A reference to this instance.
  10853. */
  10854. removeFromParent() {
  10855. const parent = this.parent;
  10856. if ( parent !== null ) {
  10857. parent.remove( this );
  10858. }
  10859. return this;
  10860. }
  10861. /**
  10862. * Removes all child objects.
  10863. *
  10864. * @fires Object3D#removed
  10865. * @fires Object3D#childremoved
  10866. * @return {Object3D} A reference to this instance.
  10867. */
  10868. clear() {
  10869. return this.remove( ... this.children );
  10870. }
  10871. /**
  10872. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10873. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10874. *
  10875. * @fires Object3D#added
  10876. * @fires Object3D#childadded
  10877. * @param {Object3D} object - The 3D object to attach.
  10878. * @return {Object3D} A reference to this instance.
  10879. */
  10880. attach( object ) {
  10881. // adds object as a child of this, while maintaining the object's world transform
  10882. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10883. this.updateWorldMatrix( true, false );
  10884. _m1$1.copy( this.matrixWorld ).invert();
  10885. if ( object.parent !== null ) {
  10886. object.parent.updateWorldMatrix( true, false );
  10887. _m1$1.multiply( object.parent.matrixWorld );
  10888. }
  10889. object.applyMatrix4( _m1$1 );
  10890. object.removeFromParent();
  10891. object.parent = this;
  10892. this.children.push( object );
  10893. object.updateWorldMatrix( false, true );
  10894. object.dispatchEvent( _addedEvent );
  10895. _childaddedEvent.child = object;
  10896. this.dispatchEvent( _childaddedEvent );
  10897. _childaddedEvent.child = null;
  10898. return this;
  10899. }
  10900. /**
  10901. * Searches through the 3D object and its children, starting with the 3D object
  10902. * itself, and returns the first with a matching ID.
  10903. *
  10904. * @param {number} id - The id.
  10905. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10906. */
  10907. getObjectById( id ) {
  10908. return this.getObjectByProperty( 'id', id );
  10909. }
  10910. /**
  10911. * Searches through the 3D object and its children, starting with the 3D object
  10912. * itself, and returns the first with a matching name.
  10913. *
  10914. * @param {string} name - The name.
  10915. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10916. */
  10917. getObjectByName( name ) {
  10918. return this.getObjectByProperty( 'name', name );
  10919. }
  10920. /**
  10921. * Searches through the 3D object and its children, starting with the 3D object
  10922. * itself, and returns the first with a matching property value.
  10923. *
  10924. * @param {string} name - The name of the property.
  10925. * @param {any} value - The value.
  10926. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10927. */
  10928. getObjectByProperty( name, value ) {
  10929. if ( this[ name ] === value ) return this;
  10930. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10931. const child = this.children[ i ];
  10932. const object = child.getObjectByProperty( name, value );
  10933. if ( object !== undefined ) {
  10934. return object;
  10935. }
  10936. }
  10937. return undefined;
  10938. }
  10939. /**
  10940. * Searches through the 3D object and its children, starting with the 3D object
  10941. * itself, and returns all 3D objects with a matching property value.
  10942. *
  10943. * @param {string} name - The name of the property.
  10944. * @param {any} value - The value.
  10945. * @param {Array<Object3D>} result - The method stores the result in this array.
  10946. * @return {Array<Object3D>} The found 3D objects.
  10947. */
  10948. getObjectsByProperty( name, value, result = [] ) {
  10949. if ( this[ name ] === value ) result.push( this );
  10950. const children = this.children;
  10951. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10952. children[ i ].getObjectsByProperty( name, value, result );
  10953. }
  10954. return result;
  10955. }
  10956. /**
  10957. * Returns a vector representing the position of the 3D object in world space.
  10958. *
  10959. * @param {Vector3} target - The target vector the result is stored to.
  10960. * @return {Vector3} The 3D object's position in world space.
  10961. */
  10962. getWorldPosition( target ) {
  10963. this.updateWorldMatrix( true, false );
  10964. return target.setFromMatrixPosition( this.matrixWorld );
  10965. }
  10966. /**
  10967. * Returns a Quaternion representing the position of the 3D object in world space.
  10968. *
  10969. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10970. * @return {Quaternion} The 3D object's rotation in world space.
  10971. */
  10972. getWorldQuaternion( target ) {
  10973. this.updateWorldMatrix( true, false );
  10974. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10975. return target;
  10976. }
  10977. /**
  10978. * Returns a vector representing the scale of the 3D object in world space.
  10979. *
  10980. * @param {Vector3} target - The target vector the result is stored to.
  10981. * @return {Vector3} The 3D object's scale in world space.
  10982. */
  10983. getWorldScale( target ) {
  10984. this.updateWorldMatrix( true, false );
  10985. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10986. return target;
  10987. }
  10988. /**
  10989. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10990. *
  10991. * @param {Vector3} target - The target vector the result is stored to.
  10992. * @return {Vector3} The 3D object's direction in world space.
  10993. */
  10994. getWorldDirection( target ) {
  10995. this.updateWorldMatrix( true, false );
  10996. const e = this.matrixWorld.elements;
  10997. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10998. }
  10999. /**
  11000. * Abstract method to get intersections between a casted ray and this
  11001. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  11002. * implement this method in order to use raycasting.
  11003. *
  11004. * @abstract
  11005. * @param {Raycaster} raycaster - The raycaster.
  11006. * @param {Array<Object>} intersects - An array holding the result of the method.
  11007. */
  11008. raycast( /* raycaster, intersects */ ) {}
  11009. /**
  11010. * Executes the callback on this 3D object and all descendants.
  11011. *
  11012. * Note: Modifying the scene graph inside the callback is discouraged.
  11013. *
  11014. * @param {Function} callback - A callback function that allows to process the current 3D object.
  11015. */
  11016. traverse( callback ) {
  11017. callback( this );
  11018. const children = this.children;
  11019. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11020. children[ i ].traverse( callback );
  11021. }
  11022. }
  11023. /**
  11024. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  11025. * Descendants of invisible 3D objects are not traversed.
  11026. *
  11027. * Note: Modifying the scene graph inside the callback is discouraged.
  11028. *
  11029. * @param {Function} callback - A callback function that allows to process the current 3D object.
  11030. */
  11031. traverseVisible( callback ) {
  11032. if ( this.visible === false ) return;
  11033. callback( this );
  11034. const children = this.children;
  11035. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11036. children[ i ].traverseVisible( callback );
  11037. }
  11038. }
  11039. /**
  11040. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  11041. *
  11042. * Note: Modifying the scene graph inside the callback is discouraged.
  11043. *
  11044. * @param {Function} callback - A callback function that allows to process the current 3D object.
  11045. */
  11046. traverseAncestors( callback ) {
  11047. const parent = this.parent;
  11048. if ( parent !== null ) {
  11049. callback( parent );
  11050. parent.traverseAncestors( callback );
  11051. }
  11052. }
  11053. /**
  11054. * Updates the transformation matrix in local space by computing it from the current
  11055. * position, rotation and scale values.
  11056. */
  11057. updateMatrix() {
  11058. this.matrix.compose( this.position, this.quaternion, this.scale );
  11059. const pivot = this.pivot;
  11060. if ( pivot !== null ) {
  11061. const px = pivot.x, py = pivot.y, pz = pivot.z;
  11062. const te = this.matrix.elements;
  11063. te[ 12 ] += px - te[ 0 ] * px - te[ 4 ] * py - te[ 8 ] * pz;
  11064. te[ 13 ] += py - te[ 1 ] * px - te[ 5 ] * py - te[ 9 ] * pz;
  11065. te[ 14 ] += pz - te[ 2 ] * px - te[ 6 ] * py - te[ 10 ] * pz;
  11066. }
  11067. this.matrixWorldNeedsUpdate = true;
  11068. }
  11069. /**
  11070. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  11071. *
  11072. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  11073. * local space. The computation of the local and world matrix can be controlled with the
  11074. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  11075. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  11076. *
  11077. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  11078. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  11079. */
  11080. updateMatrixWorld( force ) {
  11081. if ( this.matrixAutoUpdate ) this.updateMatrix();
  11082. if ( this.matrixWorldNeedsUpdate || force ) {
  11083. if ( this.matrixWorldAutoUpdate === true ) {
  11084. if ( this.parent === null ) {
  11085. this.matrixWorld.copy( this.matrix );
  11086. } else {
  11087. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  11088. }
  11089. }
  11090. this.matrixWorldNeedsUpdate = false;
  11091. force = true;
  11092. }
  11093. // make sure descendants are updated if required
  11094. const children = this.children;
  11095. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11096. const child = children[ i ];
  11097. child.updateMatrixWorld( force );
  11098. }
  11099. }
  11100. /**
  11101. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  11102. * update of ancestor and descendant nodes.
  11103. *
  11104. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  11105. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  11106. */
  11107. updateWorldMatrix( updateParents, updateChildren ) {
  11108. const parent = this.parent;
  11109. if ( updateParents === true && parent !== null ) {
  11110. parent.updateWorldMatrix( true, false );
  11111. }
  11112. if ( this.matrixAutoUpdate ) this.updateMatrix();
  11113. if ( this.matrixWorldAutoUpdate === true ) {
  11114. if ( this.parent === null ) {
  11115. this.matrixWorld.copy( this.matrix );
  11116. } else {
  11117. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  11118. }
  11119. }
  11120. // make sure descendants are updated
  11121. if ( updateChildren === true ) {
  11122. const children = this.children;
  11123. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11124. const child = children[ i ];
  11125. child.updateWorldMatrix( false, true );
  11126. }
  11127. }
  11128. }
  11129. /**
  11130. * Serializes the 3D object into JSON.
  11131. *
  11132. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11133. * @return {Object} A JSON object representing the serialized 3D object.
  11134. * @see {@link ObjectLoader#parse}
  11135. */
  11136. toJSON( meta ) {
  11137. // meta is a string when called from JSON.stringify
  11138. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  11139. const output = {};
  11140. // meta is a hash used to collect geometries, materials.
  11141. // not providing it implies that this is the root object
  11142. // being serialized.
  11143. if ( isRootObject ) {
  11144. // initialize meta obj
  11145. meta = {
  11146. geometries: {},
  11147. materials: {},
  11148. textures: {},
  11149. images: {},
  11150. shapes: {},
  11151. skeletons: {},
  11152. animations: {},
  11153. nodes: {}
  11154. };
  11155. output.metadata = {
  11156. version: 4.7,
  11157. type: 'Object',
  11158. generator: 'Object3D.toJSON'
  11159. };
  11160. }
  11161. // standard Object3D serialization
  11162. const object = {};
  11163. object.uuid = this.uuid;
  11164. object.type = this.type;
  11165. if ( this.name !== '' ) object.name = this.name;
  11166. if ( this.castShadow === true ) object.castShadow = true;
  11167. if ( this.receiveShadow === true ) object.receiveShadow = true;
  11168. if ( this.visible === false ) object.visible = false;
  11169. if ( this.frustumCulled === false ) object.frustumCulled = false;
  11170. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  11171. if ( this.static !== false ) object.static = this.static;
  11172. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  11173. object.layers = this.layers.mask;
  11174. object.matrix = this.matrix.toArray();
  11175. object.up = this.up.toArray();
  11176. if ( this.pivot !== null ) object.pivot = this.pivot.toArray();
  11177. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  11178. // object specific properties
  11179. if ( this.isInstancedMesh ) {
  11180. object.type = 'InstancedMesh';
  11181. object.count = this.count;
  11182. object.instanceMatrix = this.instanceMatrix.toJSON();
  11183. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  11184. }
  11185. if ( this.isBatchedMesh ) {
  11186. object.type = 'BatchedMesh';
  11187. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  11188. object.sortObjects = this.sortObjects;
  11189. object.drawRanges = this._drawRanges;
  11190. object.reservedRanges = this._reservedRanges;
  11191. object.geometryInfo = this._geometryInfo.map( info => ( {
  11192. ...info,
  11193. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  11194. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  11195. } ) );
  11196. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  11197. object.availableInstanceIds = this._availableInstanceIds.slice();
  11198. object.availableGeometryIds = this._availableGeometryIds.slice();
  11199. object.nextIndexStart = this._nextIndexStart;
  11200. object.nextVertexStart = this._nextVertexStart;
  11201. object.geometryCount = this._geometryCount;
  11202. object.maxInstanceCount = this._maxInstanceCount;
  11203. object.maxVertexCount = this._maxVertexCount;
  11204. object.maxIndexCount = this._maxIndexCount;
  11205. object.geometryInitialized = this._geometryInitialized;
  11206. object.matricesTexture = this._matricesTexture.toJSON( meta );
  11207. object.indirectTexture = this._indirectTexture.toJSON( meta );
  11208. if ( this._colorsTexture !== null ) {
  11209. object.colorsTexture = this._colorsTexture.toJSON( meta );
  11210. }
  11211. if ( this.boundingSphere !== null ) {
  11212. object.boundingSphere = this.boundingSphere.toJSON();
  11213. }
  11214. if ( this.boundingBox !== null ) {
  11215. object.boundingBox = this.boundingBox.toJSON();
  11216. }
  11217. }
  11218. //
  11219. function serialize( library, element ) {
  11220. if ( library[ element.uuid ] === undefined ) {
  11221. library[ element.uuid ] = element.toJSON( meta );
  11222. }
  11223. return element.uuid;
  11224. }
  11225. if ( this.isScene ) {
  11226. if ( this.background ) {
  11227. if ( this.background.isColor ) {
  11228. object.background = this.background.toJSON();
  11229. } else if ( this.background.isTexture ) {
  11230. object.background = this.background.toJSON( meta ).uuid;
  11231. }
  11232. }
  11233. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  11234. object.environment = this.environment.toJSON( meta ).uuid;
  11235. }
  11236. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  11237. object.geometry = serialize( meta.geometries, this.geometry );
  11238. const parameters = this.geometry.parameters;
  11239. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  11240. const shapes = parameters.shapes;
  11241. if ( Array.isArray( shapes ) ) {
  11242. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  11243. const shape = shapes[ i ];
  11244. serialize( meta.shapes, shape );
  11245. }
  11246. } else {
  11247. serialize( meta.shapes, shapes );
  11248. }
  11249. }
  11250. }
  11251. if ( this.isSkinnedMesh ) {
  11252. object.bindMode = this.bindMode;
  11253. object.bindMatrix = this.bindMatrix.toArray();
  11254. if ( this.skeleton !== undefined ) {
  11255. serialize( meta.skeletons, this.skeleton );
  11256. object.skeleton = this.skeleton.uuid;
  11257. }
  11258. }
  11259. if ( this.material !== undefined ) {
  11260. if ( Array.isArray( this.material ) ) {
  11261. const uuids = [];
  11262. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11263. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11264. }
  11265. object.material = uuids;
  11266. } else {
  11267. object.material = serialize( meta.materials, this.material );
  11268. }
  11269. }
  11270. //
  11271. if ( this.children.length > 0 ) {
  11272. object.children = [];
  11273. for ( let i = 0; i < this.children.length; i ++ ) {
  11274. object.children.push( this.children[ i ].toJSON( meta ).object );
  11275. }
  11276. }
  11277. //
  11278. if ( this.animations.length > 0 ) {
  11279. object.animations = [];
  11280. for ( let i = 0; i < this.animations.length; i ++ ) {
  11281. const animation = this.animations[ i ];
  11282. object.animations.push( serialize( meta.animations, animation ) );
  11283. }
  11284. }
  11285. if ( isRootObject ) {
  11286. const geometries = extractFromCache( meta.geometries );
  11287. const materials = extractFromCache( meta.materials );
  11288. const textures = extractFromCache( meta.textures );
  11289. const images = extractFromCache( meta.images );
  11290. const shapes = extractFromCache( meta.shapes );
  11291. const skeletons = extractFromCache( meta.skeletons );
  11292. const animations = extractFromCache( meta.animations );
  11293. const nodes = extractFromCache( meta.nodes );
  11294. if ( geometries.length > 0 ) output.geometries = geometries;
  11295. if ( materials.length > 0 ) output.materials = materials;
  11296. if ( textures.length > 0 ) output.textures = textures;
  11297. if ( images.length > 0 ) output.images = images;
  11298. if ( shapes.length > 0 ) output.shapes = shapes;
  11299. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11300. if ( animations.length > 0 ) output.animations = animations;
  11301. if ( nodes.length > 0 ) output.nodes = nodes;
  11302. }
  11303. output.object = object;
  11304. return output;
  11305. // extract data from the cache hash
  11306. // remove metadata on each item
  11307. // and return as array
  11308. function extractFromCache( cache ) {
  11309. const values = [];
  11310. for ( const key in cache ) {
  11311. const data = cache[ key ];
  11312. delete data.metadata;
  11313. values.push( data );
  11314. }
  11315. return values;
  11316. }
  11317. }
  11318. /**
  11319. * Returns a new 3D object with copied values from this instance.
  11320. *
  11321. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11322. * @return {Object3D} A clone of this instance.
  11323. */
  11324. clone( recursive ) {
  11325. return new this.constructor().copy( this, recursive );
  11326. }
  11327. /**
  11328. * Copies the values of the given 3D object to this instance.
  11329. *
  11330. * @param {Object3D} source - The 3D object to copy.
  11331. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11332. * @return {Object3D} A reference to this instance.
  11333. */
  11334. copy( source, recursive = true ) {
  11335. this.name = source.name;
  11336. this.up.copy( source.up );
  11337. this.position.copy( source.position );
  11338. this.rotation.order = source.rotation.order;
  11339. this.quaternion.copy( source.quaternion );
  11340. this.scale.copy( source.scale );
  11341. if ( source.pivot !== null ) {
  11342. this.pivot = source.pivot.clone();
  11343. }
  11344. this.matrix.copy( source.matrix );
  11345. this.matrixWorld.copy( source.matrixWorld );
  11346. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11347. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11348. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11349. this.layers.mask = source.layers.mask;
  11350. this.visible = source.visible;
  11351. this.castShadow = source.castShadow;
  11352. this.receiveShadow = source.receiveShadow;
  11353. this.frustumCulled = source.frustumCulled;
  11354. this.renderOrder = source.renderOrder;
  11355. this.static = source.static;
  11356. this.animations = source.animations.slice();
  11357. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11358. if ( recursive === true ) {
  11359. for ( let i = 0; i < source.children.length; i ++ ) {
  11360. const child = source.children[ i ];
  11361. this.add( child.clone() );
  11362. }
  11363. }
  11364. return this;
  11365. }
  11366. }
  11367. /**
  11368. * The default up direction for objects, also used as the default
  11369. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11370. *
  11371. * @static
  11372. * @type {Vector3}
  11373. * @default (0,1,0)
  11374. */
  11375. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11376. /**
  11377. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11378. * newly created 3D objects.
  11379. *
  11380. * @static
  11381. * @type {boolean}
  11382. * @default true
  11383. */
  11384. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11385. /**
  11386. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11387. * newly created 3D objects.
  11388. *
  11389. * @static
  11390. * @type {boolean}
  11391. * @default true
  11392. */
  11393. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11394. const _v0$1 = /*@__PURE__*/ new Vector3();
  11395. const _v1$3 = /*@__PURE__*/ new Vector3();
  11396. const _v2$2 = /*@__PURE__*/ new Vector3();
  11397. const _v3$2 = /*@__PURE__*/ new Vector3();
  11398. const _vab = /*@__PURE__*/ new Vector3();
  11399. const _vac = /*@__PURE__*/ new Vector3();
  11400. const _vbc = /*@__PURE__*/ new Vector3();
  11401. const _vap = /*@__PURE__*/ new Vector3();
  11402. const _vbp = /*@__PURE__*/ new Vector3();
  11403. const _vcp = /*@__PURE__*/ new Vector3();
  11404. const _v40 = /*@__PURE__*/ new Vector4();
  11405. const _v41 = /*@__PURE__*/ new Vector4();
  11406. const _v42 = /*@__PURE__*/ new Vector4();
  11407. /**
  11408. * A geometric triangle as defined by three vectors representing its three corners.
  11409. */
  11410. class Triangle {
  11411. /**
  11412. * Constructs a new triangle.
  11413. *
  11414. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11415. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11416. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11417. */
  11418. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11419. /**
  11420. * The first corner of the triangle.
  11421. *
  11422. * @type {Vector3}
  11423. */
  11424. this.a = a;
  11425. /**
  11426. * The second corner of the triangle.
  11427. *
  11428. * @type {Vector3}
  11429. */
  11430. this.b = b;
  11431. /**
  11432. * The third corner of the triangle.
  11433. *
  11434. * @type {Vector3}
  11435. */
  11436. this.c = c;
  11437. }
  11438. /**
  11439. * Computes the normal vector of a triangle.
  11440. *
  11441. * @param {Vector3} a - The first corner of the triangle.
  11442. * @param {Vector3} b - The second corner of the triangle.
  11443. * @param {Vector3} c - The third corner of the triangle.
  11444. * @param {Vector3} target - The target vector that is used to store the method's result.
  11445. * @return {Vector3} The triangle's normal.
  11446. */
  11447. static getNormal( a, b, c, target ) {
  11448. target.subVectors( c, b );
  11449. _v0$1.subVectors( a, b );
  11450. target.cross( _v0$1 );
  11451. const targetLengthSq = target.lengthSq();
  11452. if ( targetLengthSq > 0 ) {
  11453. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11454. }
  11455. return target.set( 0, 0, 0 );
  11456. }
  11457. /**
  11458. * Computes a barycentric coordinates from the given vector.
  11459. * Returns `null` if the triangle is degenerate.
  11460. *
  11461. * @param {Vector3} point - A point in 3D space.
  11462. * @param {Vector3} a - The first corner of the triangle.
  11463. * @param {Vector3} b - The second corner of the triangle.
  11464. * @param {Vector3} c - The third corner of the triangle.
  11465. * @param {Vector3} target - The target vector that is used to store the method's result.
  11466. * @return {?Vector3} The barycentric coordinates for the given point
  11467. */
  11468. static getBarycoord( point, a, b, c, target ) {
  11469. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11470. _v0$1.subVectors( c, a );
  11471. _v1$3.subVectors( b, a );
  11472. _v2$2.subVectors( point, a );
  11473. const dot00 = _v0$1.dot( _v0$1 );
  11474. const dot01 = _v0$1.dot( _v1$3 );
  11475. const dot02 = _v0$1.dot( _v2$2 );
  11476. const dot11 = _v1$3.dot( _v1$3 );
  11477. const dot12 = _v1$3.dot( _v2$2 );
  11478. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11479. // collinear or singular triangle
  11480. if ( denom === 0 ) {
  11481. target.set( 0, 0, 0 );
  11482. return null;
  11483. }
  11484. const invDenom = 1 / denom;
  11485. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11486. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11487. // barycentric coordinates must always sum to 1
  11488. return target.set( 1 - u - v, v, u );
  11489. }
  11490. /**
  11491. * Returns `true` if the given point, when projected onto the plane of the
  11492. * triangle, lies within the triangle.
  11493. *
  11494. * @param {Vector3} point - The point in 3D space to test.
  11495. * @param {Vector3} a - The first corner of the triangle.
  11496. * @param {Vector3} b - The second corner of the triangle.
  11497. * @param {Vector3} c - The third corner of the triangle.
  11498. * @return {boolean} Whether the given point, when projected onto the plane of the
  11499. * triangle, lies within the triangle or not.
  11500. */
  11501. static containsPoint( point, a, b, c ) {
  11502. // if the triangle is degenerate then we can't contain a point
  11503. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11504. return false;
  11505. }
  11506. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11507. }
  11508. /**
  11509. * Computes the value barycentrically interpolated for the given point on the
  11510. * triangle. Returns `null` if the triangle is degenerate.
  11511. *
  11512. * @param {Vector3} point - Position of interpolated point.
  11513. * @param {Vector3} p1 - The first corner of the triangle.
  11514. * @param {Vector3} p2 - The second corner of the triangle.
  11515. * @param {Vector3} p3 - The third corner of the triangle.
  11516. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11517. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11518. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11519. * @param {Vector3} target - The target vector that is used to store the method's result.
  11520. * @return {?Vector3} The interpolated value.
  11521. */
  11522. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11523. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11524. target.x = 0;
  11525. target.y = 0;
  11526. if ( 'z' in target ) target.z = 0;
  11527. if ( 'w' in target ) target.w = 0;
  11528. return null;
  11529. }
  11530. target.setScalar( 0 );
  11531. target.addScaledVector( v1, _v3$2.x );
  11532. target.addScaledVector( v2, _v3$2.y );
  11533. target.addScaledVector( v3, _v3$2.z );
  11534. return target;
  11535. }
  11536. /**
  11537. * Computes the value barycentrically interpolated for the given attribute and indices.
  11538. *
  11539. * @param {BufferAttribute} attr - The attribute to interpolate.
  11540. * @param {number} i1 - Index of first vertex.
  11541. * @param {number} i2 - Index of second vertex.
  11542. * @param {number} i3 - Index of third vertex.
  11543. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11544. * @param {Vector3} target - The target vector that is used to store the method's result.
  11545. * @return {Vector3} The interpolated attribute value.
  11546. */
  11547. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11548. _v40.setScalar( 0 );
  11549. _v41.setScalar( 0 );
  11550. _v42.setScalar( 0 );
  11551. _v40.fromBufferAttribute( attr, i1 );
  11552. _v41.fromBufferAttribute( attr, i2 );
  11553. _v42.fromBufferAttribute( attr, i3 );
  11554. target.setScalar( 0 );
  11555. target.addScaledVector( _v40, barycoord.x );
  11556. target.addScaledVector( _v41, barycoord.y );
  11557. target.addScaledVector( _v42, barycoord.z );
  11558. return target;
  11559. }
  11560. /**
  11561. * Returns `true` if the triangle is oriented towards the given direction.
  11562. *
  11563. * @param {Vector3} a - The first corner of the triangle.
  11564. * @param {Vector3} b - The second corner of the triangle.
  11565. * @param {Vector3} c - The third corner of the triangle.
  11566. * @param {Vector3} direction - The (normalized) direction vector.
  11567. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11568. */
  11569. static isFrontFacing( a, b, c, direction ) {
  11570. _v0$1.subVectors( c, b );
  11571. _v1$3.subVectors( a, b );
  11572. // strictly front facing
  11573. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11574. }
  11575. /**
  11576. * Sets the triangle's vertices by copying the given values.
  11577. *
  11578. * @param {Vector3} a - The first corner of the triangle.
  11579. * @param {Vector3} b - The second corner of the triangle.
  11580. * @param {Vector3} c - The third corner of the triangle.
  11581. * @return {Triangle} A reference to this triangle.
  11582. */
  11583. set( a, b, c ) {
  11584. this.a.copy( a );
  11585. this.b.copy( b );
  11586. this.c.copy( c );
  11587. return this;
  11588. }
  11589. /**
  11590. * Sets the triangle's vertices by copying the given array values.
  11591. *
  11592. * @param {Array<Vector3>} points - An array with 3D points.
  11593. * @param {number} i0 - The array index representing the first corner of the triangle.
  11594. * @param {number} i1 - The array index representing the second corner of the triangle.
  11595. * @param {number} i2 - The array index representing the third corner of the triangle.
  11596. * @return {Triangle} A reference to this triangle.
  11597. */
  11598. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11599. this.a.copy( points[ i0 ] );
  11600. this.b.copy( points[ i1 ] );
  11601. this.c.copy( points[ i2 ] );
  11602. return this;
  11603. }
  11604. /**
  11605. * Sets the triangle's vertices by copying the given attribute values.
  11606. *
  11607. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11608. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11609. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11610. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11611. * @return {Triangle} A reference to this triangle.
  11612. */
  11613. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11614. this.a.fromBufferAttribute( attribute, i0 );
  11615. this.b.fromBufferAttribute( attribute, i1 );
  11616. this.c.fromBufferAttribute( attribute, i2 );
  11617. return this;
  11618. }
  11619. /**
  11620. * Returns a new triangle with copied values from this instance.
  11621. *
  11622. * @return {Triangle} A clone of this instance.
  11623. */
  11624. clone() {
  11625. return new this.constructor().copy( this );
  11626. }
  11627. /**
  11628. * Copies the values of the given triangle to this instance.
  11629. *
  11630. * @param {Triangle} triangle - The triangle to copy.
  11631. * @return {Triangle} A reference to this triangle.
  11632. */
  11633. copy( triangle ) {
  11634. this.a.copy( triangle.a );
  11635. this.b.copy( triangle.b );
  11636. this.c.copy( triangle.c );
  11637. return this;
  11638. }
  11639. /**
  11640. * Computes the area of the triangle.
  11641. *
  11642. * @return {number} The triangle's area.
  11643. */
  11644. getArea() {
  11645. _v0$1.subVectors( this.c, this.b );
  11646. _v1$3.subVectors( this.a, this.b );
  11647. return _v0$1.cross( _v1$3 ).length() * 0.5;
  11648. }
  11649. /**
  11650. * Computes the midpoint of the triangle.
  11651. *
  11652. * @param {Vector3} target - The target vector that is used to store the method's result.
  11653. * @return {Vector3} The triangle's midpoint.
  11654. */
  11655. getMidpoint( target ) {
  11656. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11657. }
  11658. /**
  11659. * Computes the normal of the triangle.
  11660. *
  11661. * @param {Vector3} target - The target vector that is used to store the method's result.
  11662. * @return {Vector3} The triangle's normal.
  11663. */
  11664. getNormal( target ) {
  11665. return Triangle.getNormal( this.a, this.b, this.c, target );
  11666. }
  11667. /**
  11668. * Computes a plane the triangle lies within.
  11669. *
  11670. * @param {Plane} target - The target vector that is used to store the method's result.
  11671. * @return {Plane} The plane the triangle lies within.
  11672. */
  11673. getPlane( target ) {
  11674. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11675. }
  11676. /**
  11677. * Computes a barycentric coordinates from the given vector.
  11678. * Returns `null` if the triangle is degenerate.
  11679. *
  11680. * @param {Vector3} point - A point in 3D space.
  11681. * @param {Vector3} target - The target vector that is used to store the method's result.
  11682. * @return {?Vector3} The barycentric coordinates for the given point
  11683. */
  11684. getBarycoord( point, target ) {
  11685. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11686. }
  11687. /**
  11688. * Computes the value barycentrically interpolated for the given point on the
  11689. * triangle. Returns `null` if the triangle is degenerate.
  11690. *
  11691. * @param {Vector3} point - Position of interpolated point.
  11692. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11693. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11694. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11695. * @param {Vector3} target - The target vector that is used to store the method's result.
  11696. * @return {?Vector3} The interpolated value.
  11697. */
  11698. getInterpolation( point, v1, v2, v3, target ) {
  11699. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11700. }
  11701. /**
  11702. * Returns `true` if the given point, when projected onto the plane of the
  11703. * triangle, lies within the triangle.
  11704. *
  11705. * @param {Vector3} point - The point in 3D space to test.
  11706. * @return {boolean} Whether the given point, when projected onto the plane of the
  11707. * triangle, lies within the triangle or not.
  11708. */
  11709. containsPoint( point ) {
  11710. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11711. }
  11712. /**
  11713. * Returns `true` if the triangle is oriented towards the given direction.
  11714. *
  11715. * @param {Vector3} direction - The (normalized) direction vector.
  11716. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11717. */
  11718. isFrontFacing( direction ) {
  11719. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11720. }
  11721. /**
  11722. * Returns `true` if this triangle intersects with the given box.
  11723. *
  11724. * @param {Box3} box - The box to intersect.
  11725. * @return {boolean} Whether this triangle intersects with the given box or not.
  11726. */
  11727. intersectsBox( box ) {
  11728. return box.intersectsTriangle( this );
  11729. }
  11730. /**
  11731. * Returns the closest point on the triangle to the given point.
  11732. *
  11733. * @param {Vector3} p - The point to compute the closest point for.
  11734. * @param {Vector3} target - The target vector that is used to store the method's result.
  11735. * @return {Vector3} The closest point on the triangle.
  11736. */
  11737. closestPointToPoint( p, target ) {
  11738. const a = this.a, b = this.b, c = this.c;
  11739. let v, w;
  11740. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11741. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11742. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11743. // basically, we're distinguishing which of the voronoi regions of the triangle
  11744. // the point lies in with the minimum amount of redundant computation.
  11745. _vab.subVectors( b, a );
  11746. _vac.subVectors( c, a );
  11747. _vap.subVectors( p, a );
  11748. const d1 = _vab.dot( _vap );
  11749. const d2 = _vac.dot( _vap );
  11750. if ( d1 <= 0 && d2 <= 0 ) {
  11751. // vertex region of A; barycentric coords (1, 0, 0)
  11752. return target.copy( a );
  11753. }
  11754. _vbp.subVectors( p, b );
  11755. const d3 = _vab.dot( _vbp );
  11756. const d4 = _vac.dot( _vbp );
  11757. if ( d3 >= 0 && d4 <= d3 ) {
  11758. // vertex region of B; barycentric coords (0, 1, 0)
  11759. return target.copy( b );
  11760. }
  11761. const vc = d1 * d4 - d3 * d2;
  11762. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11763. v = d1 / ( d1 - d3 );
  11764. // edge region of AB; barycentric coords (1-v, v, 0)
  11765. return target.copy( a ).addScaledVector( _vab, v );
  11766. }
  11767. _vcp.subVectors( p, c );
  11768. const d5 = _vab.dot( _vcp );
  11769. const d6 = _vac.dot( _vcp );
  11770. if ( d6 >= 0 && d5 <= d6 ) {
  11771. // vertex region of C; barycentric coords (0, 0, 1)
  11772. return target.copy( c );
  11773. }
  11774. const vb = d5 * d2 - d1 * d6;
  11775. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11776. w = d2 / ( d2 - d6 );
  11777. // edge region of AC; barycentric coords (1-w, 0, w)
  11778. return target.copy( a ).addScaledVector( _vac, w );
  11779. }
  11780. const va = d3 * d6 - d5 * d4;
  11781. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11782. _vbc.subVectors( c, b );
  11783. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11784. // edge region of BC; barycentric coords (0, 1-w, w)
  11785. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11786. }
  11787. // face region
  11788. const denom = 1 / ( va + vb + vc );
  11789. // u = va * denom
  11790. v = vb * denom;
  11791. w = vc * denom;
  11792. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11793. }
  11794. /**
  11795. * Returns `true` if this triangle is equal with the given one.
  11796. *
  11797. * @param {Triangle} triangle - The triangle to test for equality.
  11798. * @return {boolean} Whether this triangle is equal with the given one.
  11799. */
  11800. equals( triangle ) {
  11801. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11802. }
  11803. }
  11804. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11805. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11806. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11807. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11808. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11809. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11810. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11811. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11812. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11813. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11814. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11815. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11816. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11817. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11818. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11819. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11820. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11821. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11822. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11823. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11824. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11825. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11826. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11827. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11828. const _hslA = { h: 0, s: 0, l: 0 };
  11829. const _hslB = { h: 0, s: 0, l: 0 };
  11830. function hue2rgb( p, q, t ) {
  11831. if ( t < 0 ) t += 1;
  11832. if ( t > 1 ) t -= 1;
  11833. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11834. if ( t < 1 / 2 ) return q;
  11835. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11836. return p;
  11837. }
  11838. /**
  11839. * A Color instance is represented by RGB components in the linear <i>working
  11840. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11841. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11842. * strings) are converted to the working color space automatically.
  11843. *
  11844. * ```js
  11845. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11846. * const color = new THREE.Color().setHex( 0x112233 );
  11847. * ```
  11848. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11849. * ```js
  11850. * // assumed already LinearSRGBColorSpace; no conversion
  11851. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11852. *
  11853. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11854. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11855. * ```
  11856. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11857. * see <i>Color management</i>. Iterating through a Color instance will yield
  11858. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11859. * in any of the following ways:
  11860. * ```js
  11861. * //empty constructor - will default white
  11862. * const color1 = new THREE.Color();
  11863. *
  11864. * //Hexadecimal color (recommended)
  11865. * const color2 = new THREE.Color( 0xff0000 );
  11866. *
  11867. * //RGB string
  11868. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11869. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11870. *
  11871. * //X11 color name - all 140 color names are supported.
  11872. * //Note the lack of CamelCase in the name
  11873. * const color5 = new THREE.Color( 'skyblue' );
  11874. * //HSL string
  11875. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11876. *
  11877. * //Separate RGB values between 0 and 1
  11878. * const color7 = new THREE.Color( 1, 0, 0 );
  11879. * ```
  11880. */
  11881. class Color {
  11882. /**
  11883. * Constructs a new color.
  11884. *
  11885. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11886. * and that method is used throughout the rest of the documentation.
  11887. *
  11888. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11889. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11890. * @param {number} [g] - The green component.
  11891. * @param {number} [b] - The blue component.
  11892. */
  11893. constructor( r, g, b ) {
  11894. /**
  11895. * This flag can be used for type testing.
  11896. *
  11897. * @type {boolean}
  11898. * @readonly
  11899. * @default true
  11900. */
  11901. this.isColor = true;
  11902. /**
  11903. * The red component.
  11904. *
  11905. * @type {number}
  11906. * @default 1
  11907. */
  11908. this.r = 1;
  11909. /**
  11910. * The green component.
  11911. *
  11912. * @type {number}
  11913. * @default 1
  11914. */
  11915. this.g = 1;
  11916. /**
  11917. * The blue component.
  11918. *
  11919. * @type {number}
  11920. * @default 1
  11921. */
  11922. this.b = 1;
  11923. return this.set( r, g, b );
  11924. }
  11925. /**
  11926. * Sets the colors's components from the given values.
  11927. *
  11928. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11929. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11930. * @param {number} [g] - The green component.
  11931. * @param {number} [b] - The blue component.
  11932. * @return {Color} A reference to this color.
  11933. */
  11934. set( r, g, b ) {
  11935. if ( g === undefined && b === undefined ) {
  11936. // r is THREE.Color, hex or string
  11937. const value = r;
  11938. if ( value && value.isColor ) {
  11939. this.copy( value );
  11940. } else if ( typeof value === 'number' ) {
  11941. this.setHex( value );
  11942. } else if ( typeof value === 'string' ) {
  11943. this.setStyle( value );
  11944. }
  11945. } else {
  11946. this.setRGB( r, g, b );
  11947. }
  11948. return this;
  11949. }
  11950. /**
  11951. * Sets the colors's components to the given scalar value.
  11952. *
  11953. * @param {number} scalar - The scalar value.
  11954. * @return {Color} A reference to this color.
  11955. */
  11956. setScalar( scalar ) {
  11957. this.r = scalar;
  11958. this.g = scalar;
  11959. this.b = scalar;
  11960. return this;
  11961. }
  11962. /**
  11963. * Sets this color from a hexadecimal value.
  11964. *
  11965. * @param {number} hex - The hexadecimal value.
  11966. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11967. * @return {Color} A reference to this color.
  11968. */
  11969. setHex( hex, colorSpace = SRGBColorSpace ) {
  11970. hex = Math.floor( hex );
  11971. this.r = ( hex >> 16 & 255 ) / 255;
  11972. this.g = ( hex >> 8 & 255 ) / 255;
  11973. this.b = ( hex & 255 ) / 255;
  11974. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11975. return this;
  11976. }
  11977. /**
  11978. * Sets this color from RGB values.
  11979. *
  11980. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11981. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11982. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11983. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11984. * @return {Color} A reference to this color.
  11985. */
  11986. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11987. this.r = r;
  11988. this.g = g;
  11989. this.b = b;
  11990. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11991. return this;
  11992. }
  11993. /**
  11994. * Sets this color from RGB values.
  11995. *
  11996. * @param {number} h - Hue value between `0.0` and `1.0`.
  11997. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11998. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11999. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12000. * @return {Color} A reference to this color.
  12001. */
  12002. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  12003. // h,s,l ranges are in 0.0 - 1.0
  12004. h = euclideanModulo( h, 1 );
  12005. s = clamp( s, 0, 1 );
  12006. l = clamp( l, 0, 1 );
  12007. if ( s === 0 ) {
  12008. this.r = this.g = this.b = l;
  12009. } else {
  12010. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  12011. const q = ( 2 * l ) - p;
  12012. this.r = hue2rgb( q, p, h + 1 / 3 );
  12013. this.g = hue2rgb( q, p, h );
  12014. this.b = hue2rgb( q, p, h - 1 / 3 );
  12015. }
  12016. ColorManagement.colorSpaceToWorking( this, colorSpace );
  12017. return this;
  12018. }
  12019. /**
  12020. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  12021. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  12022. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  12023. * all 140 color names are supported).
  12024. *
  12025. * @param {string} style - Color as a CSS-style string.
  12026. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12027. * @return {Color} A reference to this color.
  12028. */
  12029. setStyle( style, colorSpace = SRGBColorSpace ) {
  12030. function handleAlpha( string ) {
  12031. if ( string === undefined ) return;
  12032. if ( parseFloat( string ) < 1 ) {
  12033. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  12034. }
  12035. }
  12036. let m;
  12037. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  12038. // rgb / hsl
  12039. let color;
  12040. const name = m[ 1 ];
  12041. const components = m[ 2 ];
  12042. switch ( name ) {
  12043. case 'rgb':
  12044. case 'rgba':
  12045. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  12046. // rgb(255,0,0) rgba(255,0,0,0.5)
  12047. handleAlpha( color[ 4 ] );
  12048. return this.setRGB(
  12049. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  12050. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  12051. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  12052. colorSpace
  12053. );
  12054. }
  12055. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  12056. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  12057. handleAlpha( color[ 4 ] );
  12058. return this.setRGB(
  12059. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  12060. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  12061. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  12062. colorSpace
  12063. );
  12064. }
  12065. break;
  12066. case 'hsl':
  12067. case 'hsla':
  12068. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  12069. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  12070. handleAlpha( color[ 4 ] );
  12071. return this.setHSL(
  12072. parseFloat( color[ 1 ] ) / 360,
  12073. parseFloat( color[ 2 ] ) / 100,
  12074. parseFloat( color[ 3 ] ) / 100,
  12075. colorSpace
  12076. );
  12077. }
  12078. break;
  12079. default:
  12080. warn( 'Color: Unknown color model ' + style );
  12081. }
  12082. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  12083. // hex color
  12084. const hex = m[ 1 ];
  12085. const size = hex.length;
  12086. if ( size === 3 ) {
  12087. // #ff0
  12088. return this.setRGB(
  12089. parseInt( hex.charAt( 0 ), 16 ) / 15,
  12090. parseInt( hex.charAt( 1 ), 16 ) / 15,
  12091. parseInt( hex.charAt( 2 ), 16 ) / 15,
  12092. colorSpace
  12093. );
  12094. } else if ( size === 6 ) {
  12095. // #ff0000
  12096. return this.setHex( parseInt( hex, 16 ), colorSpace );
  12097. } else {
  12098. warn( 'Color: Invalid hex color ' + style );
  12099. }
  12100. } else if ( style && style.length > 0 ) {
  12101. return this.setColorName( style, colorSpace );
  12102. }
  12103. return this;
  12104. }
  12105. /**
  12106. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  12107. * you don't need the other CSS-style formats.
  12108. *
  12109. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  12110. * ```js
  12111. * Color.NAMES.aliceblue // returns 0xF0F8FF
  12112. * ```
  12113. *
  12114. * @param {string} style - The color name.
  12115. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12116. * @return {Color} A reference to this color.
  12117. */
  12118. setColorName( style, colorSpace = SRGBColorSpace ) {
  12119. // color keywords
  12120. const hex = _colorKeywords[ style.toLowerCase() ];
  12121. if ( hex !== undefined ) {
  12122. // red
  12123. this.setHex( hex, colorSpace );
  12124. } else {
  12125. // unknown color
  12126. warn( 'Color: Unknown color ' + style );
  12127. }
  12128. return this;
  12129. }
  12130. /**
  12131. * Returns a new color with copied values from this instance.
  12132. *
  12133. * @return {Color} A clone of this instance.
  12134. */
  12135. clone() {
  12136. return new this.constructor( this.r, this.g, this.b );
  12137. }
  12138. /**
  12139. * Copies the values of the given color to this instance.
  12140. *
  12141. * @param {Color} color - The color to copy.
  12142. * @return {Color} A reference to this color.
  12143. */
  12144. copy( color ) {
  12145. this.r = color.r;
  12146. this.g = color.g;
  12147. this.b = color.b;
  12148. return this;
  12149. }
  12150. /**
  12151. * Copies the given color into this color, and then converts this color from
  12152. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  12153. *
  12154. * @param {Color} color - The color to copy/convert.
  12155. * @return {Color} A reference to this color.
  12156. */
  12157. copySRGBToLinear( color ) {
  12158. this.r = SRGBToLinear( color.r );
  12159. this.g = SRGBToLinear( color.g );
  12160. this.b = SRGBToLinear( color.b );
  12161. return this;
  12162. }
  12163. /**
  12164. * Copies the given color into this color, and then converts this color from
  12165. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12166. *
  12167. * @param {Color} color - The color to copy/convert.
  12168. * @return {Color} A reference to this color.
  12169. */
  12170. copyLinearToSRGB( color ) {
  12171. this.r = LinearToSRGB( color.r );
  12172. this.g = LinearToSRGB( color.g );
  12173. this.b = LinearToSRGB( color.b );
  12174. return this;
  12175. }
  12176. /**
  12177. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  12178. *
  12179. * @return {Color} A reference to this color.
  12180. */
  12181. convertSRGBToLinear() {
  12182. this.copySRGBToLinear( this );
  12183. return this;
  12184. }
  12185. /**
  12186. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12187. *
  12188. * @return {Color} A reference to this color.
  12189. */
  12190. convertLinearToSRGB() {
  12191. this.copyLinearToSRGB( this );
  12192. return this;
  12193. }
  12194. /**
  12195. * Returns the hexadecimal value of this color.
  12196. *
  12197. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12198. * @return {number} The hexadecimal value.
  12199. */
  12200. getHex( colorSpace = SRGBColorSpace ) {
  12201. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12202. 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 ) );
  12203. }
  12204. /**
  12205. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  12206. *
  12207. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12208. * @return {string} The hexadecimal value as a string.
  12209. */
  12210. getHexString( colorSpace = SRGBColorSpace ) {
  12211. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  12212. }
  12213. /**
  12214. * Converts the colors RGB values into the HSL format and stores them into the
  12215. * given target object.
  12216. *
  12217. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  12218. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12219. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  12220. */
  12221. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  12222. // h,s,l ranges are in 0.0 - 1.0
  12223. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12224. const r = _color.r, g = _color.g, b = _color.b;
  12225. const max = Math.max( r, g, b );
  12226. const min = Math.min( r, g, b );
  12227. let hue, saturation;
  12228. const lightness = ( min + max ) / 2.0;
  12229. if ( min === max ) {
  12230. hue = 0;
  12231. saturation = 0;
  12232. } else {
  12233. const delta = max - min;
  12234. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  12235. switch ( max ) {
  12236. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  12237. case g: hue = ( b - r ) / delta + 2; break;
  12238. case b: hue = ( r - g ) / delta + 4; break;
  12239. }
  12240. hue /= 6;
  12241. }
  12242. target.h = hue;
  12243. target.s = saturation;
  12244. target.l = lightness;
  12245. return target;
  12246. }
  12247. /**
  12248. * Returns the RGB values of this color and stores them into the given target object.
  12249. *
  12250. * @param {Color} target - The target color that is used to store the method's result.
  12251. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12252. * @return {Color} The RGB representation of this color.
  12253. */
  12254. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  12255. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12256. target.r = _color.r;
  12257. target.g = _color.g;
  12258. target.b = _color.b;
  12259. return target;
  12260. }
  12261. /**
  12262. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12263. *
  12264. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12265. * @return {string} The CSS representation of this color.
  12266. */
  12267. getStyle( colorSpace = SRGBColorSpace ) {
  12268. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12269. const r = _color.r, g = _color.g, b = _color.b;
  12270. if ( colorSpace !== SRGBColorSpace ) {
  12271. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12272. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12273. }
  12274. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12275. }
  12276. /**
  12277. * Adds the given HSL values to this color's values.
  12278. * Internally, this converts the color's RGB values to HSL, adds HSL
  12279. * and then converts the color back to RGB.
  12280. *
  12281. * @param {number} h - Hue value between `0.0` and `1.0`.
  12282. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12283. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12284. * @return {Color} A reference to this color.
  12285. */
  12286. offsetHSL( h, s, l ) {
  12287. this.getHSL( _hslA );
  12288. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12289. }
  12290. /**
  12291. * Adds the RGB values of the given color to the RGB values of this color.
  12292. *
  12293. * @param {Color} color - The color to add.
  12294. * @return {Color} A reference to this color.
  12295. */
  12296. add( color ) {
  12297. this.r += color.r;
  12298. this.g += color.g;
  12299. this.b += color.b;
  12300. return this;
  12301. }
  12302. /**
  12303. * Adds the RGB values of the given colors and stores the result in this instance.
  12304. *
  12305. * @param {Color} color1 - The first color.
  12306. * @param {Color} color2 - The second color.
  12307. * @return {Color} A reference to this color.
  12308. */
  12309. addColors( color1, color2 ) {
  12310. this.r = color1.r + color2.r;
  12311. this.g = color1.g + color2.g;
  12312. this.b = color1.b + color2.b;
  12313. return this;
  12314. }
  12315. /**
  12316. * Adds the given scalar value to the RGB values of this color.
  12317. *
  12318. * @param {number} s - The scalar to add.
  12319. * @return {Color} A reference to this color.
  12320. */
  12321. addScalar( s ) {
  12322. this.r += s;
  12323. this.g += s;
  12324. this.b += s;
  12325. return this;
  12326. }
  12327. /**
  12328. * Subtracts the RGB values of the given color from the RGB values of this color.
  12329. *
  12330. * @param {Color} color - The color to subtract.
  12331. * @return {Color} A reference to this color.
  12332. */
  12333. sub( color ) {
  12334. this.r = Math.max( 0, this.r - color.r );
  12335. this.g = Math.max( 0, this.g - color.g );
  12336. this.b = Math.max( 0, this.b - color.b );
  12337. return this;
  12338. }
  12339. /**
  12340. * Multiplies the RGB values of the given color with the RGB values of this color.
  12341. *
  12342. * @param {Color} color - The color to multiply.
  12343. * @return {Color} A reference to this color.
  12344. */
  12345. multiply( color ) {
  12346. this.r *= color.r;
  12347. this.g *= color.g;
  12348. this.b *= color.b;
  12349. return this;
  12350. }
  12351. /**
  12352. * Multiplies the given scalar value with the RGB values of this color.
  12353. *
  12354. * @param {number} s - The scalar to multiply.
  12355. * @return {Color} A reference to this color.
  12356. */
  12357. multiplyScalar( s ) {
  12358. this.r *= s;
  12359. this.g *= s;
  12360. this.b *= s;
  12361. return this;
  12362. }
  12363. /**
  12364. * Linearly interpolates this color's RGB values toward the RGB values of the
  12365. * given color. The alpha argument can be thought of as the ratio between
  12366. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12367. *
  12368. * @param {Color} color - The color to converge on.
  12369. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12370. * @return {Color} A reference to this color.
  12371. */
  12372. lerp( color, alpha ) {
  12373. this.r += ( color.r - this.r ) * alpha;
  12374. this.g += ( color.g - this.g ) * alpha;
  12375. this.b += ( color.b - this.b ) * alpha;
  12376. return this;
  12377. }
  12378. /**
  12379. * Linearly interpolates between the given colors and stores the result in this instance.
  12380. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12381. * is the first and `1.0` is the second color.
  12382. *
  12383. * @param {Color} color1 - The first color.
  12384. * @param {Color} color2 - The second color.
  12385. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12386. * @return {Color} A reference to this color.
  12387. */
  12388. lerpColors( color1, color2, alpha ) {
  12389. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12390. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12391. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12392. return this;
  12393. }
  12394. /**
  12395. * Linearly interpolates this color's HSL values toward the HSL values of the
  12396. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12397. * from one color to the other, but instead going through all the hues in between
  12398. * those two colors. The alpha argument can be thought of as the ratio between
  12399. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12400. *
  12401. * @param {Color} color - The color to converge on.
  12402. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12403. * @return {Color} A reference to this color.
  12404. */
  12405. lerpHSL( color, alpha ) {
  12406. this.getHSL( _hslA );
  12407. color.getHSL( _hslB );
  12408. const h = lerp( _hslA.h, _hslB.h, alpha );
  12409. const s = lerp( _hslA.s, _hslB.s, alpha );
  12410. const l = lerp( _hslA.l, _hslB.l, alpha );
  12411. this.setHSL( h, s, l );
  12412. return this;
  12413. }
  12414. /**
  12415. * Sets the color's RGB components from the given 3D vector.
  12416. *
  12417. * @param {Vector3} v - The vector to set.
  12418. * @return {Color} A reference to this color.
  12419. */
  12420. setFromVector3( v ) {
  12421. this.r = v.x;
  12422. this.g = v.y;
  12423. this.b = v.z;
  12424. return this;
  12425. }
  12426. /**
  12427. * Transforms this color with the given 3x3 matrix.
  12428. *
  12429. * @param {Matrix3} m - The matrix.
  12430. * @return {Color} A reference to this color.
  12431. */
  12432. applyMatrix3( m ) {
  12433. const r = this.r, g = this.g, b = this.b;
  12434. const e = m.elements;
  12435. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12436. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12437. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12438. return this;
  12439. }
  12440. /**
  12441. * Returns `true` if this color is equal with the given one.
  12442. *
  12443. * @param {Color} c - The color to test for equality.
  12444. * @return {boolean} Whether this bounding color is equal with the given one.
  12445. */
  12446. equals( c ) {
  12447. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12448. }
  12449. /**
  12450. * Sets this color's RGB components from the given array.
  12451. *
  12452. * @param {Array<number>} array - An array holding the RGB values.
  12453. * @param {number} [offset=0] - The offset into the array.
  12454. * @return {Color} A reference to this color.
  12455. */
  12456. fromArray( array, offset = 0 ) {
  12457. this.r = array[ offset ];
  12458. this.g = array[ offset + 1 ];
  12459. this.b = array[ offset + 2 ];
  12460. return this;
  12461. }
  12462. /**
  12463. * Writes the RGB components of this color to the given array. If no array is provided,
  12464. * the method returns a new instance.
  12465. *
  12466. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12467. * @param {number} [offset=0] - Index of the first element in the array.
  12468. * @return {Array<number>} The color components.
  12469. */
  12470. toArray( array = [], offset = 0 ) {
  12471. array[ offset ] = this.r;
  12472. array[ offset + 1 ] = this.g;
  12473. array[ offset + 2 ] = this.b;
  12474. return array;
  12475. }
  12476. /**
  12477. * Sets the components of this color from the given buffer attribute.
  12478. *
  12479. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12480. * @param {number} index - The index into the attribute.
  12481. * @return {Color} A reference to this color.
  12482. */
  12483. fromBufferAttribute( attribute, index ) {
  12484. this.r = attribute.getX( index );
  12485. this.g = attribute.getY( index );
  12486. this.b = attribute.getZ( index );
  12487. return this;
  12488. }
  12489. /**
  12490. * This methods defines the serialization result of this class. Returns the color
  12491. * as a hexadecimal value.
  12492. *
  12493. * @return {number} The hexadecimal value.
  12494. */
  12495. toJSON() {
  12496. return this.getHex();
  12497. }
  12498. *[ Symbol.iterator ]() {
  12499. yield this.r;
  12500. yield this.g;
  12501. yield this.b;
  12502. }
  12503. }
  12504. const _color = /*@__PURE__*/ new Color();
  12505. /**
  12506. * A dictionary with X11 color names.
  12507. *
  12508. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12509. *
  12510. * @static
  12511. * @type {Object}
  12512. */
  12513. Color.NAMES = _colorKeywords;
  12514. let _materialId = 0;
  12515. /**
  12516. * Abstract base class for materials.
  12517. *
  12518. * Materials define the appearance of renderable 3D objects.
  12519. *
  12520. * @abstract
  12521. * @augments EventDispatcher
  12522. */
  12523. class Material extends EventDispatcher {
  12524. /**
  12525. * Constructs a new material.
  12526. */
  12527. constructor() {
  12528. super();
  12529. /**
  12530. * This flag can be used for type testing.
  12531. *
  12532. * @type {boolean}
  12533. * @readonly
  12534. * @default true
  12535. */
  12536. this.isMaterial = true;
  12537. /**
  12538. * The ID of the material.
  12539. *
  12540. * @name Material#id
  12541. * @type {number}
  12542. * @readonly
  12543. */
  12544. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12545. /**
  12546. * The UUID of the material.
  12547. *
  12548. * @type {string}
  12549. * @readonly
  12550. */
  12551. this.uuid = generateUUID();
  12552. /**
  12553. * The name of the material.
  12554. *
  12555. * @type {string}
  12556. */
  12557. this.name = '';
  12558. /**
  12559. * The type property is used for detecting the object type
  12560. * in context of serialization/deserialization.
  12561. *
  12562. * @type {string}
  12563. * @readonly
  12564. */
  12565. this.type = 'Material';
  12566. /**
  12567. * Defines the blending type of the material.
  12568. *
  12569. * It must be set to `CustomBlending` if custom blending properties like
  12570. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12571. * should have any effect.
  12572. *
  12573. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12574. * @default NormalBlending
  12575. */
  12576. this.blending = NormalBlending;
  12577. /**
  12578. * Defines which side of faces will be rendered - front, back or both.
  12579. *
  12580. * @type {(FrontSide|BackSide|DoubleSide)}
  12581. * @default FrontSide
  12582. */
  12583. this.side = FrontSide;
  12584. /**
  12585. * If set to `true`, vertex colors should be used.
  12586. *
  12587. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12588. * four (RGBA) component color buffer attribute is used.
  12589. *
  12590. * @type {boolean}
  12591. * @default false
  12592. */
  12593. this.vertexColors = false;
  12594. /**
  12595. * Defines how transparent the material is.
  12596. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12597. *
  12598. * If the {@link Material#transparent} is not set to `true`,
  12599. * the material will remain fully opaque and this value will only affect its color.
  12600. *
  12601. * @type {number}
  12602. * @default 1
  12603. */
  12604. this.opacity = 1;
  12605. /**
  12606. * Defines whether this material is transparent. This has an effect on
  12607. * rendering as transparent objects need special treatment and are rendered
  12608. * after non-transparent objects.
  12609. *
  12610. * When set to true, the extent to which the material is transparent is
  12611. * controlled by {@link Material#opacity}.
  12612. *
  12613. * @type {boolean}
  12614. * @default false
  12615. */
  12616. this.transparent = false;
  12617. /**
  12618. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12619. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12620. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12621. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12622. *
  12623. * @type {boolean}
  12624. * @default false
  12625. */
  12626. this.alphaHash = false;
  12627. /**
  12628. * Defines the blending source factor.
  12629. *
  12630. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12631. * @default SrcAlphaFactor
  12632. */
  12633. this.blendSrc = SrcAlphaFactor;
  12634. /**
  12635. * Defines the blending destination factor.
  12636. *
  12637. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12638. * @default OneMinusSrcAlphaFactor
  12639. */
  12640. this.blendDst = OneMinusSrcAlphaFactor;
  12641. /**
  12642. * Defines the blending equation.
  12643. *
  12644. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12645. * @default AddEquation
  12646. */
  12647. this.blendEquation = AddEquation;
  12648. /**
  12649. * Defines the blending source alpha factor.
  12650. *
  12651. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12652. * @default null
  12653. */
  12654. this.blendSrcAlpha = null;
  12655. /**
  12656. * Defines the blending destination alpha factor.
  12657. *
  12658. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12659. * @default null
  12660. */
  12661. this.blendDstAlpha = null;
  12662. /**
  12663. * Defines the blending equation of the alpha channel.
  12664. *
  12665. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12666. * @default null
  12667. */
  12668. this.blendEquationAlpha = null;
  12669. /**
  12670. * Represents the RGB values of the constant blend color.
  12671. *
  12672. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12673. *
  12674. * @type {Color}
  12675. * @default (0,0,0)
  12676. */
  12677. this.blendColor = new Color( 0, 0, 0 );
  12678. /**
  12679. * Represents the alpha value of the constant blend color.
  12680. *
  12681. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12682. *
  12683. * @type {number}
  12684. * @default 0
  12685. */
  12686. this.blendAlpha = 0;
  12687. /**
  12688. * Defines the depth function.
  12689. *
  12690. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12691. * @default LessEqualDepth
  12692. */
  12693. this.depthFunc = LessEqualDepth;
  12694. /**
  12695. * Whether to have depth test enabled when rendering this material.
  12696. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12697. *
  12698. * @type {boolean}
  12699. * @default true
  12700. */
  12701. this.depthTest = true;
  12702. /**
  12703. * Whether rendering this material has any effect on the depth buffer.
  12704. *
  12705. * When drawing 2D overlays it can be useful to disable the depth writing in
  12706. * order to layer several things together without creating z-index artifacts.
  12707. *
  12708. * @type {boolean}
  12709. * @default true
  12710. */
  12711. this.depthWrite = true;
  12712. /**
  12713. * The bit mask to use when writing to the stencil buffer.
  12714. *
  12715. * @type {number}
  12716. * @default 0xff
  12717. */
  12718. this.stencilWriteMask = 0xff;
  12719. /**
  12720. * The stencil comparison function to use.
  12721. *
  12722. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12723. * @default AlwaysStencilFunc
  12724. */
  12725. this.stencilFunc = AlwaysStencilFunc;
  12726. /**
  12727. * The value to use when performing stencil comparisons or stencil operations.
  12728. *
  12729. * @type {number}
  12730. * @default 0
  12731. */
  12732. this.stencilRef = 0;
  12733. /**
  12734. * The bit mask to use when comparing against the stencil buffer.
  12735. *
  12736. * @type {number}
  12737. * @default 0xff
  12738. */
  12739. this.stencilFuncMask = 0xff;
  12740. /**
  12741. * Which stencil operation to perform when the comparison function returns `false`.
  12742. *
  12743. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12744. * @default KeepStencilOp
  12745. */
  12746. this.stencilFail = KeepStencilOp;
  12747. /**
  12748. * Which stencil operation to perform when the comparison function returns
  12749. * `true` but the depth test fails.
  12750. *
  12751. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12752. * @default KeepStencilOp
  12753. */
  12754. this.stencilZFail = KeepStencilOp;
  12755. /**
  12756. * Which stencil operation to perform when the comparison function returns
  12757. * `true` and the depth test passes.
  12758. *
  12759. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12760. * @default KeepStencilOp
  12761. */
  12762. this.stencilZPass = KeepStencilOp;
  12763. /**
  12764. * Whether stencil operations are performed against the stencil buffer. In
  12765. * order to perform writes or comparisons against the stencil buffer this
  12766. * value must be `true`.
  12767. *
  12768. * @type {boolean}
  12769. * @default false
  12770. */
  12771. this.stencilWrite = false;
  12772. /**
  12773. * User-defined clipping planes specified as THREE.Plane objects in world
  12774. * space. These planes apply to the objects this material is attached to.
  12775. * Points in space whose signed distance to the plane is negative are clipped
  12776. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12777. * be `true`.
  12778. *
  12779. * @type {?Array<Plane>}
  12780. * @default null
  12781. */
  12782. this.clippingPlanes = null;
  12783. /**
  12784. * Changes the behavior of clipping planes so that only their intersection is
  12785. * clipped, rather than their union.
  12786. *
  12787. * @type {boolean}
  12788. * @default false
  12789. */
  12790. this.clipIntersection = false;
  12791. /**
  12792. * Defines whether to clip shadows according to the clipping planes specified
  12793. * on this material.
  12794. *
  12795. * @type {boolean}
  12796. * @default false
  12797. */
  12798. this.clipShadows = false;
  12799. /**
  12800. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12801. * is determined as follows:
  12802. *
  12803. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12804. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12805. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12806. *
  12807. * @type {?(FrontSide|BackSide|DoubleSide)}
  12808. * @default null
  12809. */
  12810. this.shadowSide = null;
  12811. /**
  12812. * Whether to render the material's color.
  12813. *
  12814. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12815. * objects that occlude other objects.
  12816. *
  12817. * @type {boolean}
  12818. * @default true
  12819. */
  12820. this.colorWrite = true;
  12821. /**
  12822. * Override the renderer's default precision for this material.
  12823. *
  12824. * @type {?('highp'|'mediump'|'lowp')}
  12825. * @default null
  12826. */
  12827. this.precision = null;
  12828. /**
  12829. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12830. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12831. * The offset is added before the depth test is performed and before the value is written
  12832. * into the depth buffer.
  12833. *
  12834. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12835. * rendering solids with highlighted edges.
  12836. *
  12837. * @type {boolean}
  12838. * @default false
  12839. */
  12840. this.polygonOffset = false;
  12841. /**
  12842. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12843. *
  12844. * @type {number}
  12845. * @default 0
  12846. */
  12847. this.polygonOffsetFactor = 0;
  12848. /**
  12849. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12850. *
  12851. * @type {number}
  12852. * @default 0
  12853. */
  12854. this.polygonOffsetUnits = 0;
  12855. /**
  12856. * Whether to apply dithering to the color to remove the appearance of banding.
  12857. *
  12858. * @type {boolean}
  12859. * @default false
  12860. */
  12861. this.dithering = false;
  12862. /**
  12863. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12864. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12865. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12866. *
  12867. * @type {boolean}
  12868. * @default false
  12869. */
  12870. this.alphaToCoverage = false;
  12871. /**
  12872. * Whether to premultiply the alpha (transparency) value.
  12873. *
  12874. * @type {boolean}
  12875. * @default false
  12876. */
  12877. this.premultipliedAlpha = false;
  12878. /**
  12879. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12880. *
  12881. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12882. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12883. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12884. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12885. * disable the two pass rendering to avoid performance issues.
  12886. *
  12887. * @type {boolean}
  12888. * @default false
  12889. */
  12890. this.forceSinglePass = false;
  12891. /**
  12892. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12893. *
  12894. * @type {boolean}
  12895. * @default true
  12896. */
  12897. this.allowOverride = true;
  12898. /**
  12899. * Defines whether 3D objects using this material are visible.
  12900. *
  12901. * @type {boolean}
  12902. * @default true
  12903. */
  12904. this.visible = true;
  12905. /**
  12906. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12907. *
  12908. * It is ignored when rendering to a render target or using post processing or when using
  12909. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12910. *
  12911. * @type {boolean}
  12912. * @default true
  12913. */
  12914. this.toneMapped = true;
  12915. /**
  12916. * An object that can be used to store custom data about the Material. It
  12917. * should not hold references to functions as these will not be cloned.
  12918. *
  12919. * @type {Object}
  12920. */
  12921. this.userData = {};
  12922. /**
  12923. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12924. *
  12925. * @type {number}
  12926. * @readonly
  12927. * @default 0
  12928. */
  12929. this.version = 0;
  12930. this._alphaTest = 0;
  12931. }
  12932. /**
  12933. * Sets the alpha value to be used when running an alpha test. The material
  12934. * will not be rendered if the opacity is lower than this value.
  12935. *
  12936. * @type {number}
  12937. * @readonly
  12938. * @default 0
  12939. */
  12940. get alphaTest() {
  12941. return this._alphaTest;
  12942. }
  12943. set alphaTest( value ) {
  12944. if ( this._alphaTest > 0 !== value > 0 ) {
  12945. this.version ++;
  12946. }
  12947. this._alphaTest = value;
  12948. }
  12949. /**
  12950. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12951. *
  12952. * This method can only be used when rendering with {@link WebGLRenderer}.
  12953. *
  12954. * @param {WebGLRenderer} renderer - The renderer.
  12955. * @param {Scene} scene - The scene.
  12956. * @param {Camera} camera - The camera that is used to render the scene.
  12957. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12958. * @param {Object3D} object - The 3D object.
  12959. * @param {Object} group - The geometry group data.
  12960. */
  12961. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12962. /**
  12963. * An optional callback that is executed immediately before the shader
  12964. * program is compiled. This function is called with the shader source code
  12965. * as a parameter. Useful for the modification of built-in materials.
  12966. *
  12967. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12968. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12969. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  12970. *
  12971. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12972. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12973. */
  12974. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12975. /**
  12976. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12977. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12978. * shader or recompile the shader for this material as needed.
  12979. *
  12980. * This method can only be used when rendering with {@link WebGLRenderer}.
  12981. *
  12982. * @return {string} The custom program cache key.
  12983. */
  12984. customProgramCacheKey() {
  12985. return this.onBeforeCompile.toString();
  12986. }
  12987. /**
  12988. * This method can be used to set default values from parameter objects.
  12989. * It is a generic implementation so it can be used with different types
  12990. * of materials.
  12991. *
  12992. * @param {Object} [values] - The material values to set.
  12993. */
  12994. setValues( values ) {
  12995. if ( values === undefined ) return;
  12996. for ( const key in values ) {
  12997. const newValue = values[ key ];
  12998. if ( newValue === undefined ) {
  12999. warn( `Material: parameter '${ key }' has value of undefined.` );
  13000. continue;
  13001. }
  13002. const currentValue = this[ key ];
  13003. if ( currentValue === undefined ) {
  13004. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  13005. continue;
  13006. }
  13007. if ( currentValue && currentValue.isColor ) {
  13008. currentValue.set( newValue );
  13009. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  13010. currentValue.copy( newValue );
  13011. } else {
  13012. this[ key ] = newValue;
  13013. }
  13014. }
  13015. }
  13016. /**
  13017. * Serializes the material into JSON.
  13018. *
  13019. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  13020. * @return {Object} A JSON object representing the serialized material.
  13021. * @see {@link ObjectLoader#parse}
  13022. */
  13023. toJSON( meta ) {
  13024. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  13025. if ( isRootObject ) {
  13026. meta = {
  13027. textures: {},
  13028. images: {}
  13029. };
  13030. }
  13031. const data = {
  13032. metadata: {
  13033. version: 4.7,
  13034. type: 'Material',
  13035. generator: 'Material.toJSON'
  13036. }
  13037. };
  13038. // standard Material serialization
  13039. data.uuid = this.uuid;
  13040. data.type = this.type;
  13041. if ( this.name !== '' ) data.name = this.name;
  13042. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  13043. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  13044. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  13045. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  13046. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  13047. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  13048. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  13049. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  13050. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  13051. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  13052. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  13053. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  13054. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  13055. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  13056. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  13057. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  13058. }
  13059. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  13060. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  13061. }
  13062. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  13063. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  13064. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  13065. }
  13066. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  13067. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  13068. }
  13069. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  13070. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  13071. }
  13072. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  13073. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  13074. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  13075. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  13076. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  13077. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  13078. }
  13079. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  13080. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  13081. }
  13082. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  13083. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  13084. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  13085. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  13086. }
  13087. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  13088. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  13089. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  13090. if ( this.lightMap && this.lightMap.isTexture ) {
  13091. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  13092. data.lightMapIntensity = this.lightMapIntensity;
  13093. }
  13094. if ( this.aoMap && this.aoMap.isTexture ) {
  13095. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  13096. data.aoMapIntensity = this.aoMapIntensity;
  13097. }
  13098. if ( this.bumpMap && this.bumpMap.isTexture ) {
  13099. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  13100. data.bumpScale = this.bumpScale;
  13101. }
  13102. if ( this.normalMap && this.normalMap.isTexture ) {
  13103. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  13104. data.normalMapType = this.normalMapType;
  13105. data.normalScale = this.normalScale.toArray();
  13106. }
  13107. if ( this.displacementMap && this.displacementMap.isTexture ) {
  13108. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  13109. data.displacementScale = this.displacementScale;
  13110. data.displacementBias = this.displacementBias;
  13111. }
  13112. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  13113. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  13114. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  13115. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  13116. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  13117. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  13118. if ( this.envMap && this.envMap.isTexture ) {
  13119. data.envMap = this.envMap.toJSON( meta ).uuid;
  13120. if ( this.combine !== undefined ) data.combine = this.combine;
  13121. }
  13122. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  13123. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  13124. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  13125. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  13126. if ( this.gradientMap && this.gradientMap.isTexture ) {
  13127. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  13128. }
  13129. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  13130. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  13131. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  13132. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  13133. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  13134. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  13135. if ( this.size !== undefined ) data.size = this.size;
  13136. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  13137. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  13138. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  13139. if ( this.side !== FrontSide ) data.side = this.side;
  13140. if ( this.vertexColors === true ) data.vertexColors = true;
  13141. if ( this.opacity < 1 ) data.opacity = this.opacity;
  13142. if ( this.transparent === true ) data.transparent = true;
  13143. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  13144. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  13145. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  13146. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  13147. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  13148. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  13149. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  13150. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  13151. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  13152. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  13153. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  13154. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  13155. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  13156. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  13157. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  13158. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  13159. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  13160. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  13161. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  13162. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  13163. // rotation (SpriteMaterial)
  13164. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  13165. if ( this.polygonOffset === true ) data.polygonOffset = true;
  13166. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  13167. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  13168. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  13169. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  13170. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  13171. if ( this.scale !== undefined ) data.scale = this.scale;
  13172. if ( this.dithering === true ) data.dithering = true;
  13173. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  13174. if ( this.alphaHash === true ) data.alphaHash = true;
  13175. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  13176. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  13177. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  13178. if ( this.allowOverride === false ) data.allowOverride = false;
  13179. if ( this.wireframe === true ) data.wireframe = true;
  13180. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  13181. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  13182. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  13183. if ( this.flatShading === true ) data.flatShading = true;
  13184. if ( this.visible === false ) data.visible = false;
  13185. if ( this.toneMapped === false ) data.toneMapped = false;
  13186. if ( this.fog === false ) data.fog = false;
  13187. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  13188. // TODO: Copied from Object3D.toJSON
  13189. function extractFromCache( cache ) {
  13190. const values = [];
  13191. for ( const key in cache ) {
  13192. const data = cache[ key ];
  13193. delete data.metadata;
  13194. values.push( data );
  13195. }
  13196. return values;
  13197. }
  13198. if ( isRootObject ) {
  13199. const textures = extractFromCache( meta.textures );
  13200. const images = extractFromCache( meta.images );
  13201. if ( textures.length > 0 ) data.textures = textures;
  13202. if ( images.length > 0 ) data.images = images;
  13203. }
  13204. return data;
  13205. }
  13206. /**
  13207. * Returns a new material with copied values from this instance.
  13208. *
  13209. * @return {Material} A clone of this instance.
  13210. */
  13211. clone() {
  13212. return new this.constructor().copy( this );
  13213. }
  13214. /**
  13215. * Copies the values of the given material to this instance.
  13216. *
  13217. * @param {Material} source - The material to copy.
  13218. * @return {Material} A reference to this instance.
  13219. */
  13220. copy( source ) {
  13221. this.name = source.name;
  13222. this.blending = source.blending;
  13223. this.side = source.side;
  13224. this.vertexColors = source.vertexColors;
  13225. this.opacity = source.opacity;
  13226. this.transparent = source.transparent;
  13227. this.blendSrc = source.blendSrc;
  13228. this.blendDst = source.blendDst;
  13229. this.blendEquation = source.blendEquation;
  13230. this.blendSrcAlpha = source.blendSrcAlpha;
  13231. this.blendDstAlpha = source.blendDstAlpha;
  13232. this.blendEquationAlpha = source.blendEquationAlpha;
  13233. this.blendColor.copy( source.blendColor );
  13234. this.blendAlpha = source.blendAlpha;
  13235. this.depthFunc = source.depthFunc;
  13236. this.depthTest = source.depthTest;
  13237. this.depthWrite = source.depthWrite;
  13238. this.stencilWriteMask = source.stencilWriteMask;
  13239. this.stencilFunc = source.stencilFunc;
  13240. this.stencilRef = source.stencilRef;
  13241. this.stencilFuncMask = source.stencilFuncMask;
  13242. this.stencilFail = source.stencilFail;
  13243. this.stencilZFail = source.stencilZFail;
  13244. this.stencilZPass = source.stencilZPass;
  13245. this.stencilWrite = source.stencilWrite;
  13246. const srcPlanes = source.clippingPlanes;
  13247. let dstPlanes = null;
  13248. if ( srcPlanes !== null ) {
  13249. const n = srcPlanes.length;
  13250. dstPlanes = new Array( n );
  13251. for ( let i = 0; i !== n; ++ i ) {
  13252. dstPlanes[ i ] = srcPlanes[ i ].clone();
  13253. }
  13254. }
  13255. this.clippingPlanes = dstPlanes;
  13256. this.clipIntersection = source.clipIntersection;
  13257. this.clipShadows = source.clipShadows;
  13258. this.shadowSide = source.shadowSide;
  13259. this.colorWrite = source.colorWrite;
  13260. this.precision = source.precision;
  13261. this.polygonOffset = source.polygonOffset;
  13262. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13263. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13264. this.dithering = source.dithering;
  13265. this.alphaTest = source.alphaTest;
  13266. this.alphaHash = source.alphaHash;
  13267. this.alphaToCoverage = source.alphaToCoverage;
  13268. this.premultipliedAlpha = source.premultipliedAlpha;
  13269. this.forceSinglePass = source.forceSinglePass;
  13270. this.allowOverride = source.allowOverride;
  13271. this.visible = source.visible;
  13272. this.toneMapped = source.toneMapped;
  13273. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13274. return this;
  13275. }
  13276. /**
  13277. * Frees the GPU-related resources allocated by this instance. Call this
  13278. * method whenever this instance is no longer used in your app.
  13279. *
  13280. * @fires Material#dispose
  13281. */
  13282. dispose() {
  13283. /**
  13284. * Fires when the material has been disposed of.
  13285. *
  13286. * @event Material#dispose
  13287. * @type {Object}
  13288. */
  13289. this.dispatchEvent( { type: 'dispose' } );
  13290. }
  13291. /**
  13292. * Setting this property to `true` indicates the engine the material
  13293. * needs to be recompiled.
  13294. *
  13295. * @type {boolean}
  13296. * @default false
  13297. * @param {boolean} value
  13298. */
  13299. set needsUpdate( value ) {
  13300. if ( value === true ) this.version ++;
  13301. }
  13302. }
  13303. /**
  13304. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13305. *
  13306. * This material is not affected by lights.
  13307. *
  13308. * @augments Material
  13309. * @demo scenes/material-browser.html#MeshBasicMaterial
  13310. */
  13311. class MeshBasicMaterial extends Material {
  13312. /**
  13313. * Constructs a new mesh basic material.
  13314. *
  13315. * @param {Object} [parameters] - An object with one or more properties
  13316. * defining the material's appearance. Any property of the material
  13317. * (including any property from inherited materials) can be passed
  13318. * in here. Color values can be passed any type of value accepted
  13319. * by {@link Color#set}.
  13320. */
  13321. constructor( parameters ) {
  13322. super();
  13323. /**
  13324. * This flag can be used for type testing.
  13325. *
  13326. * @type {boolean}
  13327. * @readonly
  13328. * @default true
  13329. */
  13330. this.isMeshBasicMaterial = true;
  13331. this.type = 'MeshBasicMaterial';
  13332. /**
  13333. * Color of the material.
  13334. *
  13335. * @type {Color}
  13336. * @default (1,1,1)
  13337. */
  13338. this.color = new Color( 0xffffff ); // diffuse
  13339. /**
  13340. * The color map. May optionally include an alpha channel, typically combined
  13341. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13342. * color is modulated by the diffuse `color`.
  13343. *
  13344. * @type {?Texture}
  13345. * @default null
  13346. */
  13347. this.map = null;
  13348. /**
  13349. * The light map. Requires a second set of UVs.
  13350. *
  13351. * @type {?Texture}
  13352. * @default null
  13353. */
  13354. this.lightMap = null;
  13355. /**
  13356. * Intensity of the baked light.
  13357. *
  13358. * @type {number}
  13359. * @default 1
  13360. */
  13361. this.lightMapIntensity = 1.0;
  13362. /**
  13363. * The red channel of this texture is used as the ambient occlusion map.
  13364. * Requires a second set of UVs.
  13365. *
  13366. * @type {?Texture}
  13367. * @default null
  13368. */
  13369. this.aoMap = null;
  13370. /**
  13371. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13372. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13373. * red channel is also `1`, ambient light is fully occluded on a surface.
  13374. *
  13375. * @type {number}
  13376. * @default 1
  13377. */
  13378. this.aoMapIntensity = 1.0;
  13379. /**
  13380. * Specular map used by the material.
  13381. *
  13382. * @type {?Texture}
  13383. * @default null
  13384. */
  13385. this.specularMap = null;
  13386. /**
  13387. * The alpha map is a grayscale texture that controls the opacity across the
  13388. * surface (black: fully transparent; white: fully opaque).
  13389. *
  13390. * Only the color of the texture is used, ignoring the alpha channel if one
  13391. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13392. * when sampling this texture due to the extra bit of precision provided for
  13393. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13394. * luminance/alpha textures will also still work as expected.
  13395. *
  13396. * @type {?Texture}
  13397. * @default null
  13398. */
  13399. this.alphaMap = null;
  13400. /**
  13401. * The environment map.
  13402. *
  13403. * @type {?Texture}
  13404. * @default null
  13405. */
  13406. this.envMap = null;
  13407. /**
  13408. * The rotation of the environment map in radians.
  13409. *
  13410. * @type {Euler}
  13411. * @default (0,0,0)
  13412. */
  13413. this.envMapRotation = new Euler();
  13414. /**
  13415. * How to combine the result of the surface's color with the environment map, if any.
  13416. *
  13417. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13418. * blend between the two colors.
  13419. *
  13420. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13421. * @default MultiplyOperation
  13422. */
  13423. this.combine = MultiplyOperation;
  13424. /**
  13425. * How much the environment map affects the surface.
  13426. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13427. *
  13428. * @type {number}
  13429. * @default 1
  13430. */
  13431. this.reflectivity = 1;
  13432. /**
  13433. * The index of refraction (IOR) of air (approximately 1) divided by the
  13434. * index of refraction of the material. It is used with environment mapping
  13435. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13436. * The refraction ratio should not exceed `1`.
  13437. *
  13438. * @type {number}
  13439. * @default 0.98
  13440. */
  13441. this.refractionRatio = 0.98;
  13442. /**
  13443. * Renders the geometry as a wireframe.
  13444. *
  13445. * @type {boolean}
  13446. * @default false
  13447. */
  13448. this.wireframe = false;
  13449. /**
  13450. * Controls the thickness of the wireframe.
  13451. *
  13452. * Can only be used with {@link SVGRenderer}.
  13453. *
  13454. * @type {number}
  13455. * @default 1
  13456. */
  13457. this.wireframeLinewidth = 1;
  13458. /**
  13459. * Defines appearance of wireframe ends.
  13460. *
  13461. * Can only be used with {@link SVGRenderer}.
  13462. *
  13463. * @type {('round'|'bevel'|'miter')}
  13464. * @default 'round'
  13465. */
  13466. this.wireframeLinecap = 'round';
  13467. /**
  13468. * Defines appearance of wireframe joints.
  13469. *
  13470. * Can only be used with {@link SVGRenderer}.
  13471. *
  13472. * @type {('round'|'bevel'|'miter')}
  13473. * @default 'round'
  13474. */
  13475. this.wireframeLinejoin = 'round';
  13476. /**
  13477. * Whether the material is affected by fog or not.
  13478. *
  13479. * @type {boolean}
  13480. * @default true
  13481. */
  13482. this.fog = true;
  13483. this.setValues( parameters );
  13484. }
  13485. copy( source ) {
  13486. super.copy( source );
  13487. this.color.copy( source.color );
  13488. this.map = source.map;
  13489. this.lightMap = source.lightMap;
  13490. this.lightMapIntensity = source.lightMapIntensity;
  13491. this.aoMap = source.aoMap;
  13492. this.aoMapIntensity = source.aoMapIntensity;
  13493. this.specularMap = source.specularMap;
  13494. this.alphaMap = source.alphaMap;
  13495. this.envMap = source.envMap;
  13496. this.envMapRotation.copy( source.envMapRotation );
  13497. this.combine = source.combine;
  13498. this.reflectivity = source.reflectivity;
  13499. this.refractionRatio = source.refractionRatio;
  13500. this.wireframe = source.wireframe;
  13501. this.wireframeLinewidth = source.wireframeLinewidth;
  13502. this.wireframeLinecap = source.wireframeLinecap;
  13503. this.wireframeLinejoin = source.wireframeLinejoin;
  13504. this.fog = source.fog;
  13505. return this;
  13506. }
  13507. }
  13508. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13509. const _tables = /*@__PURE__*/ _generateTables();
  13510. function _generateTables() {
  13511. // float32 to float16 helpers
  13512. const buffer = new ArrayBuffer( 4 );
  13513. const floatView = new Float32Array( buffer );
  13514. const uint32View = new Uint32Array( buffer );
  13515. const baseTable = new Uint32Array( 512 );
  13516. const shiftTable = new Uint32Array( 512 );
  13517. for ( let i = 0; i < 256; ++ i ) {
  13518. const e = i - 127;
  13519. // very small number (0, -0)
  13520. if ( e < -27 ) {
  13521. baseTable[ i ] = 0x0000;
  13522. baseTable[ i | 0x100 ] = 0x8000;
  13523. shiftTable[ i ] = 24;
  13524. shiftTable[ i | 0x100 ] = 24;
  13525. // small number (denorm)
  13526. } else if ( e < -14 ) {
  13527. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13528. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13529. shiftTable[ i ] = - e - 1;
  13530. shiftTable[ i | 0x100 ] = - e - 1;
  13531. // normal number
  13532. } else if ( e <= 15 ) {
  13533. baseTable[ i ] = ( e + 15 ) << 10;
  13534. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13535. shiftTable[ i ] = 13;
  13536. shiftTable[ i | 0x100 ] = 13;
  13537. // large number (Infinity, -Infinity)
  13538. } else if ( e < 128 ) {
  13539. baseTable[ i ] = 0x7c00;
  13540. baseTable[ i | 0x100 ] = 0xfc00;
  13541. shiftTable[ i ] = 24;
  13542. shiftTable[ i | 0x100 ] = 24;
  13543. // stay (NaN, Infinity, -Infinity)
  13544. } else {
  13545. baseTable[ i ] = 0x7c00;
  13546. baseTable[ i | 0x100 ] = 0xfc00;
  13547. shiftTable[ i ] = 13;
  13548. shiftTable[ i | 0x100 ] = 13;
  13549. }
  13550. }
  13551. // float16 to float32 helpers
  13552. const mantissaTable = new Uint32Array( 2048 );
  13553. const exponentTable = new Uint32Array( 64 );
  13554. const offsetTable = new Uint32Array( 64 );
  13555. for ( let i = 1; i < 1024; ++ i ) {
  13556. let m = i << 13; // zero pad mantissa bits
  13557. let e = 0; // zero exponent
  13558. // normalized
  13559. while ( ( m & 0x00800000 ) === 0 ) {
  13560. m <<= 1;
  13561. e -= 0x00800000; // decrement exponent
  13562. }
  13563. m &= -8388609; // clear leading 1 bit
  13564. e += 0x38800000; // adjust bias
  13565. mantissaTable[ i ] = m | e;
  13566. }
  13567. for ( let i = 1024; i < 2048; ++ i ) {
  13568. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13569. }
  13570. for ( let i = 1; i < 31; ++ i ) {
  13571. exponentTable[ i ] = i << 23;
  13572. }
  13573. exponentTable[ 31 ] = 0x47800000;
  13574. exponentTable[ 32 ] = 0x80000000;
  13575. for ( let i = 33; i < 63; ++ i ) {
  13576. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13577. }
  13578. exponentTable[ 63 ] = 0xc7800000;
  13579. for ( let i = 1; i < 64; ++ i ) {
  13580. if ( i !== 32 ) {
  13581. offsetTable[ i ] = 1024;
  13582. }
  13583. }
  13584. return {
  13585. floatView: floatView,
  13586. uint32View: uint32View,
  13587. baseTable: baseTable,
  13588. shiftTable: shiftTable,
  13589. mantissaTable: mantissaTable,
  13590. exponentTable: exponentTable,
  13591. offsetTable: offsetTable
  13592. };
  13593. }
  13594. /**
  13595. * Returns a half precision floating point value (FP16) from the given single
  13596. * precision floating point value (FP32).
  13597. *
  13598. * @param {number} val - A single precision floating point value.
  13599. * @return {number} The FP16 value.
  13600. */
  13601. function toHalfFloat( val ) {
  13602. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  13603. val = clamp( val, -65504, 65504 );
  13604. _tables.floatView[ 0 ] = val;
  13605. const f = _tables.uint32View[ 0 ];
  13606. const e = ( f >> 23 ) & 0x1ff;
  13607. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13608. }
  13609. /**
  13610. * Returns a single precision floating point value (FP32) from the given half
  13611. * precision floating point value (FP16).
  13612. *
  13613. * @param {number} val - A half precision floating point value.
  13614. * @return {number} The FP32 value.
  13615. */
  13616. function fromHalfFloat( val ) {
  13617. const m = val >> 10;
  13618. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13619. return _tables.floatView[ 0 ];
  13620. }
  13621. /**
  13622. * A class containing utility functions for data.
  13623. *
  13624. * @hideconstructor
  13625. */
  13626. class DataUtils {
  13627. /**
  13628. * Returns a half precision floating point value (FP16) from the given single
  13629. * precision floating point value (FP32).
  13630. *
  13631. * @param {number} val - A single precision floating point value.
  13632. * @return {number} The FP16 value.
  13633. */
  13634. static toHalfFloat( val ) {
  13635. return toHalfFloat( val );
  13636. }
  13637. /**
  13638. * Returns a single precision floating point value (FP32) from the given half
  13639. * precision floating point value (FP16).
  13640. *
  13641. * @param {number} val - A half precision floating point value.
  13642. * @return {number} The FP32 value.
  13643. */
  13644. static fromHalfFloat( val ) {
  13645. return fromHalfFloat( val );
  13646. }
  13647. }
  13648. const _vector$9 = /*@__PURE__*/ new Vector3();
  13649. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13650. let _id$2 = 0;
  13651. /**
  13652. * This class stores data for an attribute (such as vertex positions, face
  13653. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13654. * a geometry, which allows for more efficient passing of data to the GPU.
  13655. *
  13656. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13657. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13658. */
  13659. class BufferAttribute {
  13660. /**
  13661. * Constructs a new buffer attribute.
  13662. *
  13663. * @param {TypedArray} array - The array holding the attribute data.
  13664. * @param {number} itemSize - The item size.
  13665. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13666. */
  13667. constructor( array, itemSize, normalized = false ) {
  13668. if ( Array.isArray( array ) ) {
  13669. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13670. }
  13671. /**
  13672. * This flag can be used for type testing.
  13673. *
  13674. * @type {boolean}
  13675. * @readonly
  13676. * @default true
  13677. */
  13678. this.isBufferAttribute = true;
  13679. /**
  13680. * The ID of the buffer attribute.
  13681. *
  13682. * @name BufferAttribute#id
  13683. * @type {number}
  13684. * @readonly
  13685. */
  13686. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  13687. /**
  13688. * The name of the buffer attribute.
  13689. *
  13690. * @type {string}
  13691. */
  13692. this.name = '';
  13693. /**
  13694. * The array holding the attribute data. It should have `itemSize * numVertices`
  13695. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13696. *
  13697. * @type {TypedArray}
  13698. */
  13699. this.array = array;
  13700. /**
  13701. * The number of values of the array that should be associated with a particular vertex.
  13702. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13703. * normal, or color), then the value should be `3`.
  13704. *
  13705. * @type {number}
  13706. */
  13707. this.itemSize = itemSize;
  13708. /**
  13709. * Represents the number of items this buffer attribute stores. It is internally computed
  13710. * by dividing the `array` length by the `itemSize`.
  13711. *
  13712. * @type {number}
  13713. * @readonly
  13714. */
  13715. this.count = array !== undefined ? array.length / itemSize : 0;
  13716. /**
  13717. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13718. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13719. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13720. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13721. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13722. *
  13723. * @type {boolean}
  13724. */
  13725. this.normalized = normalized;
  13726. /**
  13727. * Defines the intended usage pattern of the data store for optimization purposes.
  13728. *
  13729. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13730. * instantiate a new one and set the desired usage before the next render.
  13731. *
  13732. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13733. * @default StaticDrawUsage
  13734. */
  13735. this.usage = StaticDrawUsage;
  13736. /**
  13737. * This can be used to only update some components of stored vectors (for example, just the
  13738. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13739. *
  13740. * @type {Array<Object>}
  13741. */
  13742. this.updateRanges = [];
  13743. /**
  13744. * Configures the bound GPU type for use in shaders.
  13745. *
  13746. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13747. * For lower precision float types, use `Float16BufferAttribute`.
  13748. *
  13749. * @type {(FloatType|IntType)}
  13750. * @default FloatType
  13751. */
  13752. this.gpuType = FloatType;
  13753. /**
  13754. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13755. *
  13756. * @type {number}
  13757. */
  13758. this.version = 0;
  13759. }
  13760. /**
  13761. * A callback function that is executed after the renderer has transferred the attribute
  13762. * array data to the GPU.
  13763. */
  13764. onUploadCallback() {}
  13765. /**
  13766. * Flag to indicate that this attribute has changed and should be re-sent to
  13767. * the GPU. Set this to `true` when you modify the value of the array.
  13768. *
  13769. * @type {number}
  13770. * @default false
  13771. * @param {boolean} value
  13772. */
  13773. set needsUpdate( value ) {
  13774. if ( value === true ) this.version ++;
  13775. }
  13776. /**
  13777. * Sets the usage of this buffer attribute.
  13778. *
  13779. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13780. * @return {BufferAttribute} A reference to this buffer attribute.
  13781. */
  13782. setUsage( value ) {
  13783. this.usage = value;
  13784. return this;
  13785. }
  13786. /**
  13787. * Adds a range of data in the data array to be updated on the GPU.
  13788. *
  13789. * @param {number} start - Position at which to start update.
  13790. * @param {number} count - The number of components to update.
  13791. */
  13792. addUpdateRange( start, count ) {
  13793. this.updateRanges.push( { start, count } );
  13794. }
  13795. /**
  13796. * Clears the update ranges.
  13797. */
  13798. clearUpdateRanges() {
  13799. this.updateRanges.length = 0;
  13800. }
  13801. /**
  13802. * Copies the values of the given buffer attribute to this instance.
  13803. *
  13804. * @param {BufferAttribute} source - The buffer attribute to copy.
  13805. * @return {BufferAttribute} A reference to this instance.
  13806. */
  13807. copy( source ) {
  13808. this.name = source.name;
  13809. this.array = new source.array.constructor( source.array );
  13810. this.itemSize = source.itemSize;
  13811. this.count = source.count;
  13812. this.normalized = source.normalized;
  13813. this.usage = source.usage;
  13814. this.gpuType = source.gpuType;
  13815. return this;
  13816. }
  13817. /**
  13818. * Copies a vector from the given buffer attribute to this one. The start
  13819. * and destination position in the attribute buffers are represented by the
  13820. * given indices.
  13821. *
  13822. * @param {number} index1 - The destination index into this buffer attribute.
  13823. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13824. * @param {number} index2 - The source index into the given buffer attribute.
  13825. * @return {BufferAttribute} A reference to this instance.
  13826. */
  13827. copyAt( index1, attribute, index2 ) {
  13828. index1 *= this.itemSize;
  13829. index2 *= attribute.itemSize;
  13830. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13831. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13832. }
  13833. return this;
  13834. }
  13835. /**
  13836. * Copies the given array data into this buffer attribute.
  13837. *
  13838. * @param {(TypedArray|Array)} array - The array to copy.
  13839. * @return {BufferAttribute} A reference to this instance.
  13840. */
  13841. copyArray( array ) {
  13842. this.array.set( array );
  13843. return this;
  13844. }
  13845. /**
  13846. * Applies the given 3x3 matrix to the given attribute. Works with
  13847. * item size `2` and `3`.
  13848. *
  13849. * @param {Matrix3} m - The matrix to apply.
  13850. * @return {BufferAttribute} A reference to this instance.
  13851. */
  13852. applyMatrix3( m ) {
  13853. if ( this.itemSize === 2 ) {
  13854. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13855. _vector2$1.fromBufferAttribute( this, i );
  13856. _vector2$1.applyMatrix3( m );
  13857. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13858. }
  13859. } else if ( this.itemSize === 3 ) {
  13860. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13861. _vector$9.fromBufferAttribute( this, i );
  13862. _vector$9.applyMatrix3( m );
  13863. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13864. }
  13865. }
  13866. return this;
  13867. }
  13868. /**
  13869. * Applies the given 4x4 matrix to the given attribute. Only works with
  13870. * item size `3`.
  13871. *
  13872. * @param {Matrix4} m - The matrix to apply.
  13873. * @return {BufferAttribute} A reference to this instance.
  13874. */
  13875. applyMatrix4( m ) {
  13876. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13877. _vector$9.fromBufferAttribute( this, i );
  13878. _vector$9.applyMatrix4( m );
  13879. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13880. }
  13881. return this;
  13882. }
  13883. /**
  13884. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13885. * item size `3`.
  13886. *
  13887. * @param {Matrix3} m - The normal matrix to apply.
  13888. * @return {BufferAttribute} A reference to this instance.
  13889. */
  13890. applyNormalMatrix( m ) {
  13891. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13892. _vector$9.fromBufferAttribute( this, i );
  13893. _vector$9.applyNormalMatrix( m );
  13894. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13895. }
  13896. return this;
  13897. }
  13898. /**
  13899. * Applies the given 4x4 matrix to the given attribute. Only works with
  13900. * item size `3` and with direction vectors.
  13901. *
  13902. * @param {Matrix4} m - The matrix to apply.
  13903. * @return {BufferAttribute} A reference to this instance.
  13904. */
  13905. transformDirection( m ) {
  13906. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13907. _vector$9.fromBufferAttribute( this, i );
  13908. _vector$9.transformDirection( m );
  13909. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13910. }
  13911. return this;
  13912. }
  13913. /**
  13914. * Sets the given array data in the buffer attribute.
  13915. *
  13916. * @param {(TypedArray|Array)} value - The array data to set.
  13917. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13918. * @return {BufferAttribute} A reference to this instance.
  13919. */
  13920. set( value, offset = 0 ) {
  13921. // Matching BufferAttribute constructor, do not normalize the array.
  13922. this.array.set( value, offset );
  13923. return this;
  13924. }
  13925. /**
  13926. * Returns the given component of the vector at the given index.
  13927. *
  13928. * @param {number} index - The index into the buffer attribute.
  13929. * @param {number} component - The component index.
  13930. * @return {number} The returned value.
  13931. */
  13932. getComponent( index, component ) {
  13933. let value = this.array[ index * this.itemSize + component ];
  13934. if ( this.normalized ) value = denormalize( value, this.array );
  13935. return value;
  13936. }
  13937. /**
  13938. * Sets the given value to the given component of the vector at the given index.
  13939. *
  13940. * @param {number} index - The index into the buffer attribute.
  13941. * @param {number} component - The component index.
  13942. * @param {number} value - The value to set.
  13943. * @return {BufferAttribute} A reference to this instance.
  13944. */
  13945. setComponent( index, component, value ) {
  13946. if ( this.normalized ) value = normalize( value, this.array );
  13947. this.array[ index * this.itemSize + component ] = value;
  13948. return this;
  13949. }
  13950. /**
  13951. * Returns the x component of the vector at the given index.
  13952. *
  13953. * @param {number} index - The index into the buffer attribute.
  13954. * @return {number} The x component.
  13955. */
  13956. getX( index ) {
  13957. let x = this.array[ index * this.itemSize ];
  13958. if ( this.normalized ) x = denormalize( x, this.array );
  13959. return x;
  13960. }
  13961. /**
  13962. * Sets the x component of the vector at the given index.
  13963. *
  13964. * @param {number} index - The index into the buffer attribute.
  13965. * @param {number} x - The value to set.
  13966. * @return {BufferAttribute} A reference to this instance.
  13967. */
  13968. setX( index, x ) {
  13969. if ( this.normalized ) x = normalize( x, this.array );
  13970. this.array[ index * this.itemSize ] = x;
  13971. return this;
  13972. }
  13973. /**
  13974. * Returns the y component of the vector at the given index.
  13975. *
  13976. * @param {number} index - The index into the buffer attribute.
  13977. * @return {number} The y component.
  13978. */
  13979. getY( index ) {
  13980. let y = this.array[ index * this.itemSize + 1 ];
  13981. if ( this.normalized ) y = denormalize( y, this.array );
  13982. return y;
  13983. }
  13984. /**
  13985. * Sets the y component of the vector at the given index.
  13986. *
  13987. * @param {number} index - The index into the buffer attribute.
  13988. * @param {number} y - The value to set.
  13989. * @return {BufferAttribute} A reference to this instance.
  13990. */
  13991. setY( index, y ) {
  13992. if ( this.normalized ) y = normalize( y, this.array );
  13993. this.array[ index * this.itemSize + 1 ] = y;
  13994. return this;
  13995. }
  13996. /**
  13997. * Returns the z component of the vector at the given index.
  13998. *
  13999. * @param {number} index - The index into the buffer attribute.
  14000. * @return {number} The z component.
  14001. */
  14002. getZ( index ) {
  14003. let z = this.array[ index * this.itemSize + 2 ];
  14004. if ( this.normalized ) z = denormalize( z, this.array );
  14005. return z;
  14006. }
  14007. /**
  14008. * Sets the z component of the vector at the given index.
  14009. *
  14010. * @param {number} index - The index into the buffer attribute.
  14011. * @param {number} z - The value to set.
  14012. * @return {BufferAttribute} A reference to this instance.
  14013. */
  14014. setZ( index, z ) {
  14015. if ( this.normalized ) z = normalize( z, this.array );
  14016. this.array[ index * this.itemSize + 2 ] = z;
  14017. return this;
  14018. }
  14019. /**
  14020. * Returns the w component of the vector at the given index.
  14021. *
  14022. * @param {number} index - The index into the buffer attribute.
  14023. * @return {number} The w component.
  14024. */
  14025. getW( index ) {
  14026. let w = this.array[ index * this.itemSize + 3 ];
  14027. if ( this.normalized ) w = denormalize( w, this.array );
  14028. return w;
  14029. }
  14030. /**
  14031. * Sets the w component of the vector at the given index.
  14032. *
  14033. * @param {number} index - The index into the buffer attribute.
  14034. * @param {number} w - The value to set.
  14035. * @return {BufferAttribute} A reference to this instance.
  14036. */
  14037. setW( index, w ) {
  14038. if ( this.normalized ) w = normalize( w, this.array );
  14039. this.array[ index * this.itemSize + 3 ] = w;
  14040. return this;
  14041. }
  14042. /**
  14043. * Sets the x and y component of the vector at the given index.
  14044. *
  14045. * @param {number} index - The index into the buffer attribute.
  14046. * @param {number} x - The value for the x component to set.
  14047. * @param {number} y - The value for the y component to set.
  14048. * @return {BufferAttribute} A reference to this instance.
  14049. */
  14050. setXY( index, x, y ) {
  14051. index *= this.itemSize;
  14052. if ( this.normalized ) {
  14053. x = normalize( x, this.array );
  14054. y = normalize( y, this.array );
  14055. }
  14056. this.array[ index + 0 ] = x;
  14057. this.array[ index + 1 ] = y;
  14058. return this;
  14059. }
  14060. /**
  14061. * Sets the x, y and z component of the vector at the given index.
  14062. *
  14063. * @param {number} index - The index into the buffer attribute.
  14064. * @param {number} x - The value for the x component to set.
  14065. * @param {number} y - The value for the y component to set.
  14066. * @param {number} z - The value for the z component to set.
  14067. * @return {BufferAttribute} A reference to this instance.
  14068. */
  14069. setXYZ( index, x, y, z ) {
  14070. index *= this.itemSize;
  14071. if ( this.normalized ) {
  14072. x = normalize( x, this.array );
  14073. y = normalize( y, this.array );
  14074. z = normalize( z, this.array );
  14075. }
  14076. this.array[ index + 0 ] = x;
  14077. this.array[ index + 1 ] = y;
  14078. this.array[ index + 2 ] = z;
  14079. return this;
  14080. }
  14081. /**
  14082. * Sets the x, y, z and w component of the vector at the given index.
  14083. *
  14084. * @param {number} index - The index into the buffer attribute.
  14085. * @param {number} x - The value for the x component to set.
  14086. * @param {number} y - The value for the y component to set.
  14087. * @param {number} z - The value for the z component to set.
  14088. * @param {number} w - The value for the w component to set.
  14089. * @return {BufferAttribute} A reference to this instance.
  14090. */
  14091. setXYZW( index, x, y, z, w ) {
  14092. index *= this.itemSize;
  14093. if ( this.normalized ) {
  14094. x = normalize( x, this.array );
  14095. y = normalize( y, this.array );
  14096. z = normalize( z, this.array );
  14097. w = normalize( w, this.array );
  14098. }
  14099. this.array[ index + 0 ] = x;
  14100. this.array[ index + 1 ] = y;
  14101. this.array[ index + 2 ] = z;
  14102. this.array[ index + 3 ] = w;
  14103. return this;
  14104. }
  14105. /**
  14106. * Sets the given callback function that is executed after the Renderer has transferred
  14107. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  14108. * the upload when attribute data are not needed anymore on the CPU side.
  14109. *
  14110. * @param {Function} callback - The `onUpload()` callback.
  14111. * @return {BufferAttribute} A reference to this instance.
  14112. */
  14113. onUpload( callback ) {
  14114. this.onUploadCallback = callback;
  14115. return this;
  14116. }
  14117. /**
  14118. * Returns a new buffer attribute with copied values from this instance.
  14119. *
  14120. * @return {BufferAttribute} A clone of this instance.
  14121. */
  14122. clone() {
  14123. return new this.constructor( this.array, this.itemSize ).copy( this );
  14124. }
  14125. /**
  14126. * Serializes the buffer attribute into JSON.
  14127. *
  14128. * @return {Object} A JSON object representing the serialized buffer attribute.
  14129. */
  14130. toJSON() {
  14131. const data = {
  14132. itemSize: this.itemSize,
  14133. type: this.array.constructor.name,
  14134. array: Array.from( this.array ),
  14135. normalized: this.normalized
  14136. };
  14137. if ( this.name !== '' ) data.name = this.name;
  14138. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  14139. return data;
  14140. }
  14141. }
  14142. /**
  14143. * Convenient class that can be used when creating a `Int8` buffer attribute with
  14144. * a plain `Array` instance.
  14145. *
  14146. * @augments BufferAttribute
  14147. */
  14148. class Int8BufferAttribute extends BufferAttribute {
  14149. /**
  14150. * Constructs a new buffer attribute.
  14151. *
  14152. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  14153. * @param {number} itemSize - The item size.
  14154. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14155. */
  14156. constructor( array, itemSize, normalized ) {
  14157. super( new Int8Array( array ), itemSize, normalized );
  14158. }
  14159. }
  14160. /**
  14161. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  14162. * a plain `Array` instance.
  14163. *
  14164. * @augments BufferAttribute
  14165. */
  14166. class Uint8BufferAttribute extends BufferAttribute {
  14167. /**
  14168. * Constructs a new buffer attribute.
  14169. *
  14170. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  14171. * @param {number} itemSize - The item size.
  14172. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14173. */
  14174. constructor( array, itemSize, normalized ) {
  14175. super( new Uint8Array( array ), itemSize, normalized );
  14176. }
  14177. }
  14178. /**
  14179. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  14180. * a plain `Array` instance.
  14181. *
  14182. * @augments BufferAttribute
  14183. */
  14184. class Uint8ClampedBufferAttribute extends BufferAttribute {
  14185. /**
  14186. * Constructs a new buffer attribute.
  14187. *
  14188. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  14189. * @param {number} itemSize - The item size.
  14190. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14191. */
  14192. constructor( array, itemSize, normalized ) {
  14193. super( new Uint8ClampedArray( array ), itemSize, normalized );
  14194. }
  14195. }
  14196. /**
  14197. * Convenient class that can be used when creating a `Int16` buffer attribute with
  14198. * a plain `Array` instance.
  14199. *
  14200. * @augments BufferAttribute
  14201. */
  14202. class Int16BufferAttribute extends BufferAttribute {
  14203. /**
  14204. * Constructs a new buffer attribute.
  14205. *
  14206. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  14207. * @param {number} itemSize - The item size.
  14208. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14209. */
  14210. constructor( array, itemSize, normalized ) {
  14211. super( new Int16Array( array ), itemSize, normalized );
  14212. }
  14213. }
  14214. /**
  14215. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  14216. * a plain `Array` instance.
  14217. *
  14218. * @augments BufferAttribute
  14219. */
  14220. class Uint16BufferAttribute extends BufferAttribute {
  14221. /**
  14222. * Constructs a new buffer attribute.
  14223. *
  14224. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14225. * @param {number} itemSize - The item size.
  14226. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14227. */
  14228. constructor( array, itemSize, normalized ) {
  14229. super( new Uint16Array( array ), itemSize, normalized );
  14230. }
  14231. }
  14232. /**
  14233. * Convenient class that can be used when creating a `Int32` buffer attribute with
  14234. * a plain `Array` instance.
  14235. *
  14236. * @augments BufferAttribute
  14237. */
  14238. class Int32BufferAttribute extends BufferAttribute {
  14239. /**
  14240. * Constructs a new buffer attribute.
  14241. *
  14242. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  14243. * @param {number} itemSize - The item size.
  14244. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14245. */
  14246. constructor( array, itemSize, normalized ) {
  14247. super( new Int32Array( array ), itemSize, normalized );
  14248. }
  14249. }
  14250. /**
  14251. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  14252. * a plain `Array` instance.
  14253. *
  14254. * @augments BufferAttribute
  14255. */
  14256. class Uint32BufferAttribute extends BufferAttribute {
  14257. /**
  14258. * Constructs a new buffer attribute.
  14259. *
  14260. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14261. * @param {number} itemSize - The item size.
  14262. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14263. */
  14264. constructor( array, itemSize, normalized ) {
  14265. super( new Uint32Array( array ), itemSize, normalized );
  14266. }
  14267. }
  14268. /**
  14269. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14270. * a plain `Array` instance.
  14271. *
  14272. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14273. * browser support is still problematic.
  14274. *
  14275. * @augments BufferAttribute
  14276. */
  14277. class Float16BufferAttribute extends BufferAttribute {
  14278. /**
  14279. * Constructs a new buffer attribute.
  14280. *
  14281. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14282. * @param {number} itemSize - The item size.
  14283. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14284. */
  14285. constructor( array, itemSize, normalized ) {
  14286. super( new Uint16Array( array ), itemSize, normalized );
  14287. this.isFloat16BufferAttribute = true;
  14288. }
  14289. getX( index ) {
  14290. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14291. if ( this.normalized ) x = denormalize( x, this.array );
  14292. return x;
  14293. }
  14294. setX( index, x ) {
  14295. if ( this.normalized ) x = normalize( x, this.array );
  14296. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14297. return this;
  14298. }
  14299. getY( index ) {
  14300. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14301. if ( this.normalized ) y = denormalize( y, this.array );
  14302. return y;
  14303. }
  14304. setY( index, y ) {
  14305. if ( this.normalized ) y = normalize( y, this.array );
  14306. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14307. return this;
  14308. }
  14309. getZ( index ) {
  14310. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14311. if ( this.normalized ) z = denormalize( z, this.array );
  14312. return z;
  14313. }
  14314. setZ( index, z ) {
  14315. if ( this.normalized ) z = normalize( z, this.array );
  14316. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14317. return this;
  14318. }
  14319. getW( index ) {
  14320. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14321. if ( this.normalized ) w = denormalize( w, this.array );
  14322. return w;
  14323. }
  14324. setW( index, w ) {
  14325. if ( this.normalized ) w = normalize( w, this.array );
  14326. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14327. return this;
  14328. }
  14329. setXY( index, x, y ) {
  14330. index *= this.itemSize;
  14331. if ( this.normalized ) {
  14332. x = normalize( x, this.array );
  14333. y = normalize( y, this.array );
  14334. }
  14335. this.array[ index + 0 ] = toHalfFloat( x );
  14336. this.array[ index + 1 ] = toHalfFloat( y );
  14337. return this;
  14338. }
  14339. setXYZ( index, x, y, z ) {
  14340. index *= this.itemSize;
  14341. if ( this.normalized ) {
  14342. x = normalize( x, this.array );
  14343. y = normalize( y, this.array );
  14344. z = normalize( z, this.array );
  14345. }
  14346. this.array[ index + 0 ] = toHalfFloat( x );
  14347. this.array[ index + 1 ] = toHalfFloat( y );
  14348. this.array[ index + 2 ] = toHalfFloat( z );
  14349. return this;
  14350. }
  14351. setXYZW( index, x, y, z, w ) {
  14352. index *= this.itemSize;
  14353. if ( this.normalized ) {
  14354. x = normalize( x, this.array );
  14355. y = normalize( y, this.array );
  14356. z = normalize( z, this.array );
  14357. w = normalize( w, this.array );
  14358. }
  14359. this.array[ index + 0 ] = toHalfFloat( x );
  14360. this.array[ index + 1 ] = toHalfFloat( y );
  14361. this.array[ index + 2 ] = toHalfFloat( z );
  14362. this.array[ index + 3 ] = toHalfFloat( w );
  14363. return this;
  14364. }
  14365. }
  14366. /**
  14367. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14368. * a plain `Array` instance.
  14369. *
  14370. * @augments BufferAttribute
  14371. */
  14372. class Float32BufferAttribute extends BufferAttribute {
  14373. /**
  14374. * Constructs a new buffer attribute.
  14375. *
  14376. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14377. * @param {number} itemSize - The item size.
  14378. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14379. */
  14380. constructor( array, itemSize, normalized ) {
  14381. super( new Float32Array( array ), itemSize, normalized );
  14382. }
  14383. }
  14384. let _id$1 = 0;
  14385. const _m1 = /*@__PURE__*/ new Matrix4();
  14386. const _obj = /*@__PURE__*/ new Object3D();
  14387. const _offset = /*@__PURE__*/ new Vector3();
  14388. const _box$2 = /*@__PURE__*/ new Box3();
  14389. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14390. const _vector$8 = /*@__PURE__*/ new Vector3();
  14391. /**
  14392. * A representation of mesh, line, or point geometry. Includes vertex
  14393. * positions, face indices, normals, colors, UVs, and custom attributes
  14394. * within buffers, reducing the cost of passing all this data to the GPU.
  14395. *
  14396. * ```js
  14397. * const geometry = new THREE.BufferGeometry();
  14398. * // create a simple square shape. We duplicate the top left and bottom right
  14399. * // vertices because each vertex needs to appear once per triangle.
  14400. * const vertices = new Float32Array( [
  14401. * -1.0, -1.0, 1.0, // v0
  14402. * 1.0, -1.0, 1.0, // v1
  14403. * 1.0, 1.0, 1.0, // v2
  14404. *
  14405. * 1.0, 1.0, 1.0, // v3
  14406. * -1.0, 1.0, 1.0, // v4
  14407. * -1.0, -1.0, 1.0 // v5
  14408. * ] );
  14409. * // itemSize = 3 because there are 3 values (components) per vertex
  14410. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14411. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14412. * const mesh = new THREE.Mesh( geometry, material );
  14413. * ```
  14414. *
  14415. * @augments EventDispatcher
  14416. */
  14417. class BufferGeometry extends EventDispatcher {
  14418. /**
  14419. * Constructs a new geometry.
  14420. */
  14421. constructor() {
  14422. super();
  14423. /**
  14424. * This flag can be used for type testing.
  14425. *
  14426. * @type {boolean}
  14427. * @readonly
  14428. * @default true
  14429. */
  14430. this.isBufferGeometry = true;
  14431. /**
  14432. * The ID of the geometry.
  14433. *
  14434. * @name BufferGeometry#id
  14435. * @type {number}
  14436. * @readonly
  14437. */
  14438. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  14439. /**
  14440. * The UUID of the geometry.
  14441. *
  14442. * @type {string}
  14443. * @readonly
  14444. */
  14445. this.uuid = generateUUID();
  14446. /**
  14447. * The name of the geometry.
  14448. *
  14449. * @type {string}
  14450. */
  14451. this.name = '';
  14452. this.type = 'BufferGeometry';
  14453. /**
  14454. * Allows for vertices to be re-used across multiple triangles; this is
  14455. * called using "indexed triangles". Each triangle is associated with the
  14456. * indices of three vertices. This attribute therefore stores the index of
  14457. * each vertex for each triangular face. If this attribute is not set, the
  14458. * renderer assumes that each three contiguous positions represent a single triangle.
  14459. *
  14460. * @type {?BufferAttribute}
  14461. * @default null
  14462. */
  14463. this.index = null;
  14464. /**
  14465. * A (storage) buffer attribute which was generated with a compute shader and
  14466. * now defines indirect draw calls.
  14467. *
  14468. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14469. *
  14470. * @type {?BufferAttribute}
  14471. * @default null
  14472. */
  14473. this.indirect = null;
  14474. /**
  14475. * 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.
  14476. *
  14477. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14478. *
  14479. * @type {number|Array<number>}
  14480. * @default 0
  14481. */
  14482. this.indirectOffset = 0;
  14483. /**
  14484. * This dictionary has as id the name of the attribute to be set and as value
  14485. * the buffer attribute to set it to. Rather than accessing this property directly,
  14486. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14487. *
  14488. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14489. */
  14490. this.attributes = {};
  14491. /**
  14492. * This dictionary holds the morph targets of the geometry.
  14493. *
  14494. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14495. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  14496. *
  14497. * @type {Object}
  14498. */
  14499. this.morphAttributes = {};
  14500. /**
  14501. * Used to control the morph target behavior; when set to `true`, the morph
  14502. * target data is treated as relative offsets, rather than as absolute
  14503. * positions/normals.
  14504. *
  14505. * @type {boolean}
  14506. * @default false
  14507. */
  14508. this.morphTargetsRelative = false;
  14509. /**
  14510. * Split the geometry into groups, each of which will be rendered in a
  14511. * separate draw call. This allows an array of materials to be used with the geometry.
  14512. *
  14513. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14514. *
  14515. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14516. * indices, and must not leave vertices or indices unused.
  14517. *
  14518. * @type {Array<Object>}
  14519. */
  14520. this.groups = [];
  14521. /**
  14522. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14523. *
  14524. * @type {?Box3}
  14525. * @default null
  14526. */
  14527. this.boundingBox = null;
  14528. /**
  14529. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14530. *
  14531. * @type {?Sphere}
  14532. * @default null
  14533. */
  14534. this.boundingSphere = null;
  14535. /**
  14536. * Determines the part of the geometry to render. This should not be set directly,
  14537. * instead use `setDrawRange()`.
  14538. *
  14539. * @type {{start:number,count:number}}
  14540. */
  14541. this.drawRange = { start: 0, count: Infinity };
  14542. /**
  14543. * An object that can be used to store custom data about the geometry.
  14544. * It should not hold references to functions as these will not be cloned.
  14545. *
  14546. * @type {Object}
  14547. */
  14548. this.userData = {};
  14549. }
  14550. /**
  14551. * Returns the index of this geometry.
  14552. *
  14553. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14554. */
  14555. getIndex() {
  14556. return this.index;
  14557. }
  14558. /**
  14559. * Sets the given index to this geometry.
  14560. *
  14561. * @param {Array<number>|BufferAttribute} index - The index to set.
  14562. * @return {BufferGeometry} A reference to this instance.
  14563. */
  14564. setIndex( index ) {
  14565. if ( Array.isArray( index ) ) {
  14566. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14567. } else {
  14568. this.index = index;
  14569. }
  14570. return this;
  14571. }
  14572. /**
  14573. * Sets the given indirect attribute to this geometry.
  14574. *
  14575. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14576. * @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.
  14577. * @return {BufferGeometry} A reference to this instance.
  14578. */
  14579. setIndirect( indirect, indirectOffset = 0 ) {
  14580. this.indirect = indirect;
  14581. this.indirectOffset = indirectOffset;
  14582. return this;
  14583. }
  14584. /**
  14585. * Returns the indirect attribute of this geometry.
  14586. *
  14587. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14588. */
  14589. getIndirect() {
  14590. return this.indirect;
  14591. }
  14592. /**
  14593. * Returns the buffer attribute for the given name.
  14594. *
  14595. * @param {string} name - The attribute name.
  14596. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14597. * Returns `undefined` if not attribute has been found.
  14598. */
  14599. getAttribute( name ) {
  14600. return this.attributes[ name ];
  14601. }
  14602. /**
  14603. * Sets the given attribute for the given name.
  14604. *
  14605. * @param {string} name - The attribute name.
  14606. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14607. * @return {BufferGeometry} A reference to this instance.
  14608. */
  14609. setAttribute( name, attribute ) {
  14610. this.attributes[ name ] = attribute;
  14611. return this;
  14612. }
  14613. /**
  14614. * Deletes the attribute for the given name.
  14615. *
  14616. * @param {string} name - The attribute name to delete.
  14617. * @return {BufferGeometry} A reference to this instance.
  14618. */
  14619. deleteAttribute( name ) {
  14620. delete this.attributes[ name ];
  14621. return this;
  14622. }
  14623. /**
  14624. * Returns `true` if this geometry has an attribute for the given name.
  14625. *
  14626. * @param {string} name - The attribute name.
  14627. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14628. */
  14629. hasAttribute( name ) {
  14630. return this.attributes[ name ] !== undefined;
  14631. }
  14632. /**
  14633. * Adds a group to this geometry.
  14634. *
  14635. * @param {number} start - The first element in this draw call. That is the first
  14636. * vertex for non-indexed geometry, otherwise the first triangle index.
  14637. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14638. * @param {number} [materialIndex=0] - The material array index to use.
  14639. */
  14640. addGroup( start, count, materialIndex = 0 ) {
  14641. this.groups.push( {
  14642. start: start,
  14643. count: count,
  14644. materialIndex: materialIndex
  14645. } );
  14646. }
  14647. /**
  14648. * Clears all groups.
  14649. */
  14650. clearGroups() {
  14651. this.groups = [];
  14652. }
  14653. /**
  14654. * Sets the draw range for this geometry.
  14655. *
  14656. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14657. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14658. * For indexed BufferGeometry, `count` is the number of indices to render.
  14659. */
  14660. setDrawRange( start, count ) {
  14661. this.drawRange.start = start;
  14662. this.drawRange.count = count;
  14663. }
  14664. /**
  14665. * Applies the given 4x4 transformation matrix to the geometry.
  14666. *
  14667. * @param {Matrix4} matrix - The matrix to apply.
  14668. * @return {BufferGeometry} A reference to this instance.
  14669. */
  14670. applyMatrix4( matrix ) {
  14671. const position = this.attributes.position;
  14672. if ( position !== undefined ) {
  14673. position.applyMatrix4( matrix );
  14674. position.needsUpdate = true;
  14675. }
  14676. const normal = this.attributes.normal;
  14677. if ( normal !== undefined ) {
  14678. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14679. normal.applyNormalMatrix( normalMatrix );
  14680. normal.needsUpdate = true;
  14681. }
  14682. const tangent = this.attributes.tangent;
  14683. if ( tangent !== undefined ) {
  14684. tangent.transformDirection( matrix );
  14685. tangent.needsUpdate = true;
  14686. }
  14687. if ( this.boundingBox !== null ) {
  14688. this.computeBoundingBox();
  14689. }
  14690. if ( this.boundingSphere !== null ) {
  14691. this.computeBoundingSphere();
  14692. }
  14693. return this;
  14694. }
  14695. /**
  14696. * Applies the rotation represented by the Quaternion to the geometry.
  14697. *
  14698. * @param {Quaternion} q - The Quaternion to apply.
  14699. * @return {BufferGeometry} A reference to this instance.
  14700. */
  14701. applyQuaternion( q ) {
  14702. _m1.makeRotationFromQuaternion( q );
  14703. this.applyMatrix4( _m1 );
  14704. return this;
  14705. }
  14706. /**
  14707. * Rotates the geometry about the X axis. This is typically done as a one time
  14708. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14709. * real-time mesh rotation.
  14710. *
  14711. * @param {number} angle - The angle in radians.
  14712. * @return {BufferGeometry} A reference to this instance.
  14713. */
  14714. rotateX( angle ) {
  14715. // rotate geometry around world x-axis
  14716. _m1.makeRotationX( angle );
  14717. this.applyMatrix4( _m1 );
  14718. return this;
  14719. }
  14720. /**
  14721. * Rotates the geometry about the Y axis. This is typically done as a one time
  14722. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14723. * real-time mesh rotation.
  14724. *
  14725. * @param {number} angle - The angle in radians.
  14726. * @return {BufferGeometry} A reference to this instance.
  14727. */
  14728. rotateY( angle ) {
  14729. // rotate geometry around world y-axis
  14730. _m1.makeRotationY( angle );
  14731. this.applyMatrix4( _m1 );
  14732. return this;
  14733. }
  14734. /**
  14735. * Rotates the geometry about the Z axis. This is typically done as a one time
  14736. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14737. * real-time mesh rotation.
  14738. *
  14739. * @param {number} angle - The angle in radians.
  14740. * @return {BufferGeometry} A reference to this instance.
  14741. */
  14742. rotateZ( angle ) {
  14743. // rotate geometry around world z-axis
  14744. _m1.makeRotationZ( angle );
  14745. this.applyMatrix4( _m1 );
  14746. return this;
  14747. }
  14748. /**
  14749. * Translates the geometry. This is typically done as a one time
  14750. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14751. * real-time mesh rotation.
  14752. *
  14753. * @param {number} x - The x offset.
  14754. * @param {number} y - The y offset.
  14755. * @param {number} z - The z offset.
  14756. * @return {BufferGeometry} A reference to this instance.
  14757. */
  14758. translate( x, y, z ) {
  14759. // translate geometry
  14760. _m1.makeTranslation( x, y, z );
  14761. this.applyMatrix4( _m1 );
  14762. return this;
  14763. }
  14764. /**
  14765. * Scales the geometry. This is typically done as a one time
  14766. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14767. * real-time mesh rotation.
  14768. *
  14769. * @param {number} x - The x scale.
  14770. * @param {number} y - The y scale.
  14771. * @param {number} z - The z scale.
  14772. * @return {BufferGeometry} A reference to this instance.
  14773. */
  14774. scale( x, y, z ) {
  14775. // scale geometry
  14776. _m1.makeScale( x, y, z );
  14777. this.applyMatrix4( _m1 );
  14778. return this;
  14779. }
  14780. /**
  14781. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14782. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14783. * real-time mesh rotation.
  14784. *
  14785. * @param {Vector3} vector - The target point.
  14786. * @return {BufferGeometry} A reference to this instance.
  14787. */
  14788. lookAt( vector ) {
  14789. _obj.lookAt( vector );
  14790. _obj.updateMatrix();
  14791. this.applyMatrix4( _obj.matrix );
  14792. return this;
  14793. }
  14794. /**
  14795. * Center the geometry based on its bounding box.
  14796. *
  14797. * @return {BufferGeometry} A reference to this instance.
  14798. */
  14799. center() {
  14800. this.computeBoundingBox();
  14801. this.boundingBox.getCenter( _offset ).negate();
  14802. this.translate( _offset.x, _offset.y, _offset.z );
  14803. return this;
  14804. }
  14805. /**
  14806. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14807. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14808. * set to `0`.
  14809. *
  14810. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14811. * data from the array. The length of the array must match the vertex count.
  14812. *
  14813. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14814. * @return {BufferGeometry} A reference to this instance.
  14815. */
  14816. setFromPoints( points ) {
  14817. const positionAttribute = this.getAttribute( 'position' );
  14818. if ( positionAttribute === undefined ) {
  14819. const position = [];
  14820. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14821. const point = points[ i ];
  14822. position.push( point.x, point.y, point.z || 0 );
  14823. }
  14824. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14825. } else {
  14826. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14827. for ( let i = 0; i < l; i ++ ) {
  14828. const point = points[ i ];
  14829. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14830. }
  14831. if ( points.length > positionAttribute.count ) {
  14832. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14833. }
  14834. positionAttribute.needsUpdate = true;
  14835. }
  14836. return this;
  14837. }
  14838. /**
  14839. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14840. * The bounding box is not computed by the engine; it must be computed by your app.
  14841. * You may need to recompute the bounding box if the geometry vertices are modified.
  14842. */
  14843. computeBoundingBox() {
  14844. if ( this.boundingBox === null ) {
  14845. this.boundingBox = new Box3();
  14846. }
  14847. const position = this.attributes.position;
  14848. const morphAttributesPosition = this.morphAttributes.position;
  14849. if ( position && position.isGLBufferAttribute ) {
  14850. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14851. this.boundingBox.set(
  14852. new Vector3( - Infinity, - Infinity, - Infinity ),
  14853. new Vector3( + Infinity, + Infinity, + Infinity )
  14854. );
  14855. return;
  14856. }
  14857. if ( position !== undefined ) {
  14858. this.boundingBox.setFromBufferAttribute( position );
  14859. // process morph attributes if present
  14860. if ( morphAttributesPosition ) {
  14861. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14862. const morphAttribute = morphAttributesPosition[ i ];
  14863. _box$2.setFromBufferAttribute( morphAttribute );
  14864. if ( this.morphTargetsRelative ) {
  14865. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14866. this.boundingBox.expandByPoint( _vector$8 );
  14867. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14868. this.boundingBox.expandByPoint( _vector$8 );
  14869. } else {
  14870. this.boundingBox.expandByPoint( _box$2.min );
  14871. this.boundingBox.expandByPoint( _box$2.max );
  14872. }
  14873. }
  14874. }
  14875. } else {
  14876. this.boundingBox.makeEmpty();
  14877. }
  14878. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14879. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14880. }
  14881. }
  14882. /**
  14883. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14884. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14885. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14886. */
  14887. computeBoundingSphere() {
  14888. if ( this.boundingSphere === null ) {
  14889. this.boundingSphere = new Sphere();
  14890. }
  14891. const position = this.attributes.position;
  14892. const morphAttributesPosition = this.morphAttributes.position;
  14893. if ( position && position.isGLBufferAttribute ) {
  14894. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14895. this.boundingSphere.set( new Vector3(), Infinity );
  14896. return;
  14897. }
  14898. if ( position ) {
  14899. // first, find the center of the bounding sphere
  14900. const center = this.boundingSphere.center;
  14901. _box$2.setFromBufferAttribute( position );
  14902. // process morph attributes if present
  14903. if ( morphAttributesPosition ) {
  14904. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14905. const morphAttribute = morphAttributesPosition[ i ];
  14906. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14907. if ( this.morphTargetsRelative ) {
  14908. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14909. _box$2.expandByPoint( _vector$8 );
  14910. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14911. _box$2.expandByPoint( _vector$8 );
  14912. } else {
  14913. _box$2.expandByPoint( _boxMorphTargets.min );
  14914. _box$2.expandByPoint( _boxMorphTargets.max );
  14915. }
  14916. }
  14917. }
  14918. _box$2.getCenter( center );
  14919. // second, try to find a boundingSphere with a radius smaller than the
  14920. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14921. let maxRadiusSq = 0;
  14922. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14923. _vector$8.fromBufferAttribute( position, i );
  14924. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14925. }
  14926. // process morph attributes if present
  14927. if ( morphAttributesPosition ) {
  14928. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14929. const morphAttribute = morphAttributesPosition[ i ];
  14930. const morphTargetsRelative = this.morphTargetsRelative;
  14931. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14932. _vector$8.fromBufferAttribute( morphAttribute, j );
  14933. if ( morphTargetsRelative ) {
  14934. _offset.fromBufferAttribute( position, j );
  14935. _vector$8.add( _offset );
  14936. }
  14937. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14938. }
  14939. }
  14940. }
  14941. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14942. if ( isNaN( this.boundingSphere.radius ) ) {
  14943. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14944. }
  14945. }
  14946. }
  14947. /**
  14948. * Calculates and adds a tangent attribute to this geometry.
  14949. *
  14950. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14951. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14952. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14953. */
  14954. computeTangents() {
  14955. const index = this.index;
  14956. const attributes = this.attributes;
  14957. // based on http://www.terathon.com/code/tangent.html
  14958. // (per vertex tangents)
  14959. if ( index === null ||
  14960. attributes.position === undefined ||
  14961. attributes.normal === undefined ||
  14962. attributes.uv === undefined ) {
  14963. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14964. return;
  14965. }
  14966. const positionAttribute = attributes.position;
  14967. const normalAttribute = attributes.normal;
  14968. const uvAttribute = attributes.uv;
  14969. if ( this.hasAttribute( 'tangent' ) === false ) {
  14970. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14971. }
  14972. const tangentAttribute = this.getAttribute( 'tangent' );
  14973. const tan1 = [], tan2 = [];
  14974. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14975. tan1[ i ] = new Vector3();
  14976. tan2[ i ] = new Vector3();
  14977. }
  14978. const vA = new Vector3(),
  14979. vB = new Vector3(),
  14980. vC = new Vector3(),
  14981. uvA = new Vector2(),
  14982. uvB = new Vector2(),
  14983. uvC = new Vector2(),
  14984. sdir = new Vector3(),
  14985. tdir = new Vector3();
  14986. function handleTriangle( a, b, c ) {
  14987. vA.fromBufferAttribute( positionAttribute, a );
  14988. vB.fromBufferAttribute( positionAttribute, b );
  14989. vC.fromBufferAttribute( positionAttribute, c );
  14990. uvA.fromBufferAttribute( uvAttribute, a );
  14991. uvB.fromBufferAttribute( uvAttribute, b );
  14992. uvC.fromBufferAttribute( uvAttribute, c );
  14993. vB.sub( vA );
  14994. vC.sub( vA );
  14995. uvB.sub( uvA );
  14996. uvC.sub( uvA );
  14997. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14998. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14999. if ( ! isFinite( r ) ) return;
  15000. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  15001. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  15002. tan1[ a ].add( sdir );
  15003. tan1[ b ].add( sdir );
  15004. tan1[ c ].add( sdir );
  15005. tan2[ a ].add( tdir );
  15006. tan2[ b ].add( tdir );
  15007. tan2[ c ].add( tdir );
  15008. }
  15009. let groups = this.groups;
  15010. if ( groups.length === 0 ) {
  15011. groups = [ {
  15012. start: 0,
  15013. count: index.count
  15014. } ];
  15015. }
  15016. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  15017. const group = groups[ i ];
  15018. const start = group.start;
  15019. const count = group.count;
  15020. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  15021. handleTriangle(
  15022. index.getX( j + 0 ),
  15023. index.getX( j + 1 ),
  15024. index.getX( j + 2 )
  15025. );
  15026. }
  15027. }
  15028. const tmp = new Vector3(), tmp2 = new Vector3();
  15029. const n = new Vector3(), n2 = new Vector3();
  15030. function handleVertex( v ) {
  15031. n.fromBufferAttribute( normalAttribute, v );
  15032. n2.copy( n );
  15033. const t = tan1[ v ];
  15034. // Gram-Schmidt orthogonalize
  15035. tmp.copy( t );
  15036. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  15037. // Calculate handedness
  15038. tmp2.crossVectors( n2, t );
  15039. const test = tmp2.dot( tan2[ v ] );
  15040. const w = ( test < 0.0 ) ? -1 : 1.0;
  15041. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  15042. }
  15043. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  15044. const group = groups[ i ];
  15045. const start = group.start;
  15046. const count = group.count;
  15047. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  15048. handleVertex( index.getX( j + 0 ) );
  15049. handleVertex( index.getX( j + 1 ) );
  15050. handleVertex( index.getX( j + 2 ) );
  15051. }
  15052. }
  15053. }
  15054. /**
  15055. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  15056. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  15057. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  15058. * to be the same as the face normal.
  15059. */
  15060. computeVertexNormals() {
  15061. const index = this.index;
  15062. const positionAttribute = this.getAttribute( 'position' );
  15063. if ( positionAttribute !== undefined ) {
  15064. let normalAttribute = this.getAttribute( 'normal' );
  15065. if ( normalAttribute === undefined ) {
  15066. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  15067. this.setAttribute( 'normal', normalAttribute );
  15068. } else {
  15069. // reset existing normals to zero
  15070. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  15071. normalAttribute.setXYZ( i, 0, 0, 0 );
  15072. }
  15073. }
  15074. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  15075. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  15076. const cb = new Vector3(), ab = new Vector3();
  15077. // indexed elements
  15078. if ( index ) {
  15079. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  15080. const vA = index.getX( i + 0 );
  15081. const vB = index.getX( i + 1 );
  15082. const vC = index.getX( i + 2 );
  15083. pA.fromBufferAttribute( positionAttribute, vA );
  15084. pB.fromBufferAttribute( positionAttribute, vB );
  15085. pC.fromBufferAttribute( positionAttribute, vC );
  15086. cb.subVectors( pC, pB );
  15087. ab.subVectors( pA, pB );
  15088. cb.cross( ab );
  15089. nA.fromBufferAttribute( normalAttribute, vA );
  15090. nB.fromBufferAttribute( normalAttribute, vB );
  15091. nC.fromBufferAttribute( normalAttribute, vC );
  15092. nA.add( cb );
  15093. nB.add( cb );
  15094. nC.add( cb );
  15095. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  15096. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  15097. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  15098. }
  15099. } else {
  15100. // non-indexed elements (unconnected triangle soup)
  15101. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  15102. pA.fromBufferAttribute( positionAttribute, i + 0 );
  15103. pB.fromBufferAttribute( positionAttribute, i + 1 );
  15104. pC.fromBufferAttribute( positionAttribute, i + 2 );
  15105. cb.subVectors( pC, pB );
  15106. ab.subVectors( pA, pB );
  15107. cb.cross( ab );
  15108. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  15109. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  15110. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  15111. }
  15112. }
  15113. this.normalizeNormals();
  15114. normalAttribute.needsUpdate = true;
  15115. }
  15116. }
  15117. /**
  15118. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  15119. * correct lighting on the geometry surfaces.
  15120. */
  15121. normalizeNormals() {
  15122. const normals = this.attributes.normal;
  15123. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  15124. _vector$8.fromBufferAttribute( normals, i );
  15125. _vector$8.normalize();
  15126. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  15127. }
  15128. }
  15129. /**
  15130. * Return a new non-index version of this indexed geometry. If the geometry
  15131. * is already non-indexed, the method is a NOOP.
  15132. *
  15133. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  15134. */
  15135. toNonIndexed() {
  15136. function convertBufferAttribute( attribute, indices ) {
  15137. const array = attribute.array;
  15138. const itemSize = attribute.itemSize;
  15139. const normalized = attribute.normalized;
  15140. const array2 = new array.constructor( indices.length * itemSize );
  15141. let index = 0, index2 = 0;
  15142. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  15143. if ( attribute.isInterleavedBufferAttribute ) {
  15144. index = indices[ i ] * attribute.data.stride + attribute.offset;
  15145. } else {
  15146. index = indices[ i ] * itemSize;
  15147. }
  15148. for ( let j = 0; j < itemSize; j ++ ) {
  15149. array2[ index2 ++ ] = array[ index ++ ];
  15150. }
  15151. }
  15152. return new BufferAttribute( array2, itemSize, normalized );
  15153. }
  15154. //
  15155. if ( this.index === null ) {
  15156. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  15157. return this;
  15158. }
  15159. const geometry2 = new BufferGeometry();
  15160. const indices = this.index.array;
  15161. const attributes = this.attributes;
  15162. // attributes
  15163. for ( const name in attributes ) {
  15164. const attribute = attributes[ name ];
  15165. const newAttribute = convertBufferAttribute( attribute, indices );
  15166. geometry2.setAttribute( name, newAttribute );
  15167. }
  15168. // morph attributes
  15169. const morphAttributes = this.morphAttributes;
  15170. for ( const name in morphAttributes ) {
  15171. const morphArray = [];
  15172. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15173. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  15174. const attribute = morphAttribute[ i ];
  15175. const newAttribute = convertBufferAttribute( attribute, indices );
  15176. morphArray.push( newAttribute );
  15177. }
  15178. geometry2.morphAttributes[ name ] = morphArray;
  15179. }
  15180. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  15181. // groups
  15182. const groups = this.groups;
  15183. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15184. const group = groups[ i ];
  15185. geometry2.addGroup( group.start, group.count, group.materialIndex );
  15186. }
  15187. return geometry2;
  15188. }
  15189. /**
  15190. * Serializes the geometry into JSON.
  15191. *
  15192. * @return {Object} A JSON object representing the serialized geometry.
  15193. */
  15194. toJSON() {
  15195. const data = {
  15196. metadata: {
  15197. version: 4.7,
  15198. type: 'BufferGeometry',
  15199. generator: 'BufferGeometry.toJSON'
  15200. }
  15201. };
  15202. // standard BufferGeometry serialization
  15203. data.uuid = this.uuid;
  15204. data.type = this.type;
  15205. if ( this.name !== '' ) data.name = this.name;
  15206. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15207. if ( this.parameters !== undefined ) {
  15208. const parameters = this.parameters;
  15209. for ( const key in parameters ) {
  15210. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  15211. }
  15212. return data;
  15213. }
  15214. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  15215. data.data = { attributes: {} };
  15216. const index = this.index;
  15217. if ( index !== null ) {
  15218. data.data.index = {
  15219. type: index.array.constructor.name,
  15220. array: Array.prototype.slice.call( index.array )
  15221. };
  15222. }
  15223. const attributes = this.attributes;
  15224. for ( const key in attributes ) {
  15225. const attribute = attributes[ key ];
  15226. data.data.attributes[ key ] = attribute.toJSON( data.data );
  15227. }
  15228. const morphAttributes = {};
  15229. let hasMorphAttributes = false;
  15230. for ( const key in this.morphAttributes ) {
  15231. const attributeArray = this.morphAttributes[ key ];
  15232. const array = [];
  15233. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  15234. const attribute = attributeArray[ i ];
  15235. array.push( attribute.toJSON( data.data ) );
  15236. }
  15237. if ( array.length > 0 ) {
  15238. morphAttributes[ key ] = array;
  15239. hasMorphAttributes = true;
  15240. }
  15241. }
  15242. if ( hasMorphAttributes ) {
  15243. data.data.morphAttributes = morphAttributes;
  15244. data.data.morphTargetsRelative = this.morphTargetsRelative;
  15245. }
  15246. const groups = this.groups;
  15247. if ( groups.length > 0 ) {
  15248. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  15249. }
  15250. const boundingSphere = this.boundingSphere;
  15251. if ( boundingSphere !== null ) {
  15252. data.data.boundingSphere = boundingSphere.toJSON();
  15253. }
  15254. return data;
  15255. }
  15256. /**
  15257. * Returns a new geometry with copied values from this instance.
  15258. *
  15259. * @return {BufferGeometry} A clone of this instance.
  15260. */
  15261. clone() {
  15262. return new this.constructor().copy( this );
  15263. }
  15264. /**
  15265. * Copies the values of the given geometry to this instance.
  15266. *
  15267. * @param {BufferGeometry} source - The geometry to copy.
  15268. * @return {BufferGeometry} A reference to this instance.
  15269. */
  15270. copy( source ) {
  15271. // reset
  15272. this.index = null;
  15273. this.attributes = {};
  15274. this.morphAttributes = {};
  15275. this.groups = [];
  15276. this.boundingBox = null;
  15277. this.boundingSphere = null;
  15278. // used for storing cloned, shared data
  15279. const data = {};
  15280. // name
  15281. this.name = source.name;
  15282. // index
  15283. const index = source.index;
  15284. if ( index !== null ) {
  15285. this.setIndex( index.clone() );
  15286. }
  15287. // attributes
  15288. const attributes = source.attributes;
  15289. for ( const name in attributes ) {
  15290. const attribute = attributes[ name ];
  15291. this.setAttribute( name, attribute.clone( data ) );
  15292. }
  15293. // morph attributes
  15294. const morphAttributes = source.morphAttributes;
  15295. for ( const name in morphAttributes ) {
  15296. const array = [];
  15297. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15298. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15299. array.push( morphAttribute[ i ].clone( data ) );
  15300. }
  15301. this.morphAttributes[ name ] = array;
  15302. }
  15303. this.morphTargetsRelative = source.morphTargetsRelative;
  15304. // groups
  15305. const groups = source.groups;
  15306. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15307. const group = groups[ i ];
  15308. this.addGroup( group.start, group.count, group.materialIndex );
  15309. }
  15310. // bounding box
  15311. const boundingBox = source.boundingBox;
  15312. if ( boundingBox !== null ) {
  15313. this.boundingBox = boundingBox.clone();
  15314. }
  15315. // bounding sphere
  15316. const boundingSphere = source.boundingSphere;
  15317. if ( boundingSphere !== null ) {
  15318. this.boundingSphere = boundingSphere.clone();
  15319. }
  15320. // draw range
  15321. this.drawRange.start = source.drawRange.start;
  15322. this.drawRange.count = source.drawRange.count;
  15323. // user data
  15324. this.userData = source.userData;
  15325. return this;
  15326. }
  15327. /**
  15328. * Frees the GPU-related resources allocated by this instance. Call this
  15329. * method whenever this instance is no longer used in your app.
  15330. *
  15331. * @fires BufferGeometry#dispose
  15332. */
  15333. dispose() {
  15334. this.dispatchEvent( { type: 'dispose' } );
  15335. }
  15336. }
  15337. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15338. const _ray$3 = /*@__PURE__*/ new Ray();
  15339. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15340. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15341. const _vA$1 = /*@__PURE__*/ new Vector3();
  15342. const _vB$1 = /*@__PURE__*/ new Vector3();
  15343. const _vC$1 = /*@__PURE__*/ new Vector3();
  15344. const _tempA = /*@__PURE__*/ new Vector3();
  15345. const _morphA = /*@__PURE__*/ new Vector3();
  15346. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15347. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15348. /**
  15349. * Class representing triangular polygon mesh based objects.
  15350. *
  15351. * ```js
  15352. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15353. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15354. * const mesh = new THREE.Mesh( geometry, material );
  15355. * scene.add( mesh );
  15356. * ```
  15357. *
  15358. * @augments Object3D
  15359. */
  15360. class Mesh extends Object3D {
  15361. /**
  15362. * Constructs a new mesh.
  15363. *
  15364. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15365. * @param {Material|Array<Material>} [material] - The mesh material.
  15366. */
  15367. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15368. super();
  15369. /**
  15370. * This flag can be used for type testing.
  15371. *
  15372. * @type {boolean}
  15373. * @readonly
  15374. * @default true
  15375. */
  15376. this.isMesh = true;
  15377. this.type = 'Mesh';
  15378. /**
  15379. * The mesh geometry.
  15380. *
  15381. * @type {BufferGeometry}
  15382. */
  15383. this.geometry = geometry;
  15384. /**
  15385. * The mesh material.
  15386. *
  15387. * @type {Material|Array<Material>}
  15388. * @default MeshBasicMaterial
  15389. */
  15390. this.material = material;
  15391. /**
  15392. * A dictionary representing the morph targets in the geometry. The key is the
  15393. * morph targets name, the value its attribute index. This member is `undefined`
  15394. * by default and only set when morph targets are detected in the geometry.
  15395. *
  15396. * @type {Object<string,number>|undefined}
  15397. * @default undefined
  15398. */
  15399. this.morphTargetDictionary = undefined;
  15400. /**
  15401. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15402. * is applied. This member is `undefined` by default and only set when morph targets are
  15403. * detected in the geometry.
  15404. *
  15405. * @type {Array<number>|undefined}
  15406. * @default undefined
  15407. */
  15408. this.morphTargetInfluences = undefined;
  15409. /**
  15410. * The number of instances of this mesh.
  15411. * Can only be used with {@link WebGPURenderer}.
  15412. *
  15413. * @type {number}
  15414. * @default 1
  15415. */
  15416. this.count = 1;
  15417. this.updateMorphTargets();
  15418. }
  15419. copy( source, recursive ) {
  15420. super.copy( source, recursive );
  15421. if ( source.morphTargetInfluences !== undefined ) {
  15422. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15423. }
  15424. if ( source.morphTargetDictionary !== undefined ) {
  15425. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15426. }
  15427. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15428. this.geometry = source.geometry;
  15429. return this;
  15430. }
  15431. /**
  15432. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15433. * to make sure existing morph targets can influence this 3D object.
  15434. */
  15435. updateMorphTargets() {
  15436. const geometry = this.geometry;
  15437. const morphAttributes = geometry.morphAttributes;
  15438. const keys = Object.keys( morphAttributes );
  15439. if ( keys.length > 0 ) {
  15440. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15441. if ( morphAttribute !== undefined ) {
  15442. this.morphTargetInfluences = [];
  15443. this.morphTargetDictionary = {};
  15444. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15445. const name = morphAttribute[ m ].name || String( m );
  15446. this.morphTargetInfluences.push( 0 );
  15447. this.morphTargetDictionary[ name ] = m;
  15448. }
  15449. }
  15450. }
  15451. }
  15452. /**
  15453. * Returns the local-space position of the vertex at the given index, taking into
  15454. * account the current animation state of both morph targets and skinning.
  15455. *
  15456. * @param {number} index - The vertex index.
  15457. * @param {Vector3} target - The target object that is used to store the method's result.
  15458. * @return {Vector3} The vertex position in local space.
  15459. */
  15460. getVertexPosition( index, target ) {
  15461. const geometry = this.geometry;
  15462. const position = geometry.attributes.position;
  15463. const morphPosition = geometry.morphAttributes.position;
  15464. const morphTargetsRelative = geometry.morphTargetsRelative;
  15465. target.fromBufferAttribute( position, index );
  15466. const morphInfluences = this.morphTargetInfluences;
  15467. if ( morphPosition && morphInfluences ) {
  15468. _morphA.set( 0, 0, 0 );
  15469. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15470. const influence = morphInfluences[ i ];
  15471. const morphAttribute = morphPosition[ i ];
  15472. if ( influence === 0 ) continue;
  15473. _tempA.fromBufferAttribute( morphAttribute, index );
  15474. if ( morphTargetsRelative ) {
  15475. _morphA.addScaledVector( _tempA, influence );
  15476. } else {
  15477. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15478. }
  15479. }
  15480. target.add( _morphA );
  15481. }
  15482. return target;
  15483. }
  15484. /**
  15485. * Computes intersection points between a casted ray and this line.
  15486. *
  15487. * @param {Raycaster} raycaster - The raycaster.
  15488. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15489. */
  15490. raycast( raycaster, intersects ) {
  15491. const geometry = this.geometry;
  15492. const material = this.material;
  15493. const matrixWorld = this.matrixWorld;
  15494. if ( material === undefined ) return;
  15495. // test with bounding sphere in world space
  15496. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15497. _sphere$6.copy( geometry.boundingSphere );
  15498. _sphere$6.applyMatrix4( matrixWorld );
  15499. // check distance from ray origin to bounding sphere
  15500. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15501. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15502. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15503. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15504. }
  15505. // convert ray to local space of mesh
  15506. _inverseMatrix$3.copy( matrixWorld ).invert();
  15507. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15508. // test with bounding box in local space
  15509. if ( geometry.boundingBox !== null ) {
  15510. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15511. }
  15512. // test for intersections with geometry
  15513. this._computeIntersections( raycaster, intersects, _ray$3 );
  15514. }
  15515. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15516. let intersection;
  15517. const geometry = this.geometry;
  15518. const material = this.material;
  15519. const index = geometry.index;
  15520. const position = geometry.attributes.position;
  15521. const uv = geometry.attributes.uv;
  15522. const uv1 = geometry.attributes.uv1;
  15523. const normal = geometry.attributes.normal;
  15524. const groups = geometry.groups;
  15525. const drawRange = geometry.drawRange;
  15526. if ( index !== null ) {
  15527. // indexed buffer geometry
  15528. if ( Array.isArray( material ) ) {
  15529. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15530. const group = groups[ i ];
  15531. const groupMaterial = material[ group.materialIndex ];
  15532. const start = Math.max( group.start, drawRange.start );
  15533. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15534. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15535. const a = index.getX( j );
  15536. const b = index.getX( j + 1 );
  15537. const c = index.getX( j + 2 );
  15538. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15539. if ( intersection ) {
  15540. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15541. intersection.face.materialIndex = group.materialIndex;
  15542. intersects.push( intersection );
  15543. }
  15544. }
  15545. }
  15546. } else {
  15547. const start = Math.max( 0, drawRange.start );
  15548. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15549. for ( let i = start, il = end; i < il; i += 3 ) {
  15550. const a = index.getX( i );
  15551. const b = index.getX( i + 1 );
  15552. const c = index.getX( i + 2 );
  15553. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15554. if ( intersection ) {
  15555. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15556. intersects.push( intersection );
  15557. }
  15558. }
  15559. }
  15560. } else if ( position !== undefined ) {
  15561. // non-indexed buffer geometry
  15562. if ( Array.isArray( material ) ) {
  15563. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15564. const group = groups[ i ];
  15565. const groupMaterial = material[ group.materialIndex ];
  15566. const start = Math.max( group.start, drawRange.start );
  15567. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15568. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15569. const a = j;
  15570. const b = j + 1;
  15571. const c = j + 2;
  15572. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15573. if ( intersection ) {
  15574. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15575. intersection.face.materialIndex = group.materialIndex;
  15576. intersects.push( intersection );
  15577. }
  15578. }
  15579. }
  15580. } else {
  15581. const start = Math.max( 0, drawRange.start );
  15582. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15583. for ( let i = start, il = end; i < il; i += 3 ) {
  15584. const a = i;
  15585. const b = i + 1;
  15586. const c = i + 2;
  15587. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15588. if ( intersection ) {
  15589. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15590. intersects.push( intersection );
  15591. }
  15592. }
  15593. }
  15594. }
  15595. }
  15596. }
  15597. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15598. let intersect;
  15599. if ( material.side === BackSide ) {
  15600. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15601. } else {
  15602. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15603. }
  15604. if ( intersect === null ) return null;
  15605. _intersectionPointWorld.copy( point );
  15606. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15607. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15608. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15609. return {
  15610. distance: distance,
  15611. point: _intersectionPointWorld.clone(),
  15612. object: object
  15613. };
  15614. }
  15615. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15616. object.getVertexPosition( a, _vA$1 );
  15617. object.getVertexPosition( b, _vB$1 );
  15618. object.getVertexPosition( c, _vC$1 );
  15619. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15620. if ( intersection ) {
  15621. const barycoord = new Vector3();
  15622. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15623. if ( uv ) {
  15624. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15625. }
  15626. if ( uv1 ) {
  15627. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15628. }
  15629. if ( normal ) {
  15630. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15631. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15632. intersection.normal.multiplyScalar( -1 );
  15633. }
  15634. }
  15635. const face = {
  15636. a: a,
  15637. b: b,
  15638. c: c,
  15639. normal: new Vector3(),
  15640. materialIndex: 0
  15641. };
  15642. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15643. intersection.face = face;
  15644. intersection.barycoord = barycoord;
  15645. }
  15646. return intersection;
  15647. }
  15648. /**
  15649. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15650. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15651. * of the axes.
  15652. *
  15653. * ```js
  15654. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15655. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15656. * const cube = new THREE.Mesh( geometry, material );
  15657. * scene.add( cube );
  15658. * ```
  15659. *
  15660. * @augments BufferGeometry
  15661. * @demo scenes/geometry-browser.html#BoxGeometry
  15662. */
  15663. class BoxGeometry extends BufferGeometry {
  15664. /**
  15665. * Constructs a new box geometry.
  15666. *
  15667. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15668. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15669. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15670. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15671. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15672. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15673. */
  15674. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15675. super();
  15676. this.type = 'BoxGeometry';
  15677. /**
  15678. * Holds the constructor parameters that have been
  15679. * used to generate the geometry. Any modification
  15680. * after instantiation does not change the geometry.
  15681. *
  15682. * @type {Object}
  15683. */
  15684. this.parameters = {
  15685. width: width,
  15686. height: height,
  15687. depth: depth,
  15688. widthSegments: widthSegments,
  15689. heightSegments: heightSegments,
  15690. depthSegments: depthSegments
  15691. };
  15692. const scope = this;
  15693. // segments
  15694. widthSegments = Math.floor( widthSegments );
  15695. heightSegments = Math.floor( heightSegments );
  15696. depthSegments = Math.floor( depthSegments );
  15697. // buffers
  15698. const indices = [];
  15699. const vertices = [];
  15700. const normals = [];
  15701. const uvs = [];
  15702. // helper variables
  15703. let numberOfVertices = 0;
  15704. let groupStart = 0;
  15705. // build each side of the box geometry
  15706. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15707. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15708. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15709. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15710. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15711. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15712. // build geometry
  15713. this.setIndex( indices );
  15714. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15715. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15716. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15717. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15718. const segmentWidth = width / gridX;
  15719. const segmentHeight = height / gridY;
  15720. const widthHalf = width / 2;
  15721. const heightHalf = height / 2;
  15722. const depthHalf = depth / 2;
  15723. const gridX1 = gridX + 1;
  15724. const gridY1 = gridY + 1;
  15725. let vertexCounter = 0;
  15726. let groupCount = 0;
  15727. const vector = new Vector3();
  15728. // generate vertices, normals and uvs
  15729. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15730. const y = iy * segmentHeight - heightHalf;
  15731. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15732. const x = ix * segmentWidth - widthHalf;
  15733. // set values to correct vector component
  15734. vector[ u ] = x * udir;
  15735. vector[ v ] = y * vdir;
  15736. vector[ w ] = depthHalf;
  15737. // now apply vector to vertex buffer
  15738. vertices.push( vector.x, vector.y, vector.z );
  15739. // set values to correct vector component
  15740. vector[ u ] = 0;
  15741. vector[ v ] = 0;
  15742. vector[ w ] = depth > 0 ? 1 : -1;
  15743. // now apply vector to normal buffer
  15744. normals.push( vector.x, vector.y, vector.z );
  15745. // uvs
  15746. uvs.push( ix / gridX );
  15747. uvs.push( 1 - ( iy / gridY ) );
  15748. // counters
  15749. vertexCounter += 1;
  15750. }
  15751. }
  15752. // indices
  15753. // 1. you need three indices to draw a single face
  15754. // 2. a single segment consists of two faces
  15755. // 3. so we need to generate six (2*3) indices per segment
  15756. for ( let iy = 0; iy < gridY; iy ++ ) {
  15757. for ( let ix = 0; ix < gridX; ix ++ ) {
  15758. const a = numberOfVertices + ix + gridX1 * iy;
  15759. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15760. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15761. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15762. // faces
  15763. indices.push( a, b, d );
  15764. indices.push( b, c, d );
  15765. // increase counter
  15766. groupCount += 6;
  15767. }
  15768. }
  15769. // add a group to the geometry. this will ensure multi material support
  15770. scope.addGroup( groupStart, groupCount, materialIndex );
  15771. // calculate new start value for groups
  15772. groupStart += groupCount;
  15773. // update total number of vertices
  15774. numberOfVertices += vertexCounter;
  15775. }
  15776. }
  15777. copy( source ) {
  15778. super.copy( source );
  15779. this.parameters = Object.assign( {}, source.parameters );
  15780. return this;
  15781. }
  15782. /**
  15783. * Factory method for creating an instance of this class from the given
  15784. * JSON object.
  15785. *
  15786. * @param {Object} data - A JSON object representing the serialized geometry.
  15787. * @return {BoxGeometry} A new instance.
  15788. */
  15789. static fromJSON( data ) {
  15790. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15791. }
  15792. }
  15793. /**
  15794. * Provides utility functions for managing uniforms.
  15795. *
  15796. * @module UniformsUtils
  15797. */
  15798. /**
  15799. * Clones the given uniform definitions by performing a deep-copy. That means
  15800. * if the value of a uniform refers to an object like a Vector3 or Texture,
  15801. * the cloned uniform will refer to a new object reference.
  15802. *
  15803. * @param {Object} src - An object representing uniform definitions.
  15804. * @return {Object} The cloned uniforms.
  15805. */
  15806. function cloneUniforms( src ) {
  15807. const dst = {};
  15808. for ( const u in src ) {
  15809. dst[ u ] = {};
  15810. for ( const p in src[ u ] ) {
  15811. const property = src[ u ][ p ];
  15812. if ( property && ( property.isColor ||
  15813. property.isMatrix3 || property.isMatrix4 ||
  15814. property.isVector2 || property.isVector3 || property.isVector4 ||
  15815. property.isTexture || property.isQuaternion ) ) {
  15816. if ( property.isRenderTargetTexture ) {
  15817. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15818. dst[ u ][ p ] = null;
  15819. } else {
  15820. dst[ u ][ p ] = property.clone();
  15821. }
  15822. } else if ( Array.isArray( property ) ) {
  15823. dst[ u ][ p ] = property.slice();
  15824. } else {
  15825. dst[ u ][ p ] = property;
  15826. }
  15827. }
  15828. }
  15829. return dst;
  15830. }
  15831. /**
  15832. * Merges the given uniform definitions into a single object. Since the
  15833. * method internally uses cloneUniforms(), it performs a deep-copy when
  15834. * producing the merged uniform definitions.
  15835. *
  15836. * @param {Array} uniforms - An array of objects containing uniform definitions.
  15837. * @return {Object} The merged uniforms.
  15838. */
  15839. function mergeUniforms( uniforms ) {
  15840. const merged = {};
  15841. for ( let u = 0; u < uniforms.length; u ++ ) {
  15842. const tmp = cloneUniforms( uniforms[ u ] );
  15843. for ( const p in tmp ) {
  15844. merged[ p ] = tmp[ p ];
  15845. }
  15846. }
  15847. return merged;
  15848. }
  15849. function cloneUniformsGroups( src ) {
  15850. const dst = [];
  15851. for ( let u = 0; u < src.length; u ++ ) {
  15852. dst.push( src[ u ].clone() );
  15853. }
  15854. return dst;
  15855. }
  15856. function getUnlitUniformColorSpace( renderer ) {
  15857. const currentRenderTarget = renderer.getRenderTarget();
  15858. if ( currentRenderTarget === null ) {
  15859. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15860. return renderer.outputColorSpace;
  15861. }
  15862. // https://github.com/mrdoob/three.js/issues/27868
  15863. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15864. return currentRenderTarget.texture.colorSpace;
  15865. }
  15866. return ColorManagement.workingColorSpace;
  15867. }
  15868. // Legacy
  15869. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15870. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15871. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15872. /**
  15873. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15874. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15875. * effect not included with any of the built-in materials.
  15876. *
  15877. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15878. *
  15879. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15880. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15881. * you don't want that, use {@link RawShaderMaterial} instead.
  15882. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15883. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15884. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15885. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  15886. * - The loop variable has to be *i*.
  15887. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15888. * value of *i* for the given iteration and can be used in preprocessor
  15889. * statements.
  15890. *
  15891. * ```js
  15892. * const material = new THREE.ShaderMaterial( {
  15893. * uniforms: {
  15894. * time: { value: 1.0 },
  15895. * resolution: { value: new THREE.Vector2() }
  15896. * },
  15897. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15898. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15899. * } );
  15900. * ```
  15901. *
  15902. * @augments Material
  15903. */
  15904. class ShaderMaterial extends Material {
  15905. /**
  15906. * Constructs a new shader material.
  15907. *
  15908. * @param {Object} [parameters] - An object with one or more properties
  15909. * defining the material's appearance. Any property of the material
  15910. * (including any property from inherited materials) can be passed
  15911. * in here. Color values can be passed any type of value accepted
  15912. * by {@link Color#set}.
  15913. */
  15914. constructor( parameters ) {
  15915. super();
  15916. /**
  15917. * This flag can be used for type testing.
  15918. *
  15919. * @type {boolean}
  15920. * @readonly
  15921. * @default true
  15922. */
  15923. this.isShaderMaterial = true;
  15924. this.type = 'ShaderMaterial';
  15925. /**
  15926. * Defines custom constants using `#define` directives within the GLSL code
  15927. * for both the vertex shader and the fragment shader; each key/value pair
  15928. * yields another directive.
  15929. * ```js
  15930. * defines: {
  15931. * FOO: 15,
  15932. * BAR: true
  15933. * }
  15934. * ```
  15935. * Yields the lines:
  15936. * ```
  15937. * #define FOO 15
  15938. * #define BAR true
  15939. * ```
  15940. *
  15941. * @type {Object}
  15942. */
  15943. this.defines = {};
  15944. /**
  15945. * An object of the form:
  15946. * ```js
  15947. * {
  15948. * "uniform1": { value: 1.0 },
  15949. * "uniform2": { value: 2 }
  15950. * }
  15951. * ```
  15952. * specifying the uniforms to be passed to the shader code; keys are uniform
  15953. * names, values are definitions of the form
  15954. * ```
  15955. * {
  15956. * value: 1.0
  15957. * }
  15958. * ```
  15959. * where `value` is the value of the uniform. Names must match the name of
  15960. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15961. * on every frame, so updating the value of the uniform will immediately
  15962. * update the value available to the GLSL code.
  15963. *
  15964. * @type {Object}
  15965. */
  15966. this.uniforms = {};
  15967. /**
  15968. * An array holding uniforms groups for configuring UBOs.
  15969. *
  15970. * @type {Array<UniformsGroup>}
  15971. */
  15972. this.uniformsGroups = [];
  15973. /**
  15974. * Vertex shader GLSL code. This is the actual code for the shader.
  15975. *
  15976. * @type {string}
  15977. */
  15978. this.vertexShader = default_vertex;
  15979. /**
  15980. * Fragment shader GLSL code. This is the actual code for the shader.
  15981. *
  15982. * @type {string}
  15983. */
  15984. this.fragmentShader = default_fragment;
  15985. /**
  15986. * Controls line thickness or lines.
  15987. *
  15988. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15989. * width of one pixel.
  15990. *
  15991. * @type {number}
  15992. * @default 1
  15993. */
  15994. this.linewidth = 1;
  15995. /**
  15996. * Renders the geometry as a wireframe.
  15997. *
  15998. * @type {boolean}
  15999. * @default false
  16000. */
  16001. this.wireframe = false;
  16002. /**
  16003. * Controls the thickness of the wireframe.
  16004. *
  16005. * WebGL and WebGPU ignore this property and always render
  16006. * 1 pixel wide lines.
  16007. *
  16008. * @type {number}
  16009. * @default 1
  16010. */
  16011. this.wireframeLinewidth = 1;
  16012. /**
  16013. * Defines whether the material color is affected by global fog settings; `true`
  16014. * to pass fog uniforms to the shader.
  16015. *
  16016. * Setting this property to `true` requires the definition of fog uniforms. It is
  16017. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  16018. * with predefined fog uniforms.
  16019. *
  16020. * ```js
  16021. * const material = new ShaderMaterial( {
  16022. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  16023. * vertexShader: vertexShader,
  16024. * fragmentShader: fragmentShader,
  16025. * fog: true
  16026. * } );
  16027. * ```
  16028. *
  16029. * @type {boolean}
  16030. * @default false
  16031. */
  16032. this.fog = false;
  16033. /**
  16034. * Defines whether this material uses lighting; `true` to pass uniform data
  16035. * related to lighting to this shader.
  16036. *
  16037. * @type {boolean}
  16038. * @default false
  16039. */
  16040. this.lights = false;
  16041. /**
  16042. * Defines whether this material supports clipping; `true` to let the renderer
  16043. * pass the clippingPlanes uniform.
  16044. *
  16045. * @type {boolean}
  16046. * @default false
  16047. */
  16048. this.clipping = false;
  16049. /**
  16050. * Overwritten and set to `true` by default.
  16051. *
  16052. * @type {boolean}
  16053. * @default true
  16054. */
  16055. this.forceSinglePass = true;
  16056. /**
  16057. * This object allows to enable certain WebGL 2 extensions.
  16058. *
  16059. * - clipCullDistance: set to `true` to use vertex shader clipping
  16060. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  16061. *
  16062. * @type {{clipCullDistance:false,multiDraw:false}}
  16063. */
  16064. this.extensions = {
  16065. clipCullDistance: false, // set to use vertex shader clipping
  16066. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  16067. };
  16068. /**
  16069. * When the rendered geometry doesn't include these attributes but the
  16070. * material does, these default values will be passed to the shaders. This
  16071. * avoids errors when buffer data is missing.
  16072. *
  16073. * - color: [ 1, 1, 1 ]
  16074. * - uv: [ 0, 0 ]
  16075. * - uv1: [ 0, 0 ]
  16076. *
  16077. * @type {Object}
  16078. */
  16079. this.defaultAttributeValues = {
  16080. 'color': [ 1, 1, 1 ],
  16081. 'uv': [ 0, 0 ],
  16082. 'uv1': [ 0, 0 ]
  16083. };
  16084. /**
  16085. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  16086. * to bind a generic vertex index to an attribute variable.
  16087. *
  16088. * @type {string|undefined}
  16089. * @default undefined
  16090. */
  16091. this.index0AttributeName = undefined;
  16092. /**
  16093. * Can be used to force a uniform update while changing uniforms in
  16094. * {@link Object3D#onBeforeRender}.
  16095. *
  16096. * @type {boolean}
  16097. * @default false
  16098. */
  16099. this.uniformsNeedUpdate = false;
  16100. /**
  16101. * Defines the GLSL version of custom shader code.
  16102. *
  16103. * @type {?(GLSL1|GLSL3)}
  16104. * @default null
  16105. */
  16106. this.glslVersion = null;
  16107. if ( parameters !== undefined ) {
  16108. this.setValues( parameters );
  16109. }
  16110. }
  16111. copy( source ) {
  16112. super.copy( source );
  16113. this.fragmentShader = source.fragmentShader;
  16114. this.vertexShader = source.vertexShader;
  16115. this.uniforms = cloneUniforms( source.uniforms );
  16116. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  16117. this.defines = Object.assign( {}, source.defines );
  16118. this.wireframe = source.wireframe;
  16119. this.wireframeLinewidth = source.wireframeLinewidth;
  16120. this.fog = source.fog;
  16121. this.lights = source.lights;
  16122. this.clipping = source.clipping;
  16123. this.extensions = Object.assign( {}, source.extensions );
  16124. this.glslVersion = source.glslVersion;
  16125. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  16126. this.index0AttributeName = source.index0AttributeName;
  16127. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  16128. return this;
  16129. }
  16130. toJSON( meta ) {
  16131. const data = super.toJSON( meta );
  16132. data.glslVersion = this.glslVersion;
  16133. data.uniforms = {};
  16134. for ( const name in this.uniforms ) {
  16135. const uniform = this.uniforms[ name ];
  16136. const value = uniform.value;
  16137. if ( value && value.isTexture ) {
  16138. data.uniforms[ name ] = {
  16139. type: 't',
  16140. value: value.toJSON( meta ).uuid
  16141. };
  16142. } else if ( value && value.isColor ) {
  16143. data.uniforms[ name ] = {
  16144. type: 'c',
  16145. value: value.getHex()
  16146. };
  16147. } else if ( value && value.isVector2 ) {
  16148. data.uniforms[ name ] = {
  16149. type: 'v2',
  16150. value: value.toArray()
  16151. };
  16152. } else if ( value && value.isVector3 ) {
  16153. data.uniforms[ name ] = {
  16154. type: 'v3',
  16155. value: value.toArray()
  16156. };
  16157. } else if ( value && value.isVector4 ) {
  16158. data.uniforms[ name ] = {
  16159. type: 'v4',
  16160. value: value.toArray()
  16161. };
  16162. } else if ( value && value.isMatrix3 ) {
  16163. data.uniforms[ name ] = {
  16164. type: 'm3',
  16165. value: value.toArray()
  16166. };
  16167. } else if ( value && value.isMatrix4 ) {
  16168. data.uniforms[ name ] = {
  16169. type: 'm4',
  16170. value: value.toArray()
  16171. };
  16172. } else {
  16173. data.uniforms[ name ] = {
  16174. value: value
  16175. };
  16176. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  16177. }
  16178. }
  16179. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  16180. data.vertexShader = this.vertexShader;
  16181. data.fragmentShader = this.fragmentShader;
  16182. data.lights = this.lights;
  16183. data.clipping = this.clipping;
  16184. const extensions = {};
  16185. for ( const key in this.extensions ) {
  16186. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  16187. }
  16188. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  16189. return data;
  16190. }
  16191. }
  16192. /**
  16193. * Abstract base class for cameras. This class should always be inherited
  16194. * when you build a new camera.
  16195. *
  16196. * @abstract
  16197. * @augments Object3D
  16198. */
  16199. class Camera extends Object3D {
  16200. /**
  16201. * Constructs a new camera.
  16202. */
  16203. constructor() {
  16204. super();
  16205. /**
  16206. * This flag can be used for type testing.
  16207. *
  16208. * @type {boolean}
  16209. * @readonly
  16210. * @default true
  16211. */
  16212. this.isCamera = true;
  16213. this.type = 'Camera';
  16214. /**
  16215. * The inverse of the camera's world matrix.
  16216. *
  16217. * @type {Matrix4}
  16218. */
  16219. this.matrixWorldInverse = new Matrix4();
  16220. /**
  16221. * The camera's projection matrix.
  16222. *
  16223. * @type {Matrix4}
  16224. */
  16225. this.projectionMatrix = new Matrix4();
  16226. /**
  16227. * The inverse of the camera's projection matrix.
  16228. *
  16229. * @type {Matrix4}
  16230. */
  16231. this.projectionMatrixInverse = new Matrix4();
  16232. /**
  16233. * The coordinate system in which the camera is used.
  16234. *
  16235. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16236. */
  16237. this.coordinateSystem = WebGLCoordinateSystem;
  16238. this._reversedDepth = false;
  16239. }
  16240. /**
  16241. * The flag that indicates whether the camera uses a reversed depth buffer.
  16242. *
  16243. * @type {boolean}
  16244. * @default false
  16245. */
  16246. get reversedDepth() {
  16247. return this._reversedDepth;
  16248. }
  16249. copy( source, recursive ) {
  16250. super.copy( source, recursive );
  16251. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  16252. this.projectionMatrix.copy( source.projectionMatrix );
  16253. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  16254. this.coordinateSystem = source.coordinateSystem;
  16255. return this;
  16256. }
  16257. /**
  16258. * Returns a vector representing the ("look") direction of the 3D object in world space.
  16259. *
  16260. * This method is overwritten since cameras have a different forward vector compared to other
  16261. * 3D objects. A camera looks down its local, negative z-axis by default.
  16262. *
  16263. * @param {Vector3} target - The target vector the result is stored to.
  16264. * @return {Vector3} The 3D object's direction in world space.
  16265. */
  16266. getWorldDirection( target ) {
  16267. return super.getWorldDirection( target ).negate();
  16268. }
  16269. updateMatrixWorld( force ) {
  16270. super.updateMatrixWorld( force );
  16271. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16272. }
  16273. updateWorldMatrix( updateParents, updateChildren ) {
  16274. super.updateWorldMatrix( updateParents, updateChildren );
  16275. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16276. }
  16277. clone() {
  16278. return new this.constructor().copy( this );
  16279. }
  16280. }
  16281. const _v3$1 = /*@__PURE__*/ new Vector3();
  16282. const _minTarget = /*@__PURE__*/ new Vector2();
  16283. const _maxTarget = /*@__PURE__*/ new Vector2();
  16284. /**
  16285. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  16286. *
  16287. * This projection mode is designed to mimic the way the human eye sees. It
  16288. * is the most common projection mode used for rendering a 3D scene.
  16289. *
  16290. * ```js
  16291. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  16292. * scene.add( camera );
  16293. * ```
  16294. *
  16295. * @augments Camera
  16296. */
  16297. class PerspectiveCamera extends Camera {
  16298. /**
  16299. * Constructs a new perspective camera.
  16300. *
  16301. * @param {number} [fov=50] - The vertical field of view.
  16302. * @param {number} [aspect=1] - The aspect ratio.
  16303. * @param {number} [near=0.1] - The camera's near plane.
  16304. * @param {number} [far=2000] - The camera's far plane.
  16305. */
  16306. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  16307. super();
  16308. /**
  16309. * This flag can be used for type testing.
  16310. *
  16311. * @type {boolean}
  16312. * @readonly
  16313. * @default true
  16314. */
  16315. this.isPerspectiveCamera = true;
  16316. this.type = 'PerspectiveCamera';
  16317. /**
  16318. * The vertical field of view, from bottom to top of view,
  16319. * in degrees.
  16320. *
  16321. * @type {number}
  16322. * @default 50
  16323. */
  16324. this.fov = fov;
  16325. /**
  16326. * The zoom factor of the camera.
  16327. *
  16328. * @type {number}
  16329. * @default 1
  16330. */
  16331. this.zoom = 1;
  16332. /**
  16333. * The camera's near plane. The valid range is greater than `0`
  16334. * and less than the current value of {@link PerspectiveCamera#far}.
  16335. *
  16336. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16337. * valid value for a perspective camera's near plane.
  16338. *
  16339. * @type {number}
  16340. * @default 0.1
  16341. */
  16342. this.near = near;
  16343. /**
  16344. * The camera's far plane. Must be greater than the
  16345. * current value of {@link PerspectiveCamera#near}.
  16346. *
  16347. * @type {number}
  16348. * @default 2000
  16349. */
  16350. this.far = far;
  16351. /**
  16352. * Object distance used for stereoscopy and depth-of-field effects. This
  16353. * parameter does not influence the projection matrix unless a
  16354. * {@link StereoCamera} is being used.
  16355. *
  16356. * @type {number}
  16357. * @default 10
  16358. */
  16359. this.focus = 10;
  16360. /**
  16361. * The aspect ratio, usually the canvas width / canvas height.
  16362. *
  16363. * @type {number}
  16364. * @default 1
  16365. */
  16366. this.aspect = aspect;
  16367. /**
  16368. * Represents the frustum window specification. This property should not be edited
  16369. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16370. *
  16371. * @type {?Object}
  16372. * @default null
  16373. */
  16374. this.view = null;
  16375. /**
  16376. * Film size used for the larger axis. Default is `35` (millimeters). This
  16377. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16378. * is set to a nonzero value.
  16379. *
  16380. * @type {number}
  16381. * @default 35
  16382. */
  16383. this.filmGauge = 35;
  16384. /**
  16385. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16386. *
  16387. * @type {number}
  16388. * @default 0
  16389. */
  16390. this.filmOffset = 0;
  16391. this.updateProjectionMatrix();
  16392. }
  16393. copy( source, recursive ) {
  16394. super.copy( source, recursive );
  16395. this.fov = source.fov;
  16396. this.zoom = source.zoom;
  16397. this.near = source.near;
  16398. this.far = source.far;
  16399. this.focus = source.focus;
  16400. this.aspect = source.aspect;
  16401. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16402. this.filmGauge = source.filmGauge;
  16403. this.filmOffset = source.filmOffset;
  16404. return this;
  16405. }
  16406. /**
  16407. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16408. *
  16409. * The default film gauge is 35, so that the focal length can be specified for
  16410. * a 35mm (full frame) camera.
  16411. *
  16412. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16413. */
  16414. setFocalLength( focalLength ) {
  16415. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16416. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16417. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16418. this.updateProjectionMatrix();
  16419. }
  16420. /**
  16421. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16422. * {@link PerspectiveCamera#filmGauge}.
  16423. *
  16424. * @return {number} The computed focal length.
  16425. */
  16426. getFocalLength() {
  16427. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16428. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16429. }
  16430. /**
  16431. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16432. *
  16433. * @return {number} The effective FOV.
  16434. */
  16435. getEffectiveFOV() {
  16436. return RAD2DEG * 2 * Math.atan(
  16437. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16438. }
  16439. /**
  16440. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16441. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16442. *
  16443. * @return {number} The film width.
  16444. */
  16445. getFilmWidth() {
  16446. // film not completely covered in portrait format (aspect < 1)
  16447. return this.filmGauge * Math.min( this.aspect, 1 );
  16448. }
  16449. /**
  16450. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16451. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16452. *
  16453. * @return {number} The film width.
  16454. */
  16455. getFilmHeight() {
  16456. // film not completely covered in landscape format (aspect > 1)
  16457. return this.filmGauge / Math.max( this.aspect, 1 );
  16458. }
  16459. /**
  16460. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16461. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16462. *
  16463. * @param {number} distance - The viewing distance.
  16464. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16465. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16466. */
  16467. getViewBounds( distance, minTarget, maxTarget ) {
  16468. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16469. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16470. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16471. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16472. }
  16473. /**
  16474. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16475. *
  16476. * @param {number} distance - The viewing distance.
  16477. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16478. * @returns {Vector2} The view size.
  16479. */
  16480. getViewSize( distance, target ) {
  16481. this.getViewBounds( distance, _minTarget, _maxTarget );
  16482. return target.subVectors( _maxTarget, _minTarget );
  16483. }
  16484. /**
  16485. * Sets an offset in a larger frustum. This is useful for multi-window or
  16486. * multi-monitor/multi-machine setups.
  16487. *
  16488. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16489. * the monitors are in grid like this
  16490. *```
  16491. * +---+---+---+
  16492. * | A | B | C |
  16493. * +---+---+---+
  16494. * | D | E | F |
  16495. * +---+---+---+
  16496. *```
  16497. * then for each monitor you would call it like this:
  16498. *```js
  16499. * const w = 1920;
  16500. * const h = 1080;
  16501. * const fullWidth = w * 3;
  16502. * const fullHeight = h * 2;
  16503. *
  16504. * // --A--
  16505. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16506. * // --B--
  16507. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16508. * // --C--
  16509. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16510. * // --D--
  16511. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16512. * // --E--
  16513. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16514. * // --F--
  16515. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16516. * ```
  16517. *
  16518. * Note there is no reason monitors have to be the same size or in a grid.
  16519. *
  16520. * @param {number} fullWidth - The full width of multiview setup.
  16521. * @param {number} fullHeight - The full height of multiview setup.
  16522. * @param {number} x - The horizontal offset of the subcamera.
  16523. * @param {number} y - The vertical offset of the subcamera.
  16524. * @param {number} width - The width of subcamera.
  16525. * @param {number} height - The height of subcamera.
  16526. */
  16527. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16528. this.aspect = fullWidth / fullHeight;
  16529. if ( this.view === null ) {
  16530. this.view = {
  16531. enabled: true,
  16532. fullWidth: 1,
  16533. fullHeight: 1,
  16534. offsetX: 0,
  16535. offsetY: 0,
  16536. width: 1,
  16537. height: 1
  16538. };
  16539. }
  16540. this.view.enabled = true;
  16541. this.view.fullWidth = fullWidth;
  16542. this.view.fullHeight = fullHeight;
  16543. this.view.offsetX = x;
  16544. this.view.offsetY = y;
  16545. this.view.width = width;
  16546. this.view.height = height;
  16547. this.updateProjectionMatrix();
  16548. }
  16549. /**
  16550. * Removes the view offset from the projection matrix.
  16551. */
  16552. clearViewOffset() {
  16553. if ( this.view !== null ) {
  16554. this.view.enabled = false;
  16555. }
  16556. this.updateProjectionMatrix();
  16557. }
  16558. /**
  16559. * Updates the camera's projection matrix. Must be called after any change of
  16560. * camera properties.
  16561. */
  16562. updateProjectionMatrix() {
  16563. const near = this.near;
  16564. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16565. let height = 2 * top;
  16566. let width = this.aspect * height;
  16567. let left = -0.5 * width;
  16568. const view = this.view;
  16569. if ( this.view !== null && this.view.enabled ) {
  16570. const fullWidth = view.fullWidth,
  16571. fullHeight = view.fullHeight;
  16572. left += view.offsetX * width / fullWidth;
  16573. top -= view.offsetY * height / fullHeight;
  16574. width *= view.width / fullWidth;
  16575. height *= view.height / fullHeight;
  16576. }
  16577. const skew = this.filmOffset;
  16578. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16579. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16580. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16581. }
  16582. toJSON( meta ) {
  16583. const data = super.toJSON( meta );
  16584. data.object.fov = this.fov;
  16585. data.object.zoom = this.zoom;
  16586. data.object.near = this.near;
  16587. data.object.far = this.far;
  16588. data.object.focus = this.focus;
  16589. data.object.aspect = this.aspect;
  16590. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16591. data.object.filmGauge = this.filmGauge;
  16592. data.object.filmOffset = this.filmOffset;
  16593. return data;
  16594. }
  16595. }
  16596. const fov = -90; // negative fov is not an error
  16597. const aspect = 1;
  16598. /**
  16599. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16600. * cube render target. The render target can then be used as an environment map for rendering
  16601. * realtime reflections in your scene.
  16602. *
  16603. * ```js
  16604. * // Create cube render target
  16605. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16606. *
  16607. * // Create cube camera
  16608. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16609. * scene.add( cubeCamera );
  16610. *
  16611. * // Create car
  16612. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16613. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16614. * scene.add( car );
  16615. *
  16616. * // Update the render target cube
  16617. * car.visible = false;
  16618. * cubeCamera.position.copy( car.position );
  16619. * cubeCamera.update( renderer, scene );
  16620. *
  16621. * // Render the scene
  16622. * car.visible = true;
  16623. * renderer.render( scene, camera );
  16624. * ```
  16625. *
  16626. * @augments Object3D
  16627. */
  16628. class CubeCamera extends Object3D {
  16629. /**
  16630. * Constructs a new cube camera.
  16631. *
  16632. * @param {number} near - The camera's near plane.
  16633. * @param {number} far - The camera's far plane.
  16634. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16635. */
  16636. constructor( near, far, renderTarget ) {
  16637. super();
  16638. this.type = 'CubeCamera';
  16639. /**
  16640. * A reference to the cube render target.
  16641. *
  16642. * @type {WebGLCubeRenderTarget}
  16643. */
  16644. this.renderTarget = renderTarget;
  16645. /**
  16646. * The current active coordinate system.
  16647. *
  16648. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16649. * @default null
  16650. */
  16651. this.coordinateSystem = null;
  16652. /**
  16653. * The current active mipmap level
  16654. *
  16655. * @type {number}
  16656. * @default 0
  16657. */
  16658. this.activeMipmapLevel = 0;
  16659. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16660. cameraPX.layers = this.layers;
  16661. this.add( cameraPX );
  16662. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16663. cameraNX.layers = this.layers;
  16664. this.add( cameraNX );
  16665. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16666. cameraPY.layers = this.layers;
  16667. this.add( cameraPY );
  16668. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16669. cameraNY.layers = this.layers;
  16670. this.add( cameraNY );
  16671. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16672. cameraPZ.layers = this.layers;
  16673. this.add( cameraPZ );
  16674. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16675. cameraNZ.layers = this.layers;
  16676. this.add( cameraNZ );
  16677. }
  16678. /**
  16679. * Must be called when the coordinate system of the cube camera is changed.
  16680. */
  16681. updateCoordinateSystem() {
  16682. const coordinateSystem = this.coordinateSystem;
  16683. const cameras = this.children.concat();
  16684. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16685. for ( const camera of cameras ) this.remove( camera );
  16686. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16687. cameraPX.up.set( 0, 1, 0 );
  16688. cameraPX.lookAt( 1, 0, 0 );
  16689. cameraNX.up.set( 0, 1, 0 );
  16690. cameraNX.lookAt( -1, 0, 0 );
  16691. cameraPY.up.set( 0, 0, -1 );
  16692. cameraPY.lookAt( 0, 1, 0 );
  16693. cameraNY.up.set( 0, 0, 1 );
  16694. cameraNY.lookAt( 0, -1, 0 );
  16695. cameraPZ.up.set( 0, 1, 0 );
  16696. cameraPZ.lookAt( 0, 0, 1 );
  16697. cameraNZ.up.set( 0, 1, 0 );
  16698. cameraNZ.lookAt( 0, 0, -1 );
  16699. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16700. cameraPX.up.set( 0, -1, 0 );
  16701. cameraPX.lookAt( -1, 0, 0 );
  16702. cameraNX.up.set( 0, -1, 0 );
  16703. cameraNX.lookAt( 1, 0, 0 );
  16704. cameraPY.up.set( 0, 0, 1 );
  16705. cameraPY.lookAt( 0, 1, 0 );
  16706. cameraNY.up.set( 0, 0, -1 );
  16707. cameraNY.lookAt( 0, -1, 0 );
  16708. cameraPZ.up.set( 0, -1, 0 );
  16709. cameraPZ.lookAt( 0, 0, 1 );
  16710. cameraNZ.up.set( 0, -1, 0 );
  16711. cameraNZ.lookAt( 0, 0, -1 );
  16712. } else {
  16713. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16714. }
  16715. for ( const camera of cameras ) {
  16716. this.add( camera );
  16717. camera.updateMatrixWorld();
  16718. }
  16719. }
  16720. /**
  16721. * Calling this method will render the given scene with the given renderer
  16722. * into the cube render target of the camera.
  16723. *
  16724. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16725. * @param {Scene} scene - The scene to render.
  16726. */
  16727. update( renderer, scene ) {
  16728. if ( this.parent === null ) this.updateMatrixWorld();
  16729. const { renderTarget, activeMipmapLevel } = this;
  16730. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16731. this.coordinateSystem = renderer.coordinateSystem;
  16732. this.updateCoordinateSystem();
  16733. }
  16734. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16735. const currentRenderTarget = renderer.getRenderTarget();
  16736. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16737. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16738. const currentXrEnabled = renderer.xr.enabled;
  16739. renderer.xr.enabled = false;
  16740. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16741. renderTarget.texture.generateMipmaps = false;
  16742. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16743. renderer.render( scene, cameraPX );
  16744. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16745. renderer.render( scene, cameraNX );
  16746. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16747. renderer.render( scene, cameraPY );
  16748. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16749. renderer.render( scene, cameraNY );
  16750. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16751. renderer.render( scene, cameraPZ );
  16752. // mipmaps are generated during the last call of render()
  16753. // at this point, all sides of the cube render target are defined
  16754. renderTarget.texture.generateMipmaps = generateMipmaps;
  16755. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16756. renderer.render( scene, cameraNZ );
  16757. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16758. renderer.xr.enabled = currentXrEnabled;
  16759. renderTarget.texture.needsPMREMUpdate = true;
  16760. }
  16761. }
  16762. /**
  16763. * Creates a cube texture made up of six images.
  16764. *
  16765. * ```js
  16766. * const loader = new THREE.CubeTextureLoader();
  16767. * loader.setPath( 'textures/cube/pisa/' );
  16768. *
  16769. * const textureCube = loader.load( [
  16770. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16771. * ] );
  16772. *
  16773. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16774. * ```
  16775. *
  16776. * @augments Texture
  16777. */
  16778. class CubeTexture extends Texture {
  16779. /**
  16780. * Constructs a new cube texture.
  16781. *
  16782. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16783. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16784. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16785. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16786. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16787. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16788. * @param {number} [format=RGBAFormat] - The texture format.
  16789. * @param {number} [type=UnsignedByteType] - The texture type.
  16790. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16791. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16792. */
  16793. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16794. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16795. /**
  16796. * This flag can be used for type testing.
  16797. *
  16798. * @type {boolean}
  16799. * @readonly
  16800. * @default true
  16801. */
  16802. this.isCubeTexture = true;
  16803. /**
  16804. * If set to `true`, the texture is flipped along the vertical axis when
  16805. * uploaded to the GPU.
  16806. *
  16807. * Overwritten and set to `false` by default.
  16808. *
  16809. * @type {boolean}
  16810. * @default false
  16811. */
  16812. this.flipY = false;
  16813. }
  16814. /**
  16815. * Alias for {@link CubeTexture#image}.
  16816. *
  16817. * @type {Array<Image>}
  16818. */
  16819. get images() {
  16820. return this.image;
  16821. }
  16822. set images( value ) {
  16823. this.image = value;
  16824. }
  16825. }
  16826. /**
  16827. * A cube render target used in context of {@link WebGLRenderer}.
  16828. *
  16829. * @augments WebGLRenderTarget
  16830. */
  16831. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16832. /**
  16833. * Constructs a new cube render target.
  16834. *
  16835. * @param {number} [size=1] - The size of the render target.
  16836. * @param {RenderTarget~Options} [options] - The configuration object.
  16837. */
  16838. constructor( size = 1, options = {} ) {
  16839. super( size, size, options );
  16840. /**
  16841. * This flag can be used for type testing.
  16842. *
  16843. * @type {boolean}
  16844. * @readonly
  16845. * @default true
  16846. */
  16847. this.isWebGLCubeRenderTarget = true;
  16848. const image = { width: size, height: size, depth: 1 };
  16849. const images = [ image, image, image, image, image, image ];
  16850. /**
  16851. * Overwritten with a different texture type.
  16852. *
  16853. * @type {DataArrayTexture}
  16854. */
  16855. this.texture = new CubeTexture( images );
  16856. this._setTextureOptions( options );
  16857. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16858. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16859. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16860. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16861. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16862. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16863. this.texture.isRenderTargetTexture = true;
  16864. }
  16865. /**
  16866. * Converts the given equirectangular texture to a cube map.
  16867. *
  16868. * @param {WebGLRenderer} renderer - The renderer.
  16869. * @param {Texture} texture - The equirectangular texture.
  16870. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16871. */
  16872. fromEquirectangularTexture( renderer, texture ) {
  16873. this.texture.type = texture.type;
  16874. this.texture.colorSpace = texture.colorSpace;
  16875. this.texture.generateMipmaps = texture.generateMipmaps;
  16876. this.texture.minFilter = texture.minFilter;
  16877. this.texture.magFilter = texture.magFilter;
  16878. const shader = {
  16879. uniforms: {
  16880. tEquirect: { value: null },
  16881. },
  16882. vertexShader: /* glsl */`
  16883. varying vec3 vWorldDirection;
  16884. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16885. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16886. }
  16887. void main() {
  16888. vWorldDirection = transformDirection( position, modelMatrix );
  16889. #include <begin_vertex>
  16890. #include <project_vertex>
  16891. }
  16892. `,
  16893. fragmentShader: /* glsl */`
  16894. uniform sampler2D tEquirect;
  16895. varying vec3 vWorldDirection;
  16896. #include <common>
  16897. void main() {
  16898. vec3 direction = normalize( vWorldDirection );
  16899. vec2 sampleUV = equirectUv( direction );
  16900. gl_FragColor = texture2D( tEquirect, sampleUV );
  16901. }
  16902. `
  16903. };
  16904. const geometry = new BoxGeometry( 5, 5, 5 );
  16905. const material = new ShaderMaterial( {
  16906. name: 'CubemapFromEquirect',
  16907. uniforms: cloneUniforms( shader.uniforms ),
  16908. vertexShader: shader.vertexShader,
  16909. fragmentShader: shader.fragmentShader,
  16910. side: BackSide,
  16911. blending: NoBlending
  16912. } );
  16913. material.uniforms.tEquirect.value = texture;
  16914. const mesh = new Mesh( geometry, material );
  16915. const currentMinFilter = texture.minFilter;
  16916. // Avoid blurred poles
  16917. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16918. const camera = new CubeCamera( 1, 10, this );
  16919. camera.update( renderer, mesh );
  16920. texture.minFilter = currentMinFilter;
  16921. mesh.geometry.dispose();
  16922. mesh.material.dispose();
  16923. return this;
  16924. }
  16925. /**
  16926. * Clears this cube render target.
  16927. *
  16928. * @param {WebGLRenderer} renderer - The renderer.
  16929. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16930. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16931. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16932. */
  16933. clear( renderer, color = true, depth = true, stencil = true ) {
  16934. const currentRenderTarget = renderer.getRenderTarget();
  16935. for ( let i = 0; i < 6; i ++ ) {
  16936. renderer.setRenderTarget( this, i );
  16937. renderer.clear( color, depth, stencil );
  16938. }
  16939. renderer.setRenderTarget( currentRenderTarget );
  16940. }
  16941. }
  16942. /**
  16943. * This is almost identical to an {@link Object3D}. Its purpose is to
  16944. * make working with groups of objects syntactically clearer.
  16945. *
  16946. * ```js
  16947. * // Create a group and add the two cubes.
  16948. * // These cubes can now be rotated / scaled etc as a group.
  16949. * const group = new THREE.Group();
  16950. *
  16951. * group.add( meshA );
  16952. * group.add( meshB );
  16953. *
  16954. * scene.add( group );
  16955. * ```
  16956. *
  16957. * @augments Object3D
  16958. */
  16959. class Group extends Object3D {
  16960. constructor() {
  16961. super();
  16962. /**
  16963. * This flag can be used for type testing.
  16964. *
  16965. * @type {boolean}
  16966. * @readonly
  16967. * @default true
  16968. */
  16969. this.isGroup = true;
  16970. this.type = 'Group';
  16971. }
  16972. }
  16973. const _moveEvent = { type: 'move' };
  16974. /**
  16975. * Class for representing a XR controller with its
  16976. * different coordinate systems.
  16977. *
  16978. * @private
  16979. */
  16980. class WebXRController {
  16981. /**
  16982. * Constructs a new XR controller.
  16983. */
  16984. constructor() {
  16985. /**
  16986. * A group representing the target ray space
  16987. * of the XR controller.
  16988. *
  16989. * @private
  16990. * @type {?Group}
  16991. * @default null
  16992. */
  16993. this._targetRay = null;
  16994. /**
  16995. * A group representing the grip space
  16996. * of the XR controller.
  16997. *
  16998. * @private
  16999. * @type {?Group}
  17000. * @default null
  17001. */
  17002. this._grip = null;
  17003. /**
  17004. * A group representing the hand space
  17005. * of the XR controller.
  17006. *
  17007. * @private
  17008. * @type {?Group}
  17009. * @default null
  17010. */
  17011. this._hand = null;
  17012. }
  17013. /**
  17014. * Returns a group representing the hand space of the XR controller.
  17015. *
  17016. * @return {Group} A group representing the hand space of the XR controller.
  17017. */
  17018. getHandSpace() {
  17019. if ( this._hand === null ) {
  17020. this._hand = new Group();
  17021. this._hand.matrixAutoUpdate = false;
  17022. this._hand.visible = false;
  17023. this._hand.joints = {};
  17024. this._hand.inputState = { pinching: false };
  17025. }
  17026. return this._hand;
  17027. }
  17028. /**
  17029. * Returns a group representing the target ray space of the XR controller.
  17030. *
  17031. * @return {Group} A group representing the target ray space of the XR controller.
  17032. */
  17033. getTargetRaySpace() {
  17034. if ( this._targetRay === null ) {
  17035. this._targetRay = new Group();
  17036. this._targetRay.matrixAutoUpdate = false;
  17037. this._targetRay.visible = false;
  17038. this._targetRay.hasLinearVelocity = false;
  17039. this._targetRay.linearVelocity = new Vector3();
  17040. this._targetRay.hasAngularVelocity = false;
  17041. this._targetRay.angularVelocity = new Vector3();
  17042. }
  17043. return this._targetRay;
  17044. }
  17045. /**
  17046. * Returns a group representing the grip space of the XR controller.
  17047. *
  17048. * @return {Group} A group representing the grip space of the XR controller.
  17049. */
  17050. getGripSpace() {
  17051. if ( this._grip === null ) {
  17052. this._grip = new Group();
  17053. this._grip.matrixAutoUpdate = false;
  17054. this._grip.visible = false;
  17055. this._grip.hasLinearVelocity = false;
  17056. this._grip.linearVelocity = new Vector3();
  17057. this._grip.hasAngularVelocity = false;
  17058. this._grip.angularVelocity = new Vector3();
  17059. }
  17060. return this._grip;
  17061. }
  17062. /**
  17063. * Dispatches the given event to the groups representing
  17064. * the different coordinate spaces of the XR controller.
  17065. *
  17066. * @param {Object} event - The event to dispatch.
  17067. * @return {WebXRController} A reference to this instance.
  17068. */
  17069. dispatchEvent( event ) {
  17070. if ( this._targetRay !== null ) {
  17071. this._targetRay.dispatchEvent( event );
  17072. }
  17073. if ( this._grip !== null ) {
  17074. this._grip.dispatchEvent( event );
  17075. }
  17076. if ( this._hand !== null ) {
  17077. this._hand.dispatchEvent( event );
  17078. }
  17079. return this;
  17080. }
  17081. /**
  17082. * Connects the controller with the given XR input source.
  17083. *
  17084. * @param {XRInputSource} inputSource - The input source.
  17085. * @return {WebXRController} A reference to this instance.
  17086. */
  17087. connect( inputSource ) {
  17088. if ( inputSource && inputSource.hand ) {
  17089. const hand = this._hand;
  17090. if ( hand ) {
  17091. for ( const inputjoint of inputSource.hand.values() ) {
  17092. // Initialize hand with joints when connected
  17093. this._getHandJoint( hand, inputjoint );
  17094. }
  17095. }
  17096. }
  17097. this.dispatchEvent( { type: 'connected', data: inputSource } );
  17098. return this;
  17099. }
  17100. /**
  17101. * Disconnects the controller from the given XR input source.
  17102. *
  17103. * @param {XRInputSource} inputSource - The input source.
  17104. * @return {WebXRController} A reference to this instance.
  17105. */
  17106. disconnect( inputSource ) {
  17107. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  17108. if ( this._targetRay !== null ) {
  17109. this._targetRay.visible = false;
  17110. }
  17111. if ( this._grip !== null ) {
  17112. this._grip.visible = false;
  17113. }
  17114. if ( this._hand !== null ) {
  17115. this._hand.visible = false;
  17116. }
  17117. return this;
  17118. }
  17119. /**
  17120. * Updates the controller with the given input source, XR frame and reference space.
  17121. * This updates the transformations of the groups that represent the different
  17122. * coordinate systems of the controller.
  17123. *
  17124. * @param {XRInputSource} inputSource - The input source.
  17125. * @param {XRFrame} frame - The XR frame.
  17126. * @param {XRReferenceSpace} referenceSpace - The reference space.
  17127. * @return {WebXRController} A reference to this instance.
  17128. */
  17129. update( inputSource, frame, referenceSpace ) {
  17130. let inputPose = null;
  17131. let gripPose = null;
  17132. let handPose = null;
  17133. const targetRay = this._targetRay;
  17134. const grip = this._grip;
  17135. const hand = this._hand;
  17136. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  17137. if ( hand && inputSource.hand ) {
  17138. handPose = true;
  17139. for ( const inputjoint of inputSource.hand.values() ) {
  17140. // Update the joints groups with the XRJoint poses
  17141. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  17142. // The transform of this joint will be updated with the joint pose on each frame
  17143. const joint = this._getHandJoint( hand, inputjoint );
  17144. if ( jointPose !== null ) {
  17145. joint.matrix.fromArray( jointPose.transform.matrix );
  17146. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  17147. joint.matrixWorldNeedsUpdate = true;
  17148. joint.jointRadius = jointPose.radius;
  17149. }
  17150. joint.visible = jointPose !== null;
  17151. }
  17152. // Custom events
  17153. // Check pinchz
  17154. const indexTip = hand.joints[ 'index-finger-tip' ];
  17155. const thumbTip = hand.joints[ 'thumb-tip' ];
  17156. const distance = indexTip.position.distanceTo( thumbTip.position );
  17157. const distanceToPinch = 0.02;
  17158. const threshold = 0.005;
  17159. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  17160. hand.inputState.pinching = false;
  17161. this.dispatchEvent( {
  17162. type: 'pinchend',
  17163. handedness: inputSource.handedness,
  17164. target: this
  17165. } );
  17166. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  17167. hand.inputState.pinching = true;
  17168. this.dispatchEvent( {
  17169. type: 'pinchstart',
  17170. handedness: inputSource.handedness,
  17171. target: this
  17172. } );
  17173. }
  17174. } else {
  17175. if ( grip !== null && inputSource.gripSpace ) {
  17176. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  17177. if ( gripPose !== null ) {
  17178. grip.matrix.fromArray( gripPose.transform.matrix );
  17179. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  17180. grip.matrixWorldNeedsUpdate = true;
  17181. if ( gripPose.linearVelocity ) {
  17182. grip.hasLinearVelocity = true;
  17183. grip.linearVelocity.copy( gripPose.linearVelocity );
  17184. } else {
  17185. grip.hasLinearVelocity = false;
  17186. }
  17187. if ( gripPose.angularVelocity ) {
  17188. grip.hasAngularVelocity = true;
  17189. grip.angularVelocity.copy( gripPose.angularVelocity );
  17190. } else {
  17191. grip.hasAngularVelocity = false;
  17192. }
  17193. }
  17194. }
  17195. }
  17196. if ( targetRay !== null ) {
  17197. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  17198. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  17199. if ( inputPose === null && gripPose !== null ) {
  17200. inputPose = gripPose;
  17201. }
  17202. if ( inputPose !== null ) {
  17203. targetRay.matrix.fromArray( inputPose.transform.matrix );
  17204. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  17205. targetRay.matrixWorldNeedsUpdate = true;
  17206. if ( inputPose.linearVelocity ) {
  17207. targetRay.hasLinearVelocity = true;
  17208. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  17209. } else {
  17210. targetRay.hasLinearVelocity = false;
  17211. }
  17212. if ( inputPose.angularVelocity ) {
  17213. targetRay.hasAngularVelocity = true;
  17214. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  17215. } else {
  17216. targetRay.hasAngularVelocity = false;
  17217. }
  17218. this.dispatchEvent( _moveEvent );
  17219. }
  17220. }
  17221. }
  17222. if ( targetRay !== null ) {
  17223. targetRay.visible = ( inputPose !== null );
  17224. }
  17225. if ( grip !== null ) {
  17226. grip.visible = ( gripPose !== null );
  17227. }
  17228. if ( hand !== null ) {
  17229. hand.visible = ( handPose !== null );
  17230. }
  17231. return this;
  17232. }
  17233. /**
  17234. * Returns a group representing the hand joint for the given input joint.
  17235. *
  17236. * @private
  17237. * @param {Group} hand - The group representing the hand space.
  17238. * @param {XRJointSpace} inputjoint - The hand joint data.
  17239. * @return {Group} A group representing the hand joint for the given input joint.
  17240. */
  17241. _getHandJoint( hand, inputjoint ) {
  17242. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  17243. const joint = new Group();
  17244. joint.matrixAutoUpdate = false;
  17245. joint.visible = false;
  17246. hand.joints[ inputjoint.jointName ] = joint;
  17247. hand.add( joint );
  17248. }
  17249. return hand.joints[ inputjoint.jointName ];
  17250. }
  17251. }
  17252. /**
  17253. * This class can be used to define an exponential squared fog,
  17254. * which gives a clear view near the camera and a faster than exponentially
  17255. * densening fog farther from the camera.
  17256. *
  17257. * ```js
  17258. * const scene = new THREE.Scene();
  17259. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  17260. * ```
  17261. */
  17262. class FogExp2 {
  17263. /**
  17264. * Constructs a new fog.
  17265. *
  17266. * @param {number|Color} color - The fog's color.
  17267. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  17268. */
  17269. constructor( color, density = 0.00025 ) {
  17270. /**
  17271. * This flag can be used for type testing.
  17272. *
  17273. * @type {boolean}
  17274. * @readonly
  17275. * @default true
  17276. */
  17277. this.isFogExp2 = true;
  17278. /**
  17279. * The name of the fog.
  17280. *
  17281. * @type {string}
  17282. */
  17283. this.name = '';
  17284. /**
  17285. * The fog's color.
  17286. *
  17287. * @type {Color}
  17288. */
  17289. this.color = new Color( color );
  17290. /**
  17291. * Defines how fast the fog will grow dense.
  17292. *
  17293. * @type {number}
  17294. * @default 0.00025
  17295. */
  17296. this.density = density;
  17297. }
  17298. /**
  17299. * Returns a new fog with copied values from this instance.
  17300. *
  17301. * @return {FogExp2} A clone of this instance.
  17302. */
  17303. clone() {
  17304. return new FogExp2( this.color, this.density );
  17305. }
  17306. /**
  17307. * Serializes the fog into JSON.
  17308. *
  17309. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17310. * @return {Object} A JSON object representing the serialized fog
  17311. */
  17312. toJSON( /* meta */ ) {
  17313. return {
  17314. type: 'FogExp2',
  17315. name: this.name,
  17316. color: this.color.getHex(),
  17317. density: this.density
  17318. };
  17319. }
  17320. }
  17321. /**
  17322. * This class can be used to define a linear fog that grows linearly denser
  17323. * with the distance.
  17324. *
  17325. * ```js
  17326. * const scene = new THREE.Scene();
  17327. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17328. * ```
  17329. */
  17330. class Fog {
  17331. /**
  17332. * Constructs a new fog.
  17333. *
  17334. * @param {number|Color} color - The fog's color.
  17335. * @param {number} [near=1] - The minimum distance to start applying fog.
  17336. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17337. */
  17338. constructor( color, near = 1, far = 1000 ) {
  17339. /**
  17340. * This flag can be used for type testing.
  17341. *
  17342. * @type {boolean}
  17343. * @readonly
  17344. * @default true
  17345. */
  17346. this.isFog = true;
  17347. /**
  17348. * The name of the fog.
  17349. *
  17350. * @type {string}
  17351. */
  17352. this.name = '';
  17353. /**
  17354. * The fog's color.
  17355. *
  17356. * @type {Color}
  17357. */
  17358. this.color = new Color( color );
  17359. /**
  17360. * The minimum distance to start applying fog. Objects that are less than
  17361. * `near` units from the active camera won't be affected by fog.
  17362. *
  17363. * @type {number}
  17364. * @default 1
  17365. */
  17366. this.near = near;
  17367. /**
  17368. * The maximum distance at which fog stops being calculated and applied.
  17369. * Objects that are more than `far` units away from the active camera won't
  17370. * be affected by fog.
  17371. *
  17372. * @type {number}
  17373. * @default 1000
  17374. */
  17375. this.far = far;
  17376. }
  17377. /**
  17378. * Returns a new fog with copied values from this instance.
  17379. *
  17380. * @return {Fog} A clone of this instance.
  17381. */
  17382. clone() {
  17383. return new Fog( this.color, this.near, this.far );
  17384. }
  17385. /**
  17386. * Serializes the fog into JSON.
  17387. *
  17388. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17389. * @return {Object} A JSON object representing the serialized fog
  17390. */
  17391. toJSON( /* meta */ ) {
  17392. return {
  17393. type: 'Fog',
  17394. name: this.name,
  17395. color: this.color.getHex(),
  17396. near: this.near,
  17397. far: this.far
  17398. };
  17399. }
  17400. }
  17401. /**
  17402. * Scenes allow you to set up what is to be rendered and where by three.js.
  17403. * This is where you place 3D objects like meshes, lines or lights.
  17404. *
  17405. * @augments Object3D
  17406. */
  17407. class Scene extends Object3D {
  17408. /**
  17409. * Constructs a new scene.
  17410. */
  17411. constructor() {
  17412. super();
  17413. /**
  17414. * This flag can be used for type testing.
  17415. *
  17416. * @type {boolean}
  17417. * @readonly
  17418. * @default true
  17419. */
  17420. this.isScene = true;
  17421. this.type = 'Scene';
  17422. /**
  17423. * Defines the background of the scene. Valid inputs are:
  17424. *
  17425. * - A color for defining a uniform colored background.
  17426. * - A texture for defining a (flat) textured background.
  17427. * - Cube textures or equirectangular textures for defining a skybox.
  17428. *
  17429. * @type {?(Color|Texture)}
  17430. * @default null
  17431. */
  17432. this.background = null;
  17433. /**
  17434. * Sets the environment map for all physical materials in the scene. However,
  17435. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17436. * material property.
  17437. *
  17438. * @type {?Texture}
  17439. * @default null
  17440. */
  17441. this.environment = null;
  17442. /**
  17443. * A fog instance defining the type of fog that affects everything
  17444. * rendered in the scene.
  17445. *
  17446. * @type {?(Fog|FogExp2)}
  17447. * @default null
  17448. */
  17449. this.fog = null;
  17450. /**
  17451. * Sets the blurriness of the background. Only influences environment maps
  17452. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17453. * and `1`.
  17454. *
  17455. * @type {number}
  17456. * @default 0
  17457. */
  17458. this.backgroundBlurriness = 0;
  17459. /**
  17460. * Attenuates the color of the background. Only applies to background textures.
  17461. *
  17462. * @type {number}
  17463. * @default 1
  17464. */
  17465. this.backgroundIntensity = 1;
  17466. /**
  17467. * The rotation of the background in radians. Only influences environment maps
  17468. * assigned to {@link Scene#background}.
  17469. *
  17470. * @type {Euler}
  17471. * @default (0,0,0)
  17472. */
  17473. this.backgroundRotation = new Euler();
  17474. /**
  17475. * Attenuates the color of the environment. Only influences environment maps
  17476. * assigned to {@link Scene#environment}.
  17477. *
  17478. * @type {number}
  17479. * @default 1
  17480. */
  17481. this.environmentIntensity = 1;
  17482. /**
  17483. * The rotation of the environment map in radians. Only influences physical materials
  17484. * in the scene when {@link Scene#environment} is used.
  17485. *
  17486. * @type {Euler}
  17487. * @default (0,0,0)
  17488. */
  17489. this.environmentRotation = new Euler();
  17490. /**
  17491. * Forces everything in the scene to be rendered with the defined material. It is possible
  17492. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17493. *
  17494. * @type {?Material}
  17495. * @default null
  17496. */
  17497. this.overrideMaterial = null;
  17498. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17499. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17500. }
  17501. }
  17502. copy( source, recursive ) {
  17503. super.copy( source, recursive );
  17504. if ( source.background !== null ) this.background = source.background.clone();
  17505. if ( source.environment !== null ) this.environment = source.environment.clone();
  17506. if ( source.fog !== null ) this.fog = source.fog.clone();
  17507. this.backgroundBlurriness = source.backgroundBlurriness;
  17508. this.backgroundIntensity = source.backgroundIntensity;
  17509. this.backgroundRotation.copy( source.backgroundRotation );
  17510. this.environmentIntensity = source.environmentIntensity;
  17511. this.environmentRotation.copy( source.environmentRotation );
  17512. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17513. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17514. return this;
  17515. }
  17516. toJSON( meta ) {
  17517. const data = super.toJSON( meta );
  17518. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17519. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17520. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17521. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17522. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17523. data.object.environmentRotation = this.environmentRotation.toArray();
  17524. return data;
  17525. }
  17526. }
  17527. /**
  17528. * "Interleaved" means that multiple attributes, possibly of different types,
  17529. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17530. *
  17531. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  17532. */
  17533. class InterleavedBuffer {
  17534. /**
  17535. * Constructs a new interleaved buffer.
  17536. *
  17537. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17538. * @param {number} stride - The number of typed-array elements per vertex.
  17539. */
  17540. constructor( array, stride ) {
  17541. /**
  17542. * This flag can be used for type testing.
  17543. *
  17544. * @type {boolean}
  17545. * @readonly
  17546. * @default true
  17547. */
  17548. this.isInterleavedBuffer = true;
  17549. /**
  17550. * A typed array with a shared buffer storing attribute data.
  17551. *
  17552. * @type {TypedArray}
  17553. */
  17554. this.array = array;
  17555. /**
  17556. * The number of typed-array elements per vertex.
  17557. *
  17558. * @type {number}
  17559. */
  17560. this.stride = stride;
  17561. /**
  17562. * The total number of elements in the array
  17563. *
  17564. * @type {number}
  17565. * @readonly
  17566. */
  17567. this.count = array !== undefined ? array.length / stride : 0;
  17568. /**
  17569. * Defines the intended usage pattern of the data store for optimization purposes.
  17570. *
  17571. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17572. * instantiate a new one and set the desired usage before the next render.
  17573. *
  17574. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17575. * @default StaticDrawUsage
  17576. */
  17577. this.usage = StaticDrawUsage;
  17578. /**
  17579. * This can be used to only update some components of stored vectors (for example, just the
  17580. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17581. *
  17582. * @type {Array<Object>}
  17583. */
  17584. this.updateRanges = [];
  17585. /**
  17586. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17587. *
  17588. * @type {number}
  17589. */
  17590. this.version = 0;
  17591. /**
  17592. * The UUID of the interleaved buffer.
  17593. *
  17594. * @type {string}
  17595. * @readonly
  17596. */
  17597. this.uuid = generateUUID();
  17598. }
  17599. /**
  17600. * A callback function that is executed after the renderer has transferred the attribute array
  17601. * data to the GPU.
  17602. */
  17603. onUploadCallback() {}
  17604. /**
  17605. * Flag to indicate that this attribute has changed and should be re-sent to
  17606. * the GPU. Set this to `true` when you modify the value of the array.
  17607. *
  17608. * @type {number}
  17609. * @default false
  17610. * @param {boolean} value
  17611. */
  17612. set needsUpdate( value ) {
  17613. if ( value === true ) this.version ++;
  17614. }
  17615. /**
  17616. * Sets the usage of this interleaved buffer.
  17617. *
  17618. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17619. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17620. */
  17621. setUsage( value ) {
  17622. this.usage = value;
  17623. return this;
  17624. }
  17625. /**
  17626. * Adds a range of data in the data array to be updated on the GPU.
  17627. *
  17628. * @param {number} start - Position at which to start update.
  17629. * @param {number} count - The number of components to update.
  17630. */
  17631. addUpdateRange( start, count ) {
  17632. this.updateRanges.push( { start, count } );
  17633. }
  17634. /**
  17635. * Clears the update ranges.
  17636. */
  17637. clearUpdateRanges() {
  17638. this.updateRanges.length = 0;
  17639. }
  17640. /**
  17641. * Copies the values of the given interleaved buffer to this instance.
  17642. *
  17643. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17644. * @return {InterleavedBuffer} A reference to this instance.
  17645. */
  17646. copy( source ) {
  17647. this.array = new source.array.constructor( source.array );
  17648. this.count = source.count;
  17649. this.stride = source.stride;
  17650. this.usage = source.usage;
  17651. return this;
  17652. }
  17653. /**
  17654. * Copies a vector from the given interleaved buffer to this one. The start
  17655. * and destination position in the attribute buffers are represented by the
  17656. * given indices.
  17657. *
  17658. * @param {number} index1 - The destination index into this interleaved buffer.
  17659. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17660. * @param {number} index2 - The source index into the given interleaved buffer.
  17661. * @return {InterleavedBuffer} A reference to this instance.
  17662. */
  17663. copyAt( index1, interleavedBuffer, index2 ) {
  17664. index1 *= this.stride;
  17665. index2 *= interleavedBuffer.stride;
  17666. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17667. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17668. }
  17669. return this;
  17670. }
  17671. /**
  17672. * Sets the given array data in the interleaved buffer.
  17673. *
  17674. * @param {(TypedArray|Array)} value - The array data to set.
  17675. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17676. * @return {InterleavedBuffer} A reference to this instance.
  17677. */
  17678. set( value, offset = 0 ) {
  17679. this.array.set( value, offset );
  17680. return this;
  17681. }
  17682. /**
  17683. * Returns a new interleaved buffer with copied values from this instance.
  17684. *
  17685. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17686. * @return {InterleavedBuffer} A clone of this instance.
  17687. */
  17688. clone( data ) {
  17689. if ( data.arrayBuffers === undefined ) {
  17690. data.arrayBuffers = {};
  17691. }
  17692. if ( this.array.buffer._uuid === undefined ) {
  17693. this.array.buffer._uuid = generateUUID();
  17694. }
  17695. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17696. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17697. }
  17698. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17699. const ib = new this.constructor( array, this.stride );
  17700. ib.setUsage( this.usage );
  17701. return ib;
  17702. }
  17703. /**
  17704. * Sets the given callback function that is executed after the Renderer has transferred
  17705. * the array data to the GPU. Can be used to perform clean-up operations after
  17706. * the upload when data are not needed anymore on the CPU side.
  17707. *
  17708. * @param {Function} callback - The `onUpload()` callback.
  17709. * @return {InterleavedBuffer} A reference to this instance.
  17710. */
  17711. onUpload( callback ) {
  17712. this.onUploadCallback = callback;
  17713. return this;
  17714. }
  17715. /**
  17716. * Serializes the interleaved buffer into JSON.
  17717. *
  17718. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17719. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17720. */
  17721. toJSON( data ) {
  17722. if ( data.arrayBuffers === undefined ) {
  17723. data.arrayBuffers = {};
  17724. }
  17725. // generate UUID for array buffer if necessary
  17726. if ( this.array.buffer._uuid === undefined ) {
  17727. this.array.buffer._uuid = generateUUID();
  17728. }
  17729. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17730. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17731. }
  17732. //
  17733. return {
  17734. uuid: this.uuid,
  17735. buffer: this.array.buffer._uuid,
  17736. type: this.array.constructor.name,
  17737. stride: this.stride
  17738. };
  17739. }
  17740. }
  17741. const _vector$7 = /*@__PURE__*/ new Vector3();
  17742. /**
  17743. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17744. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17745. * different offsets into the buffer.
  17746. */
  17747. class InterleavedBufferAttribute {
  17748. /**
  17749. * Constructs a new interleaved buffer attribute.
  17750. *
  17751. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17752. * @param {number} itemSize - The item size.
  17753. * @param {number} offset - The attribute offset into the buffer.
  17754. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17755. */
  17756. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17757. /**
  17758. * This flag can be used for type testing.
  17759. *
  17760. * @type {boolean}
  17761. * @readonly
  17762. * @default true
  17763. */
  17764. this.isInterleavedBufferAttribute = true;
  17765. /**
  17766. * The name of the buffer attribute.
  17767. *
  17768. * @type {string}
  17769. */
  17770. this.name = '';
  17771. /**
  17772. * The buffer holding the interleaved data.
  17773. *
  17774. * @type {InterleavedBuffer}
  17775. */
  17776. this.data = interleavedBuffer;
  17777. /**
  17778. * The item size, see {@link BufferAttribute#itemSize}.
  17779. *
  17780. * @type {number}
  17781. */
  17782. this.itemSize = itemSize;
  17783. /**
  17784. * The attribute offset into the buffer.
  17785. *
  17786. * @type {number}
  17787. */
  17788. this.offset = offset;
  17789. /**
  17790. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17791. *
  17792. * @type {InterleavedBuffer}
  17793. */
  17794. this.normalized = normalized;
  17795. }
  17796. /**
  17797. * The item count of this buffer attribute.
  17798. *
  17799. * @type {number}
  17800. * @readonly
  17801. */
  17802. get count() {
  17803. return this.data.count;
  17804. }
  17805. /**
  17806. * The array holding the interleaved buffer attribute data.
  17807. *
  17808. * @type {TypedArray}
  17809. */
  17810. get array() {
  17811. return this.data.array;
  17812. }
  17813. /**
  17814. * Flag to indicate that this attribute has changed and should be re-sent to
  17815. * the GPU. Set this to `true` when you modify the value of the array.
  17816. *
  17817. * @type {number}
  17818. * @default false
  17819. * @param {boolean} value
  17820. */
  17821. set needsUpdate( value ) {
  17822. this.data.needsUpdate = value;
  17823. }
  17824. /**
  17825. * Applies the given 4x4 matrix to the given attribute. Only works with
  17826. * item size `3`.
  17827. *
  17828. * @param {Matrix4} m - The matrix to apply.
  17829. * @return {InterleavedBufferAttribute} A reference to this instance.
  17830. */
  17831. applyMatrix4( m ) {
  17832. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17833. _vector$7.fromBufferAttribute( this, i );
  17834. _vector$7.applyMatrix4( m );
  17835. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17836. }
  17837. return this;
  17838. }
  17839. /**
  17840. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17841. * item size `3`.
  17842. *
  17843. * @param {Matrix3} m - The normal matrix to apply.
  17844. * @return {InterleavedBufferAttribute} A reference to this instance.
  17845. */
  17846. applyNormalMatrix( m ) {
  17847. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17848. _vector$7.fromBufferAttribute( this, i );
  17849. _vector$7.applyNormalMatrix( m );
  17850. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17851. }
  17852. return this;
  17853. }
  17854. /**
  17855. * Applies the given 4x4 matrix to the given attribute. Only works with
  17856. * item size `3` and with direction vectors.
  17857. *
  17858. * @param {Matrix4} m - The matrix to apply.
  17859. * @return {InterleavedBufferAttribute} A reference to this instance.
  17860. */
  17861. transformDirection( m ) {
  17862. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17863. _vector$7.fromBufferAttribute( this, i );
  17864. _vector$7.transformDirection( m );
  17865. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17866. }
  17867. return this;
  17868. }
  17869. /**
  17870. * Returns the given component of the vector at the given index.
  17871. *
  17872. * @param {number} index - The index into the buffer attribute.
  17873. * @param {number} component - The component index.
  17874. * @return {number} The returned value.
  17875. */
  17876. getComponent( index, component ) {
  17877. let value = this.array[ index * this.data.stride + this.offset + component ];
  17878. if ( this.normalized ) value = denormalize( value, this.array );
  17879. return value;
  17880. }
  17881. /**
  17882. * Sets the given value to the given component of the vector at the given index.
  17883. *
  17884. * @param {number} index - The index into the buffer attribute.
  17885. * @param {number} component - The component index.
  17886. * @param {number} value - The value to set.
  17887. * @return {InterleavedBufferAttribute} A reference to this instance.
  17888. */
  17889. setComponent( index, component, value ) {
  17890. if ( this.normalized ) value = normalize( value, this.array );
  17891. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17892. return this;
  17893. }
  17894. /**
  17895. * Sets the x component of the vector at the given index.
  17896. *
  17897. * @param {number} index - The index into the buffer attribute.
  17898. * @param {number} x - The value to set.
  17899. * @return {InterleavedBufferAttribute} A reference to this instance.
  17900. */
  17901. setX( index, x ) {
  17902. if ( this.normalized ) x = normalize( x, this.array );
  17903. this.data.array[ index * this.data.stride + this.offset ] = x;
  17904. return this;
  17905. }
  17906. /**
  17907. * Sets the y component of the vector at the given index.
  17908. *
  17909. * @param {number} index - The index into the buffer attribute.
  17910. * @param {number} y - The value to set.
  17911. * @return {InterleavedBufferAttribute} A reference to this instance.
  17912. */
  17913. setY( index, y ) {
  17914. if ( this.normalized ) y = normalize( y, this.array );
  17915. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17916. return this;
  17917. }
  17918. /**
  17919. * Sets the z component of the vector at the given index.
  17920. *
  17921. * @param {number} index - The index into the buffer attribute.
  17922. * @param {number} z - The value to set.
  17923. * @return {InterleavedBufferAttribute} A reference to this instance.
  17924. */
  17925. setZ( index, z ) {
  17926. if ( this.normalized ) z = normalize( z, this.array );
  17927. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17928. return this;
  17929. }
  17930. /**
  17931. * Sets the w component of the vector at the given index.
  17932. *
  17933. * @param {number} index - The index into the buffer attribute.
  17934. * @param {number} w - The value to set.
  17935. * @return {InterleavedBufferAttribute} A reference to this instance.
  17936. */
  17937. setW( index, w ) {
  17938. if ( this.normalized ) w = normalize( w, this.array );
  17939. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17940. return this;
  17941. }
  17942. /**
  17943. * Returns the x component of the vector at the given index.
  17944. *
  17945. * @param {number} index - The index into the buffer attribute.
  17946. * @return {number} The x component.
  17947. */
  17948. getX( index ) {
  17949. let x = this.data.array[ index * this.data.stride + this.offset ];
  17950. if ( this.normalized ) x = denormalize( x, this.array );
  17951. return x;
  17952. }
  17953. /**
  17954. * Returns the y component of the vector at the given index.
  17955. *
  17956. * @param {number} index - The index into the buffer attribute.
  17957. * @return {number} The y component.
  17958. */
  17959. getY( index ) {
  17960. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17961. if ( this.normalized ) y = denormalize( y, this.array );
  17962. return y;
  17963. }
  17964. /**
  17965. * Returns the z component of the vector at the given index.
  17966. *
  17967. * @param {number} index - The index into the buffer attribute.
  17968. * @return {number} The z component.
  17969. */
  17970. getZ( index ) {
  17971. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17972. if ( this.normalized ) z = denormalize( z, this.array );
  17973. return z;
  17974. }
  17975. /**
  17976. * Returns the w component of the vector at the given index.
  17977. *
  17978. * @param {number} index - The index into the buffer attribute.
  17979. * @return {number} The w component.
  17980. */
  17981. getW( index ) {
  17982. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17983. if ( this.normalized ) w = denormalize( w, this.array );
  17984. return w;
  17985. }
  17986. /**
  17987. * Sets the x and y component of the vector at the given index.
  17988. *
  17989. * @param {number} index - The index into the buffer attribute.
  17990. * @param {number} x - The value for the x component to set.
  17991. * @param {number} y - The value for the y component to set.
  17992. * @return {InterleavedBufferAttribute} A reference to this instance.
  17993. */
  17994. setXY( index, x, y ) {
  17995. index = index * this.data.stride + this.offset;
  17996. if ( this.normalized ) {
  17997. x = normalize( x, this.array );
  17998. y = normalize( y, this.array );
  17999. }
  18000. this.data.array[ index + 0 ] = x;
  18001. this.data.array[ index + 1 ] = y;
  18002. return this;
  18003. }
  18004. /**
  18005. * Sets the x, y and z component of the vector at the given index.
  18006. *
  18007. * @param {number} index - The index into the buffer attribute.
  18008. * @param {number} x - The value for the x component to set.
  18009. * @param {number} y - The value for the y component to set.
  18010. * @param {number} z - The value for the z component to set.
  18011. * @return {InterleavedBufferAttribute} A reference to this instance.
  18012. */
  18013. setXYZ( index, x, y, z ) {
  18014. index = index * this.data.stride + this.offset;
  18015. if ( this.normalized ) {
  18016. x = normalize( x, this.array );
  18017. y = normalize( y, this.array );
  18018. z = normalize( z, this.array );
  18019. }
  18020. this.data.array[ index + 0 ] = x;
  18021. this.data.array[ index + 1 ] = y;
  18022. this.data.array[ index + 2 ] = z;
  18023. return this;
  18024. }
  18025. /**
  18026. * Sets the x, y, z and w component of the vector at the given index.
  18027. *
  18028. * @param {number} index - The index into the buffer attribute.
  18029. * @param {number} x - The value for the x component to set.
  18030. * @param {number} y - The value for the y component to set.
  18031. * @param {number} z - The value for the z component to set.
  18032. * @param {number} w - The value for the w component to set.
  18033. * @return {InterleavedBufferAttribute} A reference to this instance.
  18034. */
  18035. setXYZW( index, x, y, z, w ) {
  18036. index = index * this.data.stride + this.offset;
  18037. if ( this.normalized ) {
  18038. x = normalize( x, this.array );
  18039. y = normalize( y, this.array );
  18040. z = normalize( z, this.array );
  18041. w = normalize( w, this.array );
  18042. }
  18043. this.data.array[ index + 0 ] = x;
  18044. this.data.array[ index + 1 ] = y;
  18045. this.data.array[ index + 2 ] = z;
  18046. this.data.array[ index + 3 ] = w;
  18047. return this;
  18048. }
  18049. /**
  18050. * Returns a new buffer attribute with copied values from this instance.
  18051. *
  18052. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  18053. *
  18054. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  18055. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  18056. */
  18057. clone( data ) {
  18058. if ( data === undefined ) {
  18059. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18060. const array = [];
  18061. for ( let i = 0; i < this.count; i ++ ) {
  18062. const index = i * this.data.stride + this.offset;
  18063. for ( let j = 0; j < this.itemSize; j ++ ) {
  18064. array.push( this.data.array[ index + j ] );
  18065. }
  18066. }
  18067. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18068. } else {
  18069. if ( data.interleavedBuffers === undefined ) {
  18070. data.interleavedBuffers = {};
  18071. }
  18072. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18073. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18074. }
  18075. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18076. }
  18077. }
  18078. /**
  18079. * Serializes the buffer attribute into JSON.
  18080. *
  18081. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  18082. *
  18083. * @param {Object} [data] - An optional value holding meta information about the serialization.
  18084. * @return {Object} A JSON object representing the serialized buffer attribute.
  18085. */
  18086. toJSON( data ) {
  18087. if ( data === undefined ) {
  18088. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18089. const array = [];
  18090. for ( let i = 0; i < this.count; i ++ ) {
  18091. const index = i * this.data.stride + this.offset;
  18092. for ( let j = 0; j < this.itemSize; j ++ ) {
  18093. array.push( this.data.array[ index + j ] );
  18094. }
  18095. }
  18096. // de-interleave data and save it as an ordinary buffer attribute for now
  18097. return {
  18098. itemSize: this.itemSize,
  18099. type: this.array.constructor.name,
  18100. array: array,
  18101. normalized: this.normalized
  18102. };
  18103. } else {
  18104. // save as true interleaved attribute
  18105. if ( data.interleavedBuffers === undefined ) {
  18106. data.interleavedBuffers = {};
  18107. }
  18108. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18109. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18110. }
  18111. return {
  18112. isInterleavedBufferAttribute: true,
  18113. itemSize: this.itemSize,
  18114. data: this.data.uuid,
  18115. offset: this.offset,
  18116. normalized: this.normalized
  18117. };
  18118. }
  18119. }
  18120. }
  18121. /**
  18122. * A material for rendering instances of {@link Sprite}.
  18123. *
  18124. * ```js
  18125. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  18126. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  18127. *
  18128. * const sprite = new THREE.Sprite( material );
  18129. * sprite.scale.set(200, 200, 1)
  18130. * scene.add( sprite );
  18131. * ```
  18132. *
  18133. * @augments Material
  18134. */
  18135. class SpriteMaterial extends Material {
  18136. /**
  18137. * Constructs a new sprite material.
  18138. *
  18139. * @param {Object} [parameters] - An object with one or more properties
  18140. * defining the material's appearance. Any property of the material
  18141. * (including any property from inherited materials) can be passed
  18142. * in here. Color values can be passed any type of value accepted
  18143. * by {@link Color#set}.
  18144. */
  18145. constructor( parameters ) {
  18146. super();
  18147. /**
  18148. * This flag can be used for type testing.
  18149. *
  18150. * @type {boolean}
  18151. * @readonly
  18152. * @default true
  18153. */
  18154. this.isSpriteMaterial = true;
  18155. this.type = 'SpriteMaterial';
  18156. /**
  18157. * Color of the material.
  18158. *
  18159. * @type {Color}
  18160. * @default (1,1,1)
  18161. */
  18162. this.color = new Color( 0xffffff );
  18163. /**
  18164. * The color map. May optionally include an alpha channel, typically combined
  18165. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  18166. * color is modulated by the diffuse `color`.
  18167. *
  18168. * @type {?Texture}
  18169. * @default null
  18170. */
  18171. this.map = null;
  18172. /**
  18173. * The alpha map is a grayscale texture that controls the opacity across the
  18174. * surface (black: fully transparent; white: fully opaque).
  18175. *
  18176. * Only the color of the texture is used, ignoring the alpha channel if one
  18177. * exists. For RGB and RGBA textures, the renderer will use the green channel
  18178. * when sampling this texture due to the extra bit of precision provided for
  18179. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  18180. * luminance/alpha textures will also still work as expected.
  18181. *
  18182. * @type {?Texture}
  18183. * @default null
  18184. */
  18185. this.alphaMap = null;
  18186. /**
  18187. * The rotation of the sprite in radians.
  18188. *
  18189. * @type {number}
  18190. * @default 0
  18191. */
  18192. this.rotation = 0;
  18193. /**
  18194. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  18195. *
  18196. * @type {boolean}
  18197. * @default true
  18198. */
  18199. this.sizeAttenuation = true;
  18200. /**
  18201. * Overwritten since sprite materials are transparent
  18202. * by default.
  18203. *
  18204. * @type {boolean}
  18205. * @default true
  18206. */
  18207. this.transparent = true;
  18208. /**
  18209. * Whether the material is affected by fog or not.
  18210. *
  18211. * @type {boolean}
  18212. * @default true
  18213. */
  18214. this.fog = true;
  18215. this.setValues( parameters );
  18216. }
  18217. copy( source ) {
  18218. super.copy( source );
  18219. this.color.copy( source.color );
  18220. this.map = source.map;
  18221. this.alphaMap = source.alphaMap;
  18222. this.rotation = source.rotation;
  18223. this.sizeAttenuation = source.sizeAttenuation;
  18224. this.fog = source.fog;
  18225. return this;
  18226. }
  18227. }
  18228. let _geometry;
  18229. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18230. const _worldScale = /*@__PURE__*/ new Vector3();
  18231. const _mvPosition = /*@__PURE__*/ new Vector3();
  18232. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18233. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18234. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18235. const _vA = /*@__PURE__*/ new Vector3();
  18236. const _vB = /*@__PURE__*/ new Vector3();
  18237. const _vC = /*@__PURE__*/ new Vector3();
  18238. const _uvA = /*@__PURE__*/ new Vector2();
  18239. const _uvB = /*@__PURE__*/ new Vector2();
  18240. const _uvC = /*@__PURE__*/ new Vector2();
  18241. /**
  18242. * A sprite is a plane that always faces towards the camera, generally with a
  18243. * partially transparent texture applied.
  18244. *
  18245. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  18246. * have no effect.
  18247. *
  18248. * ```js
  18249. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  18250. * const material = new THREE.SpriteMaterial( { map: map } );
  18251. *
  18252. * const sprite = new THREE.Sprite( material );
  18253. * scene.add( sprite );
  18254. * ```
  18255. *
  18256. * @augments Object3D
  18257. */
  18258. class Sprite extends Object3D {
  18259. /**
  18260. * Constructs a new sprite.
  18261. *
  18262. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  18263. */
  18264. constructor( material = new SpriteMaterial() ) {
  18265. super();
  18266. /**
  18267. * This flag can be used for type testing.
  18268. *
  18269. * @type {boolean}
  18270. * @readonly
  18271. * @default true
  18272. */
  18273. this.isSprite = true;
  18274. this.type = 'Sprite';
  18275. if ( _geometry === undefined ) {
  18276. _geometry = new BufferGeometry();
  18277. const float32Array = new Float32Array( [
  18278. -0.5, -0.5, 0, 0, 0,
  18279. 0.5, -0.5, 0, 1, 0,
  18280. 0.5, 0.5, 0, 1, 1,
  18281. -0.5, 0.5, 0, 0, 1
  18282. ] );
  18283. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18284. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18285. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18286. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18287. }
  18288. /**
  18289. * The sprite geometry.
  18290. *
  18291. * @type {BufferGeometry}
  18292. */
  18293. this.geometry = _geometry;
  18294. /**
  18295. * The sprite material.
  18296. *
  18297. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  18298. */
  18299. this.material = material;
  18300. /**
  18301. * The sprite's anchor point, and the point around which the sprite rotates.
  18302. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  18303. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  18304. *
  18305. * @type {Vector2}
  18306. * @default (0.5,0.5)
  18307. */
  18308. this.center = new Vector2( 0.5, 0.5 );
  18309. /**
  18310. * The number of instances of this sprite.
  18311. * Can only be used with {@link WebGPURenderer}.
  18312. *
  18313. * @type {number}
  18314. * @default 1
  18315. */
  18316. this.count = 1;
  18317. }
  18318. /**
  18319. * Computes intersection points between a casted ray and this sprite.
  18320. *
  18321. * @param {Raycaster} raycaster - The raycaster.
  18322. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18323. */
  18324. raycast( raycaster, intersects ) {
  18325. if ( raycaster.camera === null ) {
  18326. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18327. }
  18328. _worldScale.setFromMatrixScale( this.matrixWorld );
  18329. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18330. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18331. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18332. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18333. _worldScale.multiplyScalar( - _mvPosition.z );
  18334. }
  18335. const rotation = this.material.rotation;
  18336. let sin, cos;
  18337. if ( rotation !== 0 ) {
  18338. cos = Math.cos( rotation );
  18339. sin = Math.sin( rotation );
  18340. }
  18341. const center = this.center;
  18342. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18343. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18344. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18345. _uvA.set( 0, 0 );
  18346. _uvB.set( 1, 0 );
  18347. _uvC.set( 1, 1 );
  18348. // check first triangle
  18349. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18350. if ( intersect === null ) {
  18351. // check second triangle
  18352. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18353. _uvB.set( 0, 1 );
  18354. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18355. if ( intersect === null ) {
  18356. return;
  18357. }
  18358. }
  18359. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18360. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18361. intersects.push( {
  18362. distance: distance,
  18363. point: _intersectPoint.clone(),
  18364. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18365. face: null,
  18366. object: this
  18367. } );
  18368. }
  18369. copy( source, recursive ) {
  18370. super.copy( source, recursive );
  18371. if ( source.center !== undefined ) this.center.copy( source.center );
  18372. this.material = source.material;
  18373. return this;
  18374. }
  18375. }
  18376. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18377. // compute position in camera space
  18378. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18379. // to check if rotation is not zero
  18380. if ( sin !== undefined ) {
  18381. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18382. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18383. } else {
  18384. _rotatedPosition.copy( _alignedPosition );
  18385. }
  18386. vertexPosition.copy( mvPosition );
  18387. vertexPosition.x += _rotatedPosition.x;
  18388. vertexPosition.y += _rotatedPosition.y;
  18389. // transform to world space
  18390. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18391. }
  18392. const _v1$2 = /*@__PURE__*/ new Vector3();
  18393. const _v2$1 = /*@__PURE__*/ new Vector3();
  18394. /**
  18395. * A component for providing a basic Level of Detail (LOD) mechanism.
  18396. *
  18397. * Every LOD level is associated with an object, and rendering can be switched
  18398. * between them at the distances specified. Typically you would create, say,
  18399. * three meshes, one for far away (low detail), one for mid range (medium
  18400. * detail) and one for close up (high detail).
  18401. *
  18402. * ```js
  18403. * const lod = new THREE.LOD();
  18404. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18405. *
  18406. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18407. * for( let i = 0; i < 3; i++ ) {
  18408. *
  18409. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18410. * const mesh = new THREE.Mesh( geometry, material );
  18411. * lod.addLevel( mesh, i * 75 );
  18412. *
  18413. * }
  18414. *
  18415. * scene.add( lod );
  18416. * ```
  18417. *
  18418. * @augments Object3D
  18419. */
  18420. class LOD extends Object3D {
  18421. /**
  18422. * Constructs a new LOD.
  18423. */
  18424. constructor() {
  18425. super();
  18426. /**
  18427. * This flag can be used for type testing.
  18428. *
  18429. * @type {boolean}
  18430. * @readonly
  18431. * @default true
  18432. */
  18433. this.isLOD = true;
  18434. /**
  18435. * The current LOD index.
  18436. *
  18437. * @private
  18438. * @type {number}
  18439. * @default 0
  18440. */
  18441. this._currentLevel = 0;
  18442. this.type = 'LOD';
  18443. Object.defineProperties( this, {
  18444. /**
  18445. * This array holds the LOD levels.
  18446. *
  18447. * @name LOD#levels
  18448. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18449. */
  18450. levels: {
  18451. enumerable: true,
  18452. value: []
  18453. }
  18454. } );
  18455. /**
  18456. * Whether the LOD object is updated automatically by the renderer per frame
  18457. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18458. * render loop by yourself.
  18459. *
  18460. * @type {boolean}
  18461. * @default true
  18462. */
  18463. this.autoUpdate = true;
  18464. }
  18465. copy( source ) {
  18466. super.copy( source, false );
  18467. const levels = source.levels;
  18468. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18469. const level = levels[ i ];
  18470. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18471. }
  18472. this.autoUpdate = source.autoUpdate;
  18473. return this;
  18474. }
  18475. /**
  18476. * Adds a mesh that will display at a certain distance and greater. Typically
  18477. * the further away the distance, the lower the detail on the mesh.
  18478. *
  18479. * @param {Object3D} object - The 3D object to display at this level.
  18480. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18481. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18482. * @return {LOD} A reference to this instance.
  18483. */
  18484. addLevel( object, distance = 0, hysteresis = 0 ) {
  18485. distance = Math.abs( distance );
  18486. const levels = this.levels;
  18487. let l;
  18488. for ( l = 0; l < levels.length; l ++ ) {
  18489. if ( distance < levels[ l ].distance ) {
  18490. break;
  18491. }
  18492. }
  18493. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18494. this.add( object );
  18495. return this;
  18496. }
  18497. /**
  18498. * Removes an existing level, based on the distance from the camera.
  18499. * Returns `true` when the level has been removed. Otherwise `false`.
  18500. *
  18501. * @param {number} distance - Distance of the level to remove.
  18502. * @return {boolean} Whether the level has been removed or not.
  18503. */
  18504. removeLevel( distance ) {
  18505. const levels = this.levels;
  18506. for ( let i = 0; i < levels.length; i ++ ) {
  18507. if ( levels[ i ].distance === distance ) {
  18508. const removedElements = levels.splice( i, 1 );
  18509. this.remove( removedElements[ 0 ].object );
  18510. return true;
  18511. }
  18512. }
  18513. return false;
  18514. }
  18515. /**
  18516. * Returns the currently active LOD level index.
  18517. *
  18518. * @return {number} The current active LOD level index.
  18519. */
  18520. getCurrentLevel() {
  18521. return this._currentLevel;
  18522. }
  18523. /**
  18524. * Returns a reference to the first 3D object that is greater than
  18525. * the given distance.
  18526. *
  18527. * @param {number} distance - The LOD distance.
  18528. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  18529. */
  18530. getObjectForDistance( distance ) {
  18531. const levels = this.levels;
  18532. if ( levels.length > 0 ) {
  18533. let i, l;
  18534. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18535. let levelDistance = levels[ i ].distance;
  18536. if ( levels[ i ].object.visible ) {
  18537. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18538. }
  18539. if ( distance < levelDistance ) {
  18540. break;
  18541. }
  18542. }
  18543. return levels[ i - 1 ].object;
  18544. }
  18545. return null;
  18546. }
  18547. /**
  18548. * Computes intersection points between a casted ray and this LOD.
  18549. *
  18550. * @param {Raycaster} raycaster - The raycaster.
  18551. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18552. */
  18553. raycast( raycaster, intersects ) {
  18554. const levels = this.levels;
  18555. if ( levels.length > 0 ) {
  18556. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18557. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18558. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18559. }
  18560. }
  18561. /**
  18562. * Updates the LOD by computing which LOD level should be visible according
  18563. * to the current distance of the given camera.
  18564. *
  18565. * @param {Camera} camera - The camera the scene is rendered with.
  18566. */
  18567. update( camera ) {
  18568. const levels = this.levels;
  18569. if ( levels.length > 1 ) {
  18570. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18571. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18572. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18573. levels[ 0 ].object.visible = true;
  18574. let i, l;
  18575. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18576. let levelDistance = levels[ i ].distance;
  18577. if ( levels[ i ].object.visible ) {
  18578. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18579. }
  18580. if ( distance >= levelDistance ) {
  18581. levels[ i - 1 ].object.visible = false;
  18582. levels[ i ].object.visible = true;
  18583. } else {
  18584. break;
  18585. }
  18586. }
  18587. this._currentLevel = i - 1;
  18588. for ( ; i < l; i ++ ) {
  18589. levels[ i ].object.visible = false;
  18590. }
  18591. }
  18592. }
  18593. toJSON( meta ) {
  18594. const data = super.toJSON( meta );
  18595. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18596. data.object.levels = [];
  18597. const levels = this.levels;
  18598. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18599. const level = levels[ i ];
  18600. data.object.levels.push( {
  18601. object: level.object.uuid,
  18602. distance: level.distance,
  18603. hysteresis: level.hysteresis
  18604. } );
  18605. }
  18606. return data;
  18607. }
  18608. }
  18609. const _basePosition = /*@__PURE__*/ new Vector3();
  18610. const _skinIndex = /*@__PURE__*/ new Vector4();
  18611. const _skinWeight = /*@__PURE__*/ new Vector4();
  18612. const _vector3 = /*@__PURE__*/ new Vector3();
  18613. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18614. const _vertex = /*@__PURE__*/ new Vector3();
  18615. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18616. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18617. const _ray$2 = /*@__PURE__*/ new Ray();
  18618. /**
  18619. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18620. * vertices of the geometry with skinning/skeleton animation.
  18621. *
  18622. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18623. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18624. * vertex to a certain extend.
  18625. *
  18626. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18627. * or {@link FBXLoader } import respective models.
  18628. *
  18629. * @augments Mesh
  18630. * @demo scenes/bones-browser.html
  18631. */
  18632. class SkinnedMesh extends Mesh {
  18633. /**
  18634. * Constructs a new skinned mesh.
  18635. *
  18636. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18637. * @param {Material|Array<Material>} [material] - The mesh material.
  18638. */
  18639. constructor( geometry, material ) {
  18640. super( geometry, material );
  18641. /**
  18642. * This flag can be used for type testing.
  18643. *
  18644. * @type {boolean}
  18645. * @readonly
  18646. * @default true
  18647. */
  18648. this.isSkinnedMesh = true;
  18649. this.type = 'SkinnedMesh';
  18650. /**
  18651. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18652. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18653. * across multiple skinned meshes.
  18654. *
  18655. * @type {(AttachedBindMode|DetachedBindMode)}
  18656. * @default AttachedBindMode
  18657. */
  18658. this.bindMode = AttachedBindMode;
  18659. /**
  18660. * The base matrix that is used for the bound bone transforms.
  18661. *
  18662. * @type {Matrix4}
  18663. */
  18664. this.bindMatrix = new Matrix4();
  18665. /**
  18666. * The base matrix that is used for resetting the bound bone transforms.
  18667. *
  18668. * @type {Matrix4}
  18669. */
  18670. this.bindMatrixInverse = new Matrix4();
  18671. /**
  18672. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18673. *
  18674. * @type {?Box3}
  18675. * @default null
  18676. */
  18677. this.boundingBox = null;
  18678. /**
  18679. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18680. *
  18681. * @type {?Sphere}
  18682. * @default null
  18683. */
  18684. this.boundingSphere = null;
  18685. }
  18686. /**
  18687. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18688. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18689. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18690. * the current animation state.
  18691. */
  18692. computeBoundingBox() {
  18693. const geometry = this.geometry;
  18694. if ( this.boundingBox === null ) {
  18695. this.boundingBox = new Box3();
  18696. }
  18697. this.boundingBox.makeEmpty();
  18698. const positionAttribute = geometry.getAttribute( 'position' );
  18699. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18700. this.getVertexPosition( i, _vertex );
  18701. this.boundingBox.expandByPoint( _vertex );
  18702. }
  18703. }
  18704. /**
  18705. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18706. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18707. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18708. * per frame in order to reflect the current animation state.
  18709. */
  18710. computeBoundingSphere() {
  18711. const geometry = this.geometry;
  18712. if ( this.boundingSphere === null ) {
  18713. this.boundingSphere = new Sphere();
  18714. }
  18715. this.boundingSphere.makeEmpty();
  18716. const positionAttribute = geometry.getAttribute( 'position' );
  18717. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18718. this.getVertexPosition( i, _vertex );
  18719. this.boundingSphere.expandByPoint( _vertex );
  18720. }
  18721. }
  18722. copy( source, recursive ) {
  18723. super.copy( source, recursive );
  18724. this.bindMode = source.bindMode;
  18725. this.bindMatrix.copy( source.bindMatrix );
  18726. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18727. this.skeleton = source.skeleton;
  18728. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18729. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18730. return this;
  18731. }
  18732. raycast( raycaster, intersects ) {
  18733. const material = this.material;
  18734. const matrixWorld = this.matrixWorld;
  18735. if ( material === undefined ) return;
  18736. // test with bounding sphere in world space
  18737. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18738. _sphere$5.copy( this.boundingSphere );
  18739. _sphere$5.applyMatrix4( matrixWorld );
  18740. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18741. // convert ray to local space of skinned mesh
  18742. _inverseMatrix$2.copy( matrixWorld ).invert();
  18743. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18744. // test with bounding box in local space
  18745. if ( this.boundingBox !== null ) {
  18746. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18747. }
  18748. // test for intersections with geometry
  18749. this._computeIntersections( raycaster, intersects, _ray$2 );
  18750. }
  18751. getVertexPosition( index, target ) {
  18752. super.getVertexPosition( index, target );
  18753. this.applyBoneTransform( index, target );
  18754. return target;
  18755. }
  18756. /**
  18757. * Binds the given skeleton to the skinned mesh.
  18758. *
  18759. * @param {Skeleton} skeleton - The skeleton to bind.
  18760. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18761. * the skinned mesh's world matrix will be used instead.
  18762. */
  18763. bind( skeleton, bindMatrix ) {
  18764. this.skeleton = skeleton;
  18765. if ( bindMatrix === undefined ) {
  18766. this.updateMatrixWorld( true );
  18767. this.skeleton.calculateInverses();
  18768. bindMatrix = this.matrixWorld;
  18769. }
  18770. this.bindMatrix.copy( bindMatrix );
  18771. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18772. }
  18773. /**
  18774. * This method sets the skinned mesh in the rest pose).
  18775. */
  18776. pose() {
  18777. this.skeleton.pose();
  18778. }
  18779. /**
  18780. * Normalizes the skin weights which are defined as a buffer attribute
  18781. * in the skinned mesh's geometry.
  18782. */
  18783. normalizeSkinWeights() {
  18784. const vector = new Vector4();
  18785. const skinWeight = this.geometry.attributes.skinWeight;
  18786. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18787. vector.fromBufferAttribute( skinWeight, i );
  18788. const scale = 1.0 / vector.manhattanLength();
  18789. if ( scale !== Infinity ) {
  18790. vector.multiplyScalar( scale );
  18791. } else {
  18792. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18793. }
  18794. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18795. }
  18796. }
  18797. updateMatrixWorld( force ) {
  18798. super.updateMatrixWorld( force );
  18799. if ( this.bindMode === AttachedBindMode ) {
  18800. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18801. } else if ( this.bindMode === DetachedBindMode ) {
  18802. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18803. } else {
  18804. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18805. }
  18806. }
  18807. /**
  18808. * Applies the bone transform associated with the given index to the given
  18809. * vertex position. Returns the updated vector.
  18810. *
  18811. * @param {number} index - The vertex index.
  18812. * @param {Vector3} target - The target object that is used to store the method's result.
  18813. * the skinned mesh's world matrix will be used instead.
  18814. * @return {Vector3} The updated vertex position.
  18815. */
  18816. applyBoneTransform( index, target ) {
  18817. const skeleton = this.skeleton;
  18818. const geometry = this.geometry;
  18819. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18820. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18821. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18822. target.set( 0, 0, 0 );
  18823. for ( let i = 0; i < 4; i ++ ) {
  18824. const weight = _skinWeight.getComponent( i );
  18825. if ( weight !== 0 ) {
  18826. const boneIndex = _skinIndex.getComponent( i );
  18827. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18828. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18829. }
  18830. }
  18831. return target.applyMatrix4( this.bindMatrixInverse );
  18832. }
  18833. }
  18834. /**
  18835. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18836. * the {@link SkinnedMesh}.
  18837. *
  18838. * ```js
  18839. * const root = new THREE.Bone();
  18840. * const child = new THREE.Bone();
  18841. *
  18842. * root.add( child );
  18843. * child.position.y = 5;
  18844. * ```
  18845. *
  18846. * @augments Object3D
  18847. */
  18848. class Bone extends Object3D {
  18849. /**
  18850. * Constructs a new bone.
  18851. */
  18852. constructor() {
  18853. super();
  18854. /**
  18855. * This flag can be used for type testing.
  18856. *
  18857. * @type {boolean}
  18858. * @readonly
  18859. * @default true
  18860. */
  18861. this.isBone = true;
  18862. this.type = 'Bone';
  18863. }
  18864. }
  18865. /**
  18866. * Creates a texture directly from raw buffer data.
  18867. *
  18868. * The interpretation of the data depends on type and format: If the type is
  18869. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18870. * texel data. If the format is `RGBAFormat`, data needs four values for
  18871. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18872. *
  18873. * @augments Texture
  18874. */
  18875. class DataTexture extends Texture {
  18876. /**
  18877. * Constructs a new data texture.
  18878. *
  18879. * @param {?TypedArray} [data=null] - The buffer data.
  18880. * @param {number} [width=1] - The width of the texture.
  18881. * @param {number} [height=1] - The height of the texture.
  18882. * @param {number} [format=RGBAFormat] - The texture format.
  18883. * @param {number} [type=UnsignedByteType] - The texture type.
  18884. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18885. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18886. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18887. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18888. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18889. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18890. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18891. */
  18892. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18893. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18894. /**
  18895. * This flag can be used for type testing.
  18896. *
  18897. * @type {boolean}
  18898. * @readonly
  18899. * @default true
  18900. */
  18901. this.isDataTexture = true;
  18902. /**
  18903. * The image definition of a data texture.
  18904. *
  18905. * @type {{data:TypedArray,width:number,height:number}}
  18906. */
  18907. this.image = { data: data, width: width, height: height };
  18908. /**
  18909. * Whether to generate mipmaps (if possible) for a texture.
  18910. *
  18911. * Overwritten and set to `false` by default.
  18912. *
  18913. * @type {boolean}
  18914. * @default false
  18915. */
  18916. this.generateMipmaps = false;
  18917. /**
  18918. * If set to `true`, the texture is flipped along the vertical axis when
  18919. * uploaded to the GPU.
  18920. *
  18921. * Overwritten and set to `false` by default.
  18922. *
  18923. * @type {boolean}
  18924. * @default false
  18925. */
  18926. this.flipY = false;
  18927. /**
  18928. * Specifies the alignment requirements for the start of each pixel row in memory.
  18929. *
  18930. * Overwritten and set to `1` by default.
  18931. *
  18932. * @type {boolean}
  18933. * @default 1
  18934. */
  18935. this.unpackAlignment = 1;
  18936. }
  18937. }
  18938. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18939. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18940. /**
  18941. * Class for representing the armatures in `three.js`. The skeleton
  18942. * is defined by a hierarchy of bones.
  18943. *
  18944. * ```js
  18945. * const bones = [];
  18946. *
  18947. * const shoulder = new THREE.Bone();
  18948. * const elbow = new THREE.Bone();
  18949. * const hand = new THREE.Bone();
  18950. *
  18951. * shoulder.add( elbow );
  18952. * elbow.add( hand );
  18953. *
  18954. * bones.push( shoulder , elbow, hand);
  18955. *
  18956. * shoulder.position.y = -5;
  18957. * elbow.position.y = 0;
  18958. * hand.position.y = 5;
  18959. *
  18960. * const armSkeleton = new THREE.Skeleton( bones );
  18961. * ```
  18962. */
  18963. class Skeleton {
  18964. /**
  18965. * Constructs a new skeleton.
  18966. *
  18967. * @param {Array<Bone>} [bones] - An array of bones.
  18968. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18969. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18970. */
  18971. constructor( bones = [], boneInverses = [] ) {
  18972. this.uuid = generateUUID();
  18973. /**
  18974. * An array of bones defining the skeleton.
  18975. *
  18976. * @type {Array<Bone>}
  18977. */
  18978. this.bones = bones.slice( 0 );
  18979. /**
  18980. * An array of bone inverse matrices.
  18981. *
  18982. * @type {Array<Matrix4>}
  18983. */
  18984. this.boneInverses = boneInverses;
  18985. /**
  18986. * An array buffer holding the bone data.
  18987. * Input data for {@link Skeleton#boneTexture}.
  18988. *
  18989. * @type {?Float32Array}
  18990. * @default null
  18991. */
  18992. this.boneMatrices = null;
  18993. /**
  18994. * An array buffer holding the bone data of the previous frame.
  18995. * Required for computing velocity. Maintained in {@link SkinningNode}.
  18996. *
  18997. * @type {?Float32Array}
  18998. * @default null
  18999. */
  19000. this.previousBoneMatrices = null;
  19001. /**
  19002. * A texture holding the bone data for use
  19003. * in the vertex shader.
  19004. *
  19005. * @type {?DataTexture}
  19006. * @default null
  19007. */
  19008. this.boneTexture = null;
  19009. this.init();
  19010. }
  19011. /**
  19012. * Initializes the skeleton. This method gets automatically called by the constructor
  19013. * but depending on how the skeleton is created it might be necessary to call this method
  19014. * manually.
  19015. */
  19016. init() {
  19017. const bones = this.bones;
  19018. const boneInverses = this.boneInverses;
  19019. this.boneMatrices = new Float32Array( bones.length * 16 );
  19020. // calculate inverse bone matrices if necessary
  19021. if ( boneInverses.length === 0 ) {
  19022. this.calculateInverses();
  19023. } else {
  19024. // handle special case
  19025. if ( bones.length !== boneInverses.length ) {
  19026. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  19027. this.boneInverses = [];
  19028. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19029. this.boneInverses.push( new Matrix4() );
  19030. }
  19031. }
  19032. }
  19033. }
  19034. /**
  19035. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  19036. * and fills it with new matrices.
  19037. */
  19038. calculateInverses() {
  19039. this.boneInverses.length = 0;
  19040. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19041. const inverse = new Matrix4();
  19042. if ( this.bones[ i ] ) {
  19043. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  19044. }
  19045. this.boneInverses.push( inverse );
  19046. }
  19047. }
  19048. /**
  19049. * Resets the skeleton to the base pose.
  19050. */
  19051. pose() {
  19052. // recover the bind-time world matrices
  19053. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19054. const bone = this.bones[ i ];
  19055. if ( bone ) {
  19056. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  19057. }
  19058. }
  19059. // compute the local matrices, positions, rotations and scales
  19060. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19061. const bone = this.bones[ i ];
  19062. if ( bone ) {
  19063. if ( bone.parent && bone.parent.isBone ) {
  19064. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  19065. bone.matrix.multiply( bone.matrixWorld );
  19066. } else {
  19067. bone.matrix.copy( bone.matrixWorld );
  19068. }
  19069. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  19070. }
  19071. }
  19072. }
  19073. /**
  19074. * Resets the skeleton to the base pose.
  19075. */
  19076. update() {
  19077. const bones = this.bones;
  19078. const boneInverses = this.boneInverses;
  19079. const boneMatrices = this.boneMatrices;
  19080. const boneTexture = this.boneTexture;
  19081. // flatten bone matrices to array
  19082. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  19083. // compute the offset between the current and the original transform
  19084. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  19085. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  19086. _offsetMatrix.toArray( boneMatrices, i * 16 );
  19087. }
  19088. if ( boneTexture !== null ) {
  19089. boneTexture.needsUpdate = true;
  19090. }
  19091. }
  19092. /**
  19093. * Returns a new skeleton with copied values from this instance.
  19094. *
  19095. * @return {Skeleton} A clone of this instance.
  19096. */
  19097. clone() {
  19098. return new Skeleton( this.bones, this.boneInverses );
  19099. }
  19100. /**
  19101. * Computes a data texture for passing bone data to the vertex shader.
  19102. *
  19103. * @return {Skeleton} A reference of this instance.
  19104. */
  19105. computeBoneTexture() {
  19106. // layout (1 matrix = 4 pixels)
  19107. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19108. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19109. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19110. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19111. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19112. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  19113. size = Math.ceil( size / 4 ) * 4;
  19114. size = Math.max( size, 4 );
  19115. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19116. boneMatrices.set( this.boneMatrices ); // copy current values
  19117. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19118. boneTexture.needsUpdate = true;
  19119. this.boneMatrices = boneMatrices;
  19120. this.boneTexture = boneTexture;
  19121. return this;
  19122. }
  19123. /**
  19124. * Searches through the skeleton's bone array and returns the first with a
  19125. * matching name.
  19126. *
  19127. * @param {string} name - The name of the bone.
  19128. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  19129. */
  19130. getBoneByName( name ) {
  19131. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19132. const bone = this.bones[ i ];
  19133. if ( bone.name === name ) {
  19134. return bone;
  19135. }
  19136. }
  19137. return undefined;
  19138. }
  19139. /**
  19140. * Frees the GPU-related resources allocated by this instance. Call this
  19141. * method whenever this instance is no longer used in your app.
  19142. */
  19143. dispose( ) {
  19144. if ( this.boneTexture !== null ) {
  19145. this.boneTexture.dispose();
  19146. this.boneTexture = null;
  19147. }
  19148. }
  19149. /**
  19150. * Setups the skeleton by the given JSON and bones.
  19151. *
  19152. * @param {Object} json - The skeleton as serialized JSON.
  19153. * @param {Object<string, Bone>} bones - An array of bones.
  19154. * @return {Skeleton} A reference of this instance.
  19155. */
  19156. fromJSON( json, bones ) {
  19157. this.uuid = json.uuid;
  19158. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  19159. const uuid = json.bones[ i ];
  19160. let bone = bones[ uuid ];
  19161. if ( bone === undefined ) {
  19162. warn( 'Skeleton: No bone found with UUID:', uuid );
  19163. bone = new Bone();
  19164. }
  19165. this.bones.push( bone );
  19166. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  19167. }
  19168. this.init();
  19169. return this;
  19170. }
  19171. /**
  19172. * Serializes the skeleton into JSON.
  19173. *
  19174. * @return {Object} A JSON object representing the serialized skeleton.
  19175. * @see {@link ObjectLoader#parse}
  19176. */
  19177. toJSON() {
  19178. const data = {
  19179. metadata: {
  19180. version: 4.7,
  19181. type: 'Skeleton',
  19182. generator: 'Skeleton.toJSON'
  19183. },
  19184. bones: [],
  19185. boneInverses: []
  19186. };
  19187. data.uuid = this.uuid;
  19188. const bones = this.bones;
  19189. const boneInverses = this.boneInverses;
  19190. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19191. const bone = bones[ i ];
  19192. data.bones.push( bone.uuid );
  19193. const boneInverse = boneInverses[ i ];
  19194. data.boneInverses.push( boneInverse.toArray() );
  19195. }
  19196. return data;
  19197. }
  19198. }
  19199. /**
  19200. * An instanced version of a buffer attribute.
  19201. *
  19202. * @augments BufferAttribute
  19203. */
  19204. class InstancedBufferAttribute extends BufferAttribute {
  19205. /**
  19206. * Constructs a new instanced buffer attribute.
  19207. *
  19208. * @param {TypedArray} array - The array holding the attribute data.
  19209. * @param {number} itemSize - The item size.
  19210. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  19211. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  19212. */
  19213. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19214. super( array, itemSize, normalized );
  19215. /**
  19216. * This flag can be used for type testing.
  19217. *
  19218. * @type {boolean}
  19219. * @readonly
  19220. * @default true
  19221. */
  19222. this.isInstancedBufferAttribute = true;
  19223. /**
  19224. * Defines how often a value of this buffer attribute should be repeated. A
  19225. * value of one means that each value of the instanced attribute is used for
  19226. * a single instance. A value of two means that each value is used for two
  19227. * consecutive instances (and so on).
  19228. *
  19229. * @type {number}
  19230. * @default 1
  19231. */
  19232. this.meshPerAttribute = meshPerAttribute;
  19233. }
  19234. copy( source ) {
  19235. super.copy( source );
  19236. this.meshPerAttribute = source.meshPerAttribute;
  19237. return this;
  19238. }
  19239. toJSON() {
  19240. const data = super.toJSON();
  19241. data.meshPerAttribute = this.meshPerAttribute;
  19242. data.isInstancedBufferAttribute = true;
  19243. return data;
  19244. }
  19245. }
  19246. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19247. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19248. const _instanceIntersects = [];
  19249. const _box3 = /*@__PURE__*/ new Box3();
  19250. const _identity = /*@__PURE__*/ new Matrix4();
  19251. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19252. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19253. /**
  19254. * A special version of a mesh with instanced rendering support. Use
  19255. * this class if you have to render a large number of objects with the same
  19256. * geometry and material(s) but with different world transformations. The usage
  19257. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  19258. * improve the overall rendering performance in your application.
  19259. *
  19260. * @augments Mesh
  19261. */
  19262. class InstancedMesh extends Mesh {
  19263. /**
  19264. * Constructs a new instanced mesh.
  19265. *
  19266. * @param {BufferGeometry} [geometry] - The mesh geometry.
  19267. * @param {Material|Array<Material>} [material] - The mesh material.
  19268. * @param {number} count - The number of instances.
  19269. */
  19270. constructor( geometry, material, count ) {
  19271. super( geometry, material );
  19272. /**
  19273. * This flag can be used for type testing.
  19274. *
  19275. * @type {boolean}
  19276. * @readonly
  19277. * @default true
  19278. */
  19279. this.isInstancedMesh = true;
  19280. /**
  19281. * Represents the local transformation of all instances. You have to set its
  19282. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19283. * via {@link InstancedMesh#setMatrixAt}.
  19284. *
  19285. * @type {InstancedBufferAttribute}
  19286. */
  19287. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19288. /**
  19289. * Represents the local transformation of all instances of the previous frame.
  19290. * Required for computing velocity. Maintained in {@link InstanceNode}.
  19291. *
  19292. * @type {?InstancedBufferAttribute}
  19293. * @default null
  19294. */
  19295. this.previousInstanceMatrix = null;
  19296. /**
  19297. * Represents the color of all instances. You have to set its
  19298. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19299. * via {@link InstancedMesh#setColorAt}.
  19300. *
  19301. * @type {?InstancedBufferAttribute}
  19302. * @default null
  19303. */
  19304. this.instanceColor = null;
  19305. /**
  19306. * Represents the morph target weights of all instances. You have to set its
  19307. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  19308. * via {@link InstancedMesh#setMorphAt}.
  19309. *
  19310. * @type {?DataTexture}
  19311. * @default null
  19312. */
  19313. this.morphTexture = null;
  19314. /**
  19315. * The number of instances.
  19316. *
  19317. * @type {number}
  19318. */
  19319. this.count = count;
  19320. /**
  19321. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  19322. *
  19323. * @type {?Box3}
  19324. * @default null
  19325. */
  19326. this.boundingBox = null;
  19327. /**
  19328. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19329. *
  19330. * @type {?Sphere}
  19331. * @default null
  19332. */
  19333. this.boundingSphere = null;
  19334. for ( let i = 0; i < count; i ++ ) {
  19335. this.setMatrixAt( i, _identity );
  19336. }
  19337. }
  19338. /**
  19339. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19340. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19341. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19342. */
  19343. computeBoundingBox() {
  19344. const geometry = this.geometry;
  19345. const count = this.count;
  19346. if ( this.boundingBox === null ) {
  19347. this.boundingBox = new Box3();
  19348. }
  19349. if ( geometry.boundingBox === null ) {
  19350. geometry.computeBoundingBox();
  19351. }
  19352. this.boundingBox.makeEmpty();
  19353. for ( let i = 0; i < count; i ++ ) {
  19354. this.getMatrixAt( i, _instanceLocalMatrix );
  19355. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19356. this.boundingBox.union( _box3 );
  19357. }
  19358. }
  19359. /**
  19360. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19361. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19362. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19363. */
  19364. computeBoundingSphere() {
  19365. const geometry = this.geometry;
  19366. const count = this.count;
  19367. if ( this.boundingSphere === null ) {
  19368. this.boundingSphere = new Sphere();
  19369. }
  19370. if ( geometry.boundingSphere === null ) {
  19371. geometry.computeBoundingSphere();
  19372. }
  19373. this.boundingSphere.makeEmpty();
  19374. for ( let i = 0; i < count; i ++ ) {
  19375. this.getMatrixAt( i, _instanceLocalMatrix );
  19376. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19377. this.boundingSphere.union( _sphere$4 );
  19378. }
  19379. }
  19380. copy( source, recursive ) {
  19381. super.copy( source, recursive );
  19382. this.instanceMatrix.copy( source.instanceMatrix );
  19383. if ( source.previousInstanceMatrix !== null ) this.previousInstanceMatrix = source.previousInstanceMatrix.clone();
  19384. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19385. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19386. this.count = source.count;
  19387. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19388. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19389. return this;
  19390. }
  19391. /**
  19392. * Gets the color of the defined instance.
  19393. *
  19394. * @param {number} index - The instance index.
  19395. * @param {Color} color - The target object that is used to store the method's result.
  19396. */
  19397. getColorAt( index, color ) {
  19398. color.fromArray( this.instanceColor.array, index * 3 );
  19399. }
  19400. /**
  19401. * Gets the local transformation matrix of the defined instance.
  19402. *
  19403. * @param {number} index - The instance index.
  19404. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19405. */
  19406. getMatrixAt( index, matrix ) {
  19407. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19408. }
  19409. /**
  19410. * Gets the morph target weights of the defined instance.
  19411. *
  19412. * @param {number} index - The instance index.
  19413. * @param {Mesh} object - The target object that is used to store the method's result.
  19414. */
  19415. getMorphAt( index, object ) {
  19416. const objectInfluences = object.morphTargetInfluences;
  19417. const array = this.morphTexture.source.data.data;
  19418. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19419. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19420. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19421. objectInfluences[ i ] = array[ dataIndex + i ];
  19422. }
  19423. }
  19424. raycast( raycaster, intersects ) {
  19425. const matrixWorld = this.matrixWorld;
  19426. const raycastTimes = this.count;
  19427. _mesh$1.geometry = this.geometry;
  19428. _mesh$1.material = this.material;
  19429. if ( _mesh$1.material === undefined ) return;
  19430. // test with bounding sphere first
  19431. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19432. _sphere$4.copy( this.boundingSphere );
  19433. _sphere$4.applyMatrix4( matrixWorld );
  19434. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19435. // now test each instance
  19436. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19437. // calculate the world matrix for each instance
  19438. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19439. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19440. // the mesh represents this single instance
  19441. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19442. _mesh$1.raycast( raycaster, _instanceIntersects );
  19443. // process the result of raycast
  19444. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19445. const intersect = _instanceIntersects[ i ];
  19446. intersect.instanceId = instanceId;
  19447. intersect.object = this;
  19448. intersects.push( intersect );
  19449. }
  19450. _instanceIntersects.length = 0;
  19451. }
  19452. }
  19453. /**
  19454. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19455. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19456. *
  19457. * @param {number} index - The instance index.
  19458. * @param {Color} color - The instance color.
  19459. */
  19460. setColorAt( index, color ) {
  19461. if ( this.instanceColor === null ) {
  19462. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19463. }
  19464. color.toArray( this.instanceColor.array, index * 3 );
  19465. }
  19466. /**
  19467. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19468. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19469. *
  19470. * @param {number} index - The instance index.
  19471. * @param {Matrix4} matrix - The local transformation.
  19472. */
  19473. setMatrixAt( index, matrix ) {
  19474. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19475. }
  19476. /**
  19477. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19478. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19479. *
  19480. * @param {number} index - The instance index.
  19481. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19482. * of a single instance.
  19483. */
  19484. setMorphAt( index, object ) {
  19485. const objectInfluences = object.morphTargetInfluences;
  19486. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19487. if ( this.morphTexture === null ) {
  19488. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19489. }
  19490. const array = this.morphTexture.source.data.data;
  19491. let morphInfluencesSum = 0;
  19492. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19493. morphInfluencesSum += objectInfluences[ i ];
  19494. }
  19495. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19496. const dataIndex = len * index;
  19497. array[ dataIndex ] = morphBaseInfluence;
  19498. array.set( objectInfluences, dataIndex + 1 );
  19499. }
  19500. updateMorphTargets() {
  19501. }
  19502. /**
  19503. * Frees the GPU-related resources allocated by this instance. Call this
  19504. * method whenever this instance is no longer used in your app.
  19505. */
  19506. dispose() {
  19507. this.dispatchEvent( { type: 'dispose' } );
  19508. if ( this.morphTexture !== null ) {
  19509. this.morphTexture.dispose();
  19510. this.morphTexture = null;
  19511. }
  19512. }
  19513. }
  19514. const _vector1 = /*@__PURE__*/ new Vector3();
  19515. const _vector2 = /*@__PURE__*/ new Vector3();
  19516. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19517. /**
  19518. * A two dimensional surface that extends infinitely in 3D space, represented
  19519. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  19520. * by a unit length normal vector and a constant.
  19521. */
  19522. class Plane {
  19523. /**
  19524. * Constructs a new plane.
  19525. *
  19526. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19527. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19528. */
  19529. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19530. /**
  19531. * This flag can be used for type testing.
  19532. *
  19533. * @type {boolean}
  19534. * @readonly
  19535. * @default true
  19536. */
  19537. this.isPlane = true;
  19538. /**
  19539. * A unit length vector defining the normal of the plane.
  19540. *
  19541. * @type {Vector3}
  19542. */
  19543. this.normal = normal;
  19544. /**
  19545. * The signed distance from the origin to the plane.
  19546. *
  19547. * @type {number}
  19548. * @default 0
  19549. */
  19550. this.constant = constant;
  19551. }
  19552. /**
  19553. * Sets the plane components by copying the given values.
  19554. *
  19555. * @param {Vector3} normal - The normal.
  19556. * @param {number} constant - The constant.
  19557. * @return {Plane} A reference to this plane.
  19558. */
  19559. set( normal, constant ) {
  19560. this.normal.copy( normal );
  19561. this.constant = constant;
  19562. return this;
  19563. }
  19564. /**
  19565. * Sets the plane components by defining `x`, `y`, `z` as the
  19566. * plane normal and `w` as the constant.
  19567. *
  19568. * @param {number} x - The value for the normal's x component.
  19569. * @param {number} y - The value for the normal's y component.
  19570. * @param {number} z - The value for the normal's z component.
  19571. * @param {number} w - The constant value.
  19572. * @return {Plane} A reference to this plane.
  19573. */
  19574. setComponents( x, y, z, w ) {
  19575. this.normal.set( x, y, z );
  19576. this.constant = w;
  19577. return this;
  19578. }
  19579. /**
  19580. * Sets the plane from the given normal and coplanar point (that is a point
  19581. * that lies onto the plane).
  19582. *
  19583. * @param {Vector3} normal - The normal.
  19584. * @param {Vector3} point - A coplanar point.
  19585. * @return {Plane} A reference to this plane.
  19586. */
  19587. setFromNormalAndCoplanarPoint( normal, point ) {
  19588. this.normal.copy( normal );
  19589. this.constant = - point.dot( this.normal );
  19590. return this;
  19591. }
  19592. /**
  19593. * Sets the plane from three coplanar points. The winding order is
  19594. * assumed to be counter-clockwise, and determines the direction of
  19595. * the plane normal.
  19596. *
  19597. * @param {Vector3} a - The first coplanar point.
  19598. * @param {Vector3} b - The second coplanar point.
  19599. * @param {Vector3} c - The third coplanar point.
  19600. * @return {Plane} A reference to this plane.
  19601. */
  19602. setFromCoplanarPoints( a, b, c ) {
  19603. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19604. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19605. this.setFromNormalAndCoplanarPoint( normal, a );
  19606. return this;
  19607. }
  19608. /**
  19609. * Copies the values of the given plane to this instance.
  19610. *
  19611. * @param {Plane} plane - The plane to copy.
  19612. * @return {Plane} A reference to this plane.
  19613. */
  19614. copy( plane ) {
  19615. this.normal.copy( plane.normal );
  19616. this.constant = plane.constant;
  19617. return this;
  19618. }
  19619. /**
  19620. * Normalizes the plane normal and adjusts the constant accordingly.
  19621. *
  19622. * @return {Plane} A reference to this plane.
  19623. */
  19624. normalize() {
  19625. // Note: will lead to a divide by zero if the plane is invalid.
  19626. const inverseNormalLength = 1.0 / this.normal.length();
  19627. this.normal.multiplyScalar( inverseNormalLength );
  19628. this.constant *= inverseNormalLength;
  19629. return this;
  19630. }
  19631. /**
  19632. * Negates both the plane normal and the constant.
  19633. *
  19634. * @return {Plane} A reference to this plane.
  19635. */
  19636. negate() {
  19637. this.constant *= -1;
  19638. this.normal.negate();
  19639. return this;
  19640. }
  19641. /**
  19642. * Returns the signed distance from the given point to this plane.
  19643. *
  19644. * @param {Vector3} point - The point to compute the distance for.
  19645. * @return {number} The signed distance.
  19646. */
  19647. distanceToPoint( point ) {
  19648. return this.normal.dot( point ) + this.constant;
  19649. }
  19650. /**
  19651. * Returns the signed distance from the given sphere to this plane.
  19652. *
  19653. * @param {Sphere} sphere - The sphere to compute the distance for.
  19654. * @return {number} The signed distance.
  19655. */
  19656. distanceToSphere( sphere ) {
  19657. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19658. }
  19659. /**
  19660. * Projects a the given point onto the plane.
  19661. *
  19662. * @param {Vector3} point - The point to project.
  19663. * @param {Vector3} target - The target vector that is used to store the method's result.
  19664. * @return {Vector3} The projected point on the plane.
  19665. */
  19666. projectPoint( point, target ) {
  19667. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19668. }
  19669. /**
  19670. * Returns the intersection point of the passed line and the plane. Returns
  19671. * `null` if the line does not intersect. Returns the line's starting point if
  19672. * the line is coplanar with the plane.
  19673. *
  19674. * @param {Line3} line - The line to compute the intersection for.
  19675. * @param {Vector3} target - The target vector that is used to store the method's result.
  19676. * @return {?Vector3} The intersection point.
  19677. */
  19678. intersectLine( line, target ) {
  19679. const direction = line.delta( _vector1 );
  19680. const denominator = this.normal.dot( direction );
  19681. if ( denominator === 0 ) {
  19682. // line is coplanar, return origin
  19683. if ( this.distanceToPoint( line.start ) === 0 ) {
  19684. return target.copy( line.start );
  19685. }
  19686. // Unsure if this is the correct method to handle this case.
  19687. return null;
  19688. }
  19689. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19690. if ( t < 0 || t > 1 ) {
  19691. return null;
  19692. }
  19693. return target.copy( line.start ).addScaledVector( direction, t );
  19694. }
  19695. /**
  19696. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19697. *
  19698. * @param {Line3} line - The line to test.
  19699. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19700. */
  19701. intersectsLine( line ) {
  19702. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19703. const startSign = this.distanceToPoint( line.start );
  19704. const endSign = this.distanceToPoint( line.end );
  19705. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19706. }
  19707. /**
  19708. * Returns `true` if the given bounding box intersects with the plane.
  19709. *
  19710. * @param {Box3} box - The bounding box to test.
  19711. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19712. */
  19713. intersectsBox( box ) {
  19714. return box.intersectsPlane( this );
  19715. }
  19716. /**
  19717. * Returns `true` if the given bounding sphere intersects with the plane.
  19718. *
  19719. * @param {Sphere} sphere - The bounding sphere to test.
  19720. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19721. */
  19722. intersectsSphere( sphere ) {
  19723. return sphere.intersectsPlane( this );
  19724. }
  19725. /**
  19726. * Returns a coplanar vector to the plane, by calculating the
  19727. * projection of the normal at the origin onto the plane.
  19728. *
  19729. * @param {Vector3} target - The target vector that is used to store the method's result.
  19730. * @return {Vector3} The coplanar point.
  19731. */
  19732. coplanarPoint( target ) {
  19733. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19734. }
  19735. /**
  19736. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19737. *
  19738. * The optional normal matrix can be pre-computed like so:
  19739. * ```js
  19740. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19741. * ```
  19742. *
  19743. * @param {Matrix4} matrix - The transformation matrix.
  19744. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19745. * @return {Plane} A reference to this plane.
  19746. */
  19747. applyMatrix4( matrix, optionalNormalMatrix ) {
  19748. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19749. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19750. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19751. this.constant = - referencePoint.dot( normal );
  19752. return this;
  19753. }
  19754. /**
  19755. * Translates the plane by the distance defined by the given offset vector.
  19756. * Note that this only affects the plane constant and will not affect the normal vector.
  19757. *
  19758. * @param {Vector3} offset - The offset vector.
  19759. * @return {Plane} A reference to this plane.
  19760. */
  19761. translate( offset ) {
  19762. this.constant -= offset.dot( this.normal );
  19763. return this;
  19764. }
  19765. /**
  19766. * Returns `true` if this plane is equal with the given one.
  19767. *
  19768. * @param {Plane} plane - The plane to test for equality.
  19769. * @return {boolean} Whether this plane is equal with the given one.
  19770. */
  19771. equals( plane ) {
  19772. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19773. }
  19774. /**
  19775. * Returns a new plane with copied values from this instance.
  19776. *
  19777. * @return {Plane} A clone of this instance.
  19778. */
  19779. clone() {
  19780. return new this.constructor().copy( this );
  19781. }
  19782. }
  19783. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19784. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19785. const _vector$6 = /*@__PURE__*/ new Vector3();
  19786. /**
  19787. * Frustums are used to determine what is inside the camera's field of view.
  19788. * They help speed up the rendering process - objects which lie outside a camera's
  19789. * frustum can safely be excluded from rendering.
  19790. *
  19791. * This class is mainly intended for use internally by a renderer.
  19792. */
  19793. class Frustum {
  19794. /**
  19795. * Constructs a new frustum.
  19796. *
  19797. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19798. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19799. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19800. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19801. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19802. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19803. */
  19804. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19805. /**
  19806. * This array holds the planes that enclose the frustum.
  19807. *
  19808. * @type {Array<Plane>}
  19809. */
  19810. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19811. }
  19812. /**
  19813. * Sets the frustum planes by copying the given planes.
  19814. *
  19815. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19816. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19817. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19818. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19819. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19820. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19821. * @return {Frustum} A reference to this frustum.
  19822. */
  19823. set( p0, p1, p2, p3, p4, p5 ) {
  19824. const planes = this.planes;
  19825. planes[ 0 ].copy( p0 );
  19826. planes[ 1 ].copy( p1 );
  19827. planes[ 2 ].copy( p2 );
  19828. planes[ 3 ].copy( p3 );
  19829. planes[ 4 ].copy( p4 );
  19830. planes[ 5 ].copy( p5 );
  19831. return this;
  19832. }
  19833. /**
  19834. * Copies the values of the given frustum to this instance.
  19835. *
  19836. * @param {Frustum} frustum - The frustum to copy.
  19837. * @return {Frustum} A reference to this frustum.
  19838. */
  19839. copy( frustum ) {
  19840. const planes = this.planes;
  19841. for ( let i = 0; i < 6; i ++ ) {
  19842. planes[ i ].copy( frustum.planes[ i ] );
  19843. }
  19844. return this;
  19845. }
  19846. /**
  19847. * Sets the frustum planes from the given projection matrix.
  19848. *
  19849. * @param {Matrix4} m - The projection matrix.
  19850. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19851. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19852. * @return {Frustum} A reference to this frustum.
  19853. */
  19854. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19855. const planes = this.planes;
  19856. const me = m.elements;
  19857. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19858. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19859. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19860. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19861. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19862. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19863. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19864. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19865. if ( reversedDepth ) {
  19866. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19867. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19868. } else {
  19869. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19870. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19871. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19872. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19873. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19874. } else {
  19875. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19876. }
  19877. }
  19878. return this;
  19879. }
  19880. /**
  19881. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19882. *
  19883. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19884. *
  19885. * @param {Object3D} object - The 3D object to test.
  19886. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19887. */
  19888. intersectsObject( object ) {
  19889. if ( object.boundingSphere !== undefined ) {
  19890. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19891. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19892. } else {
  19893. const geometry = object.geometry;
  19894. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19895. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19896. }
  19897. return this.intersectsSphere( _sphere$3 );
  19898. }
  19899. /**
  19900. * Returns `true` if the given sprite is intersecting this frustum.
  19901. *
  19902. * @param {Sprite} sprite - The sprite to test.
  19903. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19904. */
  19905. intersectsSprite( sprite ) {
  19906. _sphere$3.center.set( 0, 0, 0 );
  19907. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19908. _sphere$3.radius = 0.7071067811865476 + offset;
  19909. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19910. return this.intersectsSphere( _sphere$3 );
  19911. }
  19912. /**
  19913. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19914. *
  19915. * @param {Sphere} sphere - The bounding sphere to test.
  19916. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19917. */
  19918. intersectsSphere( sphere ) {
  19919. const planes = this.planes;
  19920. const center = sphere.center;
  19921. const negRadius = - sphere.radius;
  19922. for ( let i = 0; i < 6; i ++ ) {
  19923. const distance = planes[ i ].distanceToPoint( center );
  19924. if ( distance < negRadius ) {
  19925. return false;
  19926. }
  19927. }
  19928. return true;
  19929. }
  19930. /**
  19931. * Returns `true` if the given bounding box is intersecting this frustum.
  19932. *
  19933. * @param {Box3} box - The bounding box to test.
  19934. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19935. */
  19936. intersectsBox( box ) {
  19937. const planes = this.planes;
  19938. for ( let i = 0; i < 6; i ++ ) {
  19939. const plane = planes[ i ];
  19940. // corner at max distance
  19941. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19942. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19943. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19944. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19945. return false;
  19946. }
  19947. }
  19948. return true;
  19949. }
  19950. /**
  19951. * Returns `true` if the given point lies within the frustum.
  19952. *
  19953. * @param {Vector3} point - The point to test.
  19954. * @return {boolean} Whether the point lies within this frustum or not.
  19955. */
  19956. containsPoint( point ) {
  19957. const planes = this.planes;
  19958. for ( let i = 0; i < 6; i ++ ) {
  19959. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19960. return false;
  19961. }
  19962. }
  19963. return true;
  19964. }
  19965. /**
  19966. * Returns a new frustum with copied values from this instance.
  19967. *
  19968. * @return {Frustum} A clone of this instance.
  19969. */
  19970. clone() {
  19971. return new this.constructor().copy( this );
  19972. }
  19973. }
  19974. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  19975. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19976. /**
  19977. * FrustumArray is used to determine if an object is visible in at least one camera
  19978. * from an array of cameras. This is particularly useful for multi-view renderers.
  19979. */
  19980. class FrustumArray {
  19981. /**
  19982. * Constructs a new frustum array.
  19983. *
  19984. */
  19985. constructor() {
  19986. /**
  19987. * The coordinate system to use.
  19988. *
  19989. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19990. * @default WebGLCoordinateSystem
  19991. */
  19992. this.coordinateSystem = WebGLCoordinateSystem;
  19993. }
  19994. /**
  19995. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19996. * from the camera array.
  19997. *
  19998. * @param {Object3D} object - The 3D object to test.
  19999. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20000. * @return {boolean} Whether the 3D object is visible in any camera.
  20001. */
  20002. intersectsObject( object, cameraArray ) {
  20003. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  20004. return false;
  20005. }
  20006. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20007. const camera = cameraArray.cameras[ i ];
  20008. _projScreenMatrix$1.multiplyMatrices(
  20009. camera.projectionMatrix,
  20010. camera.matrixWorldInverse
  20011. );
  20012. _frustum$1.setFromProjectionMatrix(
  20013. _projScreenMatrix$1,
  20014. camera.coordinateSystem,
  20015. camera.reversedDepth
  20016. );
  20017. if ( _frustum$1.intersectsObject( object ) ) {
  20018. return true; // Object is visible in at least one camera
  20019. }
  20020. }
  20021. return false; // Not visible in any camera
  20022. }
  20023. /**
  20024. * Returns `true` if the given sprite is intersecting any frustum
  20025. * from the camera array.
  20026. *
  20027. * @param {Sprite} sprite - The sprite to test.
  20028. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20029. * @return {boolean} Whether the sprite is visible in any camera.
  20030. */
  20031. intersectsSprite( sprite, cameraArray ) {
  20032. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20033. return false;
  20034. }
  20035. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20036. const camera = cameraArray.cameras[ i ];
  20037. _projScreenMatrix$1.multiplyMatrices(
  20038. camera.projectionMatrix,
  20039. camera.matrixWorldInverse
  20040. );
  20041. _frustum$1.setFromProjectionMatrix(
  20042. _projScreenMatrix$1,
  20043. camera.coordinateSystem,
  20044. camera.reversedDepth
  20045. );
  20046. if ( _frustum$1.intersectsSprite( sprite ) ) {
  20047. return true; // Sprite is visible in at least one camera
  20048. }
  20049. }
  20050. return false; // Not visible in any camera
  20051. }
  20052. /**
  20053. * Returns `true` if the given bounding sphere is intersecting any frustum
  20054. * from the camera array.
  20055. *
  20056. * @param {Sphere} sphere - The bounding sphere to test.
  20057. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20058. * @return {boolean} Whether the sphere is visible in any camera.
  20059. */
  20060. intersectsSphere( sphere, cameraArray ) {
  20061. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20062. return false;
  20063. }
  20064. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20065. const camera = cameraArray.cameras[ i ];
  20066. _projScreenMatrix$1.multiplyMatrices(
  20067. camera.projectionMatrix,
  20068. camera.matrixWorldInverse
  20069. );
  20070. _frustum$1.setFromProjectionMatrix(
  20071. _projScreenMatrix$1,
  20072. camera.coordinateSystem,
  20073. camera.reversedDepth
  20074. );
  20075. if ( _frustum$1.intersectsSphere( sphere ) ) {
  20076. return true; // Sphere is visible in at least one camera
  20077. }
  20078. }
  20079. return false; // Not visible in any camera
  20080. }
  20081. /**
  20082. * Returns `true` if the given bounding box is intersecting any frustum
  20083. * from the camera array.
  20084. *
  20085. * @param {Box3} box - The bounding box to test.
  20086. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20087. * @return {boolean} Whether the box is visible in any camera.
  20088. */
  20089. intersectsBox( box, cameraArray ) {
  20090. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20091. return false;
  20092. }
  20093. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20094. const camera = cameraArray.cameras[ i ];
  20095. _projScreenMatrix$1.multiplyMatrices(
  20096. camera.projectionMatrix,
  20097. camera.matrixWorldInverse
  20098. );
  20099. _frustum$1.setFromProjectionMatrix(
  20100. _projScreenMatrix$1,
  20101. camera.coordinateSystem,
  20102. camera.reversedDepth
  20103. );
  20104. if ( _frustum$1.intersectsBox( box ) ) {
  20105. return true; // Box is visible in at least one camera
  20106. }
  20107. }
  20108. return false; // Not visible in any camera
  20109. }
  20110. /**
  20111. * Returns `true` if the given point lies within any frustum
  20112. * from the camera array.
  20113. *
  20114. * @param {Vector3} point - The point to test.
  20115. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20116. * @return {boolean} Whether the point is visible in any camera.
  20117. */
  20118. containsPoint( point, cameraArray ) {
  20119. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20120. return false;
  20121. }
  20122. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20123. const camera = cameraArray.cameras[ i ];
  20124. _projScreenMatrix$1.multiplyMatrices(
  20125. camera.projectionMatrix,
  20126. camera.matrixWorldInverse
  20127. );
  20128. _frustum$1.setFromProjectionMatrix(
  20129. _projScreenMatrix$1,
  20130. camera.coordinateSystem,
  20131. camera.reversedDepth
  20132. );
  20133. if ( _frustum$1.containsPoint( point ) ) {
  20134. return true; // Point is visible in at least one camera
  20135. }
  20136. }
  20137. return false; // Not visible in any camera
  20138. }
  20139. /**
  20140. * Returns a new frustum array with copied values from this instance.
  20141. *
  20142. * @return {FrustumArray} A clone of this instance.
  20143. */
  20144. clone() {
  20145. return new FrustumArray();
  20146. }
  20147. }
  20148. function ascIdSort( a, b ) {
  20149. return a - b;
  20150. }
  20151. function sortOpaque( a, b ) {
  20152. return a.z - b.z;
  20153. }
  20154. function sortTransparent( a, b ) {
  20155. return b.z - a.z;
  20156. }
  20157. class MultiDrawRenderList {
  20158. constructor() {
  20159. this.index = 0;
  20160. this.pool = [];
  20161. this.list = [];
  20162. }
  20163. push( start, count, z, index ) {
  20164. const pool = this.pool;
  20165. const list = this.list;
  20166. if ( this.index >= pool.length ) {
  20167. pool.push( {
  20168. start: -1,
  20169. count: -1,
  20170. z: -1,
  20171. index: -1,
  20172. } );
  20173. }
  20174. const item = pool[ this.index ];
  20175. list.push( item );
  20176. this.index ++;
  20177. item.start = start;
  20178. item.count = count;
  20179. item.z = z;
  20180. item.index = index;
  20181. }
  20182. reset() {
  20183. this.list.length = 0;
  20184. this.index = 0;
  20185. }
  20186. }
  20187. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  20188. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  20189. const _frustum = /*@__PURE__*/ new Frustum();
  20190. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  20191. const _box$1 = /*@__PURE__*/ new Box3();
  20192. const _sphere$2 = /*@__PURE__*/ new Sphere();
  20193. const _vector$5 = /*@__PURE__*/ new Vector3();
  20194. const _forward$1 = /*@__PURE__*/ new Vector3();
  20195. const _temp = /*@__PURE__*/ new Vector3();
  20196. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  20197. const _mesh = /*@__PURE__*/ new Mesh();
  20198. const _batchIntersects = [];
  20199. // copies data from attribute "src" into "target" starting at "targetOffset"
  20200. function copyAttributeData( src, target, targetOffset = 0 ) {
  20201. const itemSize = target.itemSize;
  20202. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  20203. // use the component getters and setters if the array data cannot
  20204. // be copied directly
  20205. const vertexCount = src.count;
  20206. for ( let i = 0; i < vertexCount; i ++ ) {
  20207. for ( let c = 0; c < itemSize; c ++ ) {
  20208. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  20209. }
  20210. }
  20211. } else {
  20212. // faster copy approach using typed array set function
  20213. target.array.set( src.array, targetOffset * itemSize );
  20214. }
  20215. target.needsUpdate = true;
  20216. }
  20217. // safely copies array contents to a potentially smaller array
  20218. function copyArrayContents( src, target ) {
  20219. if ( src.constructor !== target.constructor ) {
  20220. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  20221. const len = Math.min( src.length, target.length );
  20222. for ( let i = 0; i < len; i ++ ) {
  20223. target[ i ] = src[ i ];
  20224. }
  20225. } else {
  20226. // if the arrays use the same data layout we can use a fast block copy
  20227. const len = Math.min( src.length, target.length );
  20228. target.set( new src.constructor( src.buffer, 0, len ) );
  20229. }
  20230. }
  20231. /**
  20232. * A special version of a mesh with multi draw batch rendering support. Use
  20233. * this class if you have to render a large number of objects with the same
  20234. * material but with different geometries or world transformations. The usage of
  20235. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  20236. * rendering performance in your application.
  20237. *
  20238. * ```js
  20239. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  20240. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  20241. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  20242. *
  20243. * // initialize and add geometries into the batched mesh
  20244. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  20245. * const boxGeometryId = batchedMesh.addGeometry( box );
  20246. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  20247. *
  20248. * // create instances of those geometries
  20249. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  20250. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  20251. *
  20252. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  20253. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  20254. *
  20255. * // position the geometries
  20256. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  20257. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  20258. *
  20259. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  20260. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  20261. *
  20262. * scene.add( batchedMesh );
  20263. * ```
  20264. *
  20265. * @augments Mesh
  20266. */
  20267. class BatchedMesh extends Mesh {
  20268. /**
  20269. * Constructs a new batched mesh.
  20270. *
  20271. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  20272. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  20273. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  20274. * @param {Material|Array<Material>} [material] - The mesh material.
  20275. */
  20276. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  20277. super( new BufferGeometry(), material );
  20278. /**
  20279. * This flag can be used for type testing.
  20280. *
  20281. * @type {boolean}
  20282. * @readonly
  20283. * @default true
  20284. */
  20285. this.isBatchedMesh = true;
  20286. /**
  20287. * When set ot `true`, the individual objects of a batch are frustum culled.
  20288. *
  20289. * @type {boolean}
  20290. * @default true
  20291. */
  20292. this.perObjectFrustumCulled = true;
  20293. /**
  20294. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  20295. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  20296. * rendered front to back.
  20297. *
  20298. * @type {boolean}
  20299. * @default true
  20300. */
  20301. this.sortObjects = true;
  20302. /**
  20303. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  20304. *
  20305. * @type {?Box3}
  20306. * @default null
  20307. */
  20308. this.boundingBox = null;
  20309. /**
  20310. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  20311. *
  20312. * @type {?Sphere}
  20313. * @default null
  20314. */
  20315. this.boundingSphere = null;
  20316. /**
  20317. * Takes a sort a function that is run before render. The function takes a list of instances to
  20318. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  20319. * sort with.
  20320. *
  20321. * @type {?Function}
  20322. * @default null
  20323. */
  20324. this.customSort = null;
  20325. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20326. this._instanceInfo = [];
  20327. this._geometryInfo = [];
  20328. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20329. this._availableInstanceIds = [];
  20330. this._availableGeometryIds = [];
  20331. // used to track where the next point is that geometry should be inserted
  20332. this._nextIndexStart = 0;
  20333. this._nextVertexStart = 0;
  20334. this._geometryCount = 0;
  20335. // flags
  20336. this._visibilityChanged = true;
  20337. this._geometryInitialized = false;
  20338. // cached user options
  20339. this._maxInstanceCount = maxInstanceCount;
  20340. this._maxVertexCount = maxVertexCount;
  20341. this._maxIndexCount = maxIndexCount;
  20342. // buffers for multi draw
  20343. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20344. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20345. this._multiDrawCount = 0;
  20346. this._multiDrawInstances = null;
  20347. // Local matrix per geometry by using data texture
  20348. this._matricesTexture = null;
  20349. this._indirectTexture = null;
  20350. this._colorsTexture = null;
  20351. this._initMatricesTexture();
  20352. this._initIndirectTexture();
  20353. }
  20354. /**
  20355. * The maximum number of individual instances that can be stored in the batch.
  20356. *
  20357. * @type {number}
  20358. * @readonly
  20359. */
  20360. get maxInstanceCount() {
  20361. return this._maxInstanceCount;
  20362. }
  20363. /**
  20364. * The instance count.
  20365. *
  20366. * @type {number}
  20367. * @readonly
  20368. */
  20369. get instanceCount() {
  20370. return this._instanceInfo.length - this._availableInstanceIds.length;
  20371. }
  20372. /**
  20373. * The number of unused vertices.
  20374. *
  20375. * @type {number}
  20376. * @readonly
  20377. */
  20378. get unusedVertexCount() {
  20379. return this._maxVertexCount - this._nextVertexStart;
  20380. }
  20381. /**
  20382. * The number of unused indices.
  20383. *
  20384. * @type {number}
  20385. * @readonly
  20386. */
  20387. get unusedIndexCount() {
  20388. return this._maxIndexCount - this._nextIndexStart;
  20389. }
  20390. _initMatricesTexture() {
  20391. // layout (1 matrix = 4 pixels)
  20392. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20393. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20394. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20395. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20396. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20397. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20398. size = Math.ceil( size / 4 ) * 4;
  20399. size = Math.max( size, 4 );
  20400. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20401. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20402. this._matricesTexture = matricesTexture;
  20403. }
  20404. _initIndirectTexture() {
  20405. let size = Math.sqrt( this._maxInstanceCount );
  20406. size = Math.ceil( size );
  20407. const indirectArray = new Uint32Array( size * size );
  20408. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20409. this._indirectTexture = indirectTexture;
  20410. }
  20411. _initColorsTexture() {
  20412. let size = Math.sqrt( this._maxInstanceCount );
  20413. size = Math.ceil( size );
  20414. // 4 floats per RGBA pixel initialized to white
  20415. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20416. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20417. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20418. this._colorsTexture = colorsTexture;
  20419. }
  20420. _initializeGeometry( reference ) {
  20421. const geometry = this.geometry;
  20422. const maxVertexCount = this._maxVertexCount;
  20423. const maxIndexCount = this._maxIndexCount;
  20424. if ( this._geometryInitialized === false ) {
  20425. for ( const attributeName in reference.attributes ) {
  20426. const srcAttribute = reference.getAttribute( attributeName );
  20427. const { array, itemSize, normalized } = srcAttribute;
  20428. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20429. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20430. geometry.setAttribute( attributeName, dstAttribute );
  20431. }
  20432. if ( reference.getIndex() !== null ) {
  20433. // Reserve last u16 index for primitive restart.
  20434. const indexArray = maxVertexCount > 65535
  20435. ? new Uint32Array( maxIndexCount )
  20436. : new Uint16Array( maxIndexCount );
  20437. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20438. }
  20439. this._geometryInitialized = true;
  20440. }
  20441. }
  20442. // Make sure the geometry is compatible with the existing combined geometry attributes
  20443. _validateGeometry( geometry ) {
  20444. // check to ensure the geometries are using consistent attributes and indices
  20445. const batchGeometry = this.geometry;
  20446. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20447. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20448. }
  20449. for ( const attributeName in batchGeometry.attributes ) {
  20450. if ( ! geometry.hasAttribute( attributeName ) ) {
  20451. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20452. }
  20453. const srcAttribute = geometry.getAttribute( attributeName );
  20454. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20455. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20456. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20457. }
  20458. }
  20459. }
  20460. /**
  20461. * Validates the instance defined by the given ID.
  20462. *
  20463. * @param {number} instanceId - The instance to validate.
  20464. */
  20465. validateInstanceId( instanceId ) {
  20466. const instanceInfo = this._instanceInfo;
  20467. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20468. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20469. }
  20470. }
  20471. /**
  20472. * Validates the geometry defined by the given ID.
  20473. *
  20474. * @param {number} geometryId - The geometry to validate.
  20475. */
  20476. validateGeometryId( geometryId ) {
  20477. const geometryInfoList = this._geometryInfo;
  20478. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20479. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20480. }
  20481. }
  20482. /**
  20483. * Takes a sort a function that is run before render. The function takes a list of instances to
  20484. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20485. *
  20486. * @param {Function} func - The custom sort function.
  20487. * @return {BatchedMesh} A reference to this batched mesh.
  20488. */
  20489. setCustomSort( func ) {
  20490. this.customSort = func;
  20491. return this;
  20492. }
  20493. /**
  20494. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20495. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20496. * otherwise they are `null`.
  20497. */
  20498. computeBoundingBox() {
  20499. if ( this.boundingBox === null ) {
  20500. this.boundingBox = new Box3();
  20501. }
  20502. const boundingBox = this.boundingBox;
  20503. const instanceInfo = this._instanceInfo;
  20504. boundingBox.makeEmpty();
  20505. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20506. if ( instanceInfo[ i ].active === false ) continue;
  20507. const geometryId = instanceInfo[ i ].geometryIndex;
  20508. this.getMatrixAt( i, _matrix$1 );
  20509. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20510. boundingBox.union( _box$1 );
  20511. }
  20512. }
  20513. /**
  20514. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20515. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20516. * otherwise they are `null`.
  20517. */
  20518. computeBoundingSphere() {
  20519. if ( this.boundingSphere === null ) {
  20520. this.boundingSphere = new Sphere();
  20521. }
  20522. const boundingSphere = this.boundingSphere;
  20523. const instanceInfo = this._instanceInfo;
  20524. boundingSphere.makeEmpty();
  20525. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20526. if ( instanceInfo[ i ].active === false ) continue;
  20527. const geometryId = instanceInfo[ i ].geometryIndex;
  20528. this.getMatrixAt( i, _matrix$1 );
  20529. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20530. boundingSphere.union( _sphere$2 );
  20531. }
  20532. }
  20533. /**
  20534. * Adds a new instance to the batch using the geometry of the given ID and returns
  20535. * a new id referring to the new instance to be used by other functions.
  20536. *
  20537. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20538. * @return {number} The instance ID.
  20539. */
  20540. addInstance( geometryId ) {
  20541. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20542. // ensure we're not over geometry
  20543. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20544. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20545. }
  20546. const instanceInfo = {
  20547. visible: true,
  20548. active: true,
  20549. geometryIndex: geometryId,
  20550. };
  20551. let drawId = null;
  20552. // Prioritize using previously freed instance ids
  20553. if ( this._availableInstanceIds.length > 0 ) {
  20554. this._availableInstanceIds.sort( ascIdSort );
  20555. drawId = this._availableInstanceIds.shift();
  20556. this._instanceInfo[ drawId ] = instanceInfo;
  20557. } else {
  20558. drawId = this._instanceInfo.length;
  20559. this._instanceInfo.push( instanceInfo );
  20560. }
  20561. const matricesTexture = this._matricesTexture;
  20562. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20563. matricesTexture.needsUpdate = true;
  20564. const colorsTexture = this._colorsTexture;
  20565. if ( colorsTexture ) {
  20566. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20567. colorsTexture.needsUpdate = true;
  20568. }
  20569. this._visibilityChanged = true;
  20570. return drawId;
  20571. }
  20572. /**
  20573. * Adds the given geometry to the batch and returns the associated
  20574. * geometry id referring to it to be used in other functions.
  20575. *
  20576. * @param {BufferGeometry} geometry - The geometry to add.
  20577. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20578. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20579. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20580. * Defaults to the length of the given geometry vertex buffer.
  20581. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20582. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20583. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20584. * the length of the given geometry index buffer.
  20585. * @return {number} The geometry ID.
  20586. */
  20587. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20588. this._initializeGeometry( geometry );
  20589. this._validateGeometry( geometry );
  20590. const geometryInfo = {
  20591. // geometry information
  20592. vertexStart: -1,
  20593. vertexCount: -1,
  20594. reservedVertexCount: -1,
  20595. indexStart: -1,
  20596. indexCount: -1,
  20597. reservedIndexCount: -1,
  20598. // draw range information
  20599. start: -1,
  20600. count: -1,
  20601. // state
  20602. boundingBox: null,
  20603. boundingSphere: null,
  20604. active: true,
  20605. };
  20606. const geometryInfoList = this._geometryInfo;
  20607. geometryInfo.vertexStart = this._nextVertexStart;
  20608. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20609. const index = geometry.getIndex();
  20610. const hasIndex = index !== null;
  20611. if ( hasIndex ) {
  20612. geometryInfo.indexStart = this._nextIndexStart;
  20613. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20614. }
  20615. if (
  20616. geometryInfo.indexStart !== -1 &&
  20617. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20618. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20619. ) {
  20620. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20621. }
  20622. // update id
  20623. let geometryId;
  20624. if ( this._availableGeometryIds.length > 0 ) {
  20625. this._availableGeometryIds.sort( ascIdSort );
  20626. geometryId = this._availableGeometryIds.shift();
  20627. geometryInfoList[ geometryId ] = geometryInfo;
  20628. } else {
  20629. geometryId = this._geometryCount;
  20630. this._geometryCount ++;
  20631. geometryInfoList.push( geometryInfo );
  20632. }
  20633. // update the geometry
  20634. this.setGeometryAt( geometryId, geometry );
  20635. // increment the next geometry position
  20636. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20637. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20638. return geometryId;
  20639. }
  20640. /**
  20641. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20642. * is not enough space reserved for geometry. Calling this will change all instances that are
  20643. * rendering that geometry.
  20644. *
  20645. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20646. * @param {BufferGeometry} geometry - The new geometry.
  20647. * @return {number} The geometry ID.
  20648. */
  20649. setGeometryAt( geometryId, geometry ) {
  20650. if ( geometryId >= this._geometryCount ) {
  20651. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20652. }
  20653. this._validateGeometry( geometry );
  20654. const batchGeometry = this.geometry;
  20655. const hasIndex = batchGeometry.getIndex() !== null;
  20656. const dstIndex = batchGeometry.getIndex();
  20657. const srcIndex = geometry.getIndex();
  20658. const geometryInfo = this._geometryInfo[ geometryId ];
  20659. if (
  20660. hasIndex &&
  20661. srcIndex.count > geometryInfo.reservedIndexCount ||
  20662. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20663. ) {
  20664. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20665. }
  20666. // copy geometry buffer data over
  20667. const vertexStart = geometryInfo.vertexStart;
  20668. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20669. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20670. for ( const attributeName in batchGeometry.attributes ) {
  20671. // copy attribute data
  20672. const srcAttribute = geometry.getAttribute( attributeName );
  20673. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20674. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20675. // fill the rest in with zeroes
  20676. const itemSize = srcAttribute.itemSize;
  20677. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20678. const index = vertexStart + i;
  20679. for ( let c = 0; c < itemSize; c ++ ) {
  20680. dstAttribute.setComponent( index, c, 0 );
  20681. }
  20682. }
  20683. dstAttribute.needsUpdate = true;
  20684. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20685. }
  20686. // copy index
  20687. if ( hasIndex ) {
  20688. const indexStart = geometryInfo.indexStart;
  20689. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20690. geometryInfo.indexCount = geometry.getIndex().count;
  20691. // copy index data over
  20692. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20693. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20694. }
  20695. // fill the rest in with zeroes
  20696. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20697. dstIndex.setX( indexStart + i, vertexStart );
  20698. }
  20699. dstIndex.needsUpdate = true;
  20700. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20701. }
  20702. // update the draw range
  20703. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20704. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20705. // store the bounding boxes
  20706. geometryInfo.boundingBox = null;
  20707. if ( geometry.boundingBox !== null ) {
  20708. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20709. }
  20710. geometryInfo.boundingSphere = null;
  20711. if ( geometry.boundingSphere !== null ) {
  20712. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20713. }
  20714. this._visibilityChanged = true;
  20715. return geometryId;
  20716. }
  20717. /**
  20718. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20719. * this geometry will also be removed as a side effect.
  20720. *
  20721. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20722. * @return {BatchedMesh} A reference to this batched mesh.
  20723. */
  20724. deleteGeometry( geometryId ) {
  20725. const geometryInfoList = this._geometryInfo;
  20726. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20727. return this;
  20728. }
  20729. // delete any instances associated with this geometry
  20730. const instanceInfo = this._instanceInfo;
  20731. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20732. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20733. this.deleteInstance( i );
  20734. }
  20735. }
  20736. geometryInfoList[ geometryId ].active = false;
  20737. this._availableGeometryIds.push( geometryId );
  20738. this._visibilityChanged = true;
  20739. return this;
  20740. }
  20741. /**
  20742. * Deletes an existing instance from the batch using the given ID.
  20743. *
  20744. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20745. * @return {BatchedMesh} A reference to this batched mesh.
  20746. */
  20747. deleteInstance( instanceId ) {
  20748. this.validateInstanceId( instanceId );
  20749. this._instanceInfo[ instanceId ].active = false;
  20750. this._availableInstanceIds.push( instanceId );
  20751. this._visibilityChanged = true;
  20752. return this;
  20753. }
  20754. /**
  20755. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  20756. * previously deleted geometry, freeing up space to add new geometry.
  20757. *
  20758. * @return {BatchedMesh} A reference to this batched mesh.
  20759. */
  20760. optimize() {
  20761. // track the next indices to copy data to
  20762. let nextVertexStart = 0;
  20763. let nextIndexStart = 0;
  20764. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20765. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20766. const geometryInfoList = this._geometryInfo;
  20767. const indices = geometryInfoList
  20768. .map( ( e, i ) => i )
  20769. .sort( ( a, b ) => {
  20770. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20771. } );
  20772. const geometry = this.geometry;
  20773. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20774. // if a geometry range is inactive then don't copy anything
  20775. const index = indices[ i ];
  20776. const geometryInfo = geometryInfoList[ index ];
  20777. if ( geometryInfo.active === false ) {
  20778. continue;
  20779. }
  20780. // if a geometry contains an index buffer then shift it, as well
  20781. if ( geometry.index !== null ) {
  20782. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20783. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20784. const index = geometry.index;
  20785. const array = index.array;
  20786. // shift the index pointers based on how the vertex data will shift
  20787. // adjusting the index must happen first so the original vertex start value is available
  20788. const elementDelta = nextVertexStart - vertexStart;
  20789. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20790. array[ j ] = array[ j ] + elementDelta;
  20791. }
  20792. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20793. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20794. index.needsUpdate = true;
  20795. geometryInfo.indexStart = nextIndexStart;
  20796. }
  20797. nextIndexStart += geometryInfo.reservedIndexCount;
  20798. }
  20799. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20800. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20801. const { vertexStart, reservedVertexCount } = geometryInfo;
  20802. const attributes = geometry.attributes;
  20803. for ( const key in attributes ) {
  20804. const attribute = attributes[ key ];
  20805. const { array, itemSize } = attribute;
  20806. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20807. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20808. attribute.needsUpdate = true;
  20809. }
  20810. geometryInfo.vertexStart = nextVertexStart;
  20811. }
  20812. nextVertexStart += geometryInfo.reservedVertexCount;
  20813. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20814. }
  20815. this._nextIndexStart = nextIndexStart;
  20816. this._nextVertexStart = nextVertexStart;
  20817. this._visibilityChanged = true;
  20818. return this;
  20819. }
  20820. /**
  20821. * Returns the bounding box for the given geometry.
  20822. *
  20823. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20824. * @param {Box3} target - The target object that is used to store the method's result.
  20825. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20826. */
  20827. getBoundingBoxAt( geometryId, target ) {
  20828. if ( geometryId >= this._geometryCount ) {
  20829. return null;
  20830. }
  20831. // compute bounding box
  20832. const geometry = this.geometry;
  20833. const geometryInfo = this._geometryInfo[ geometryId ];
  20834. if ( geometryInfo.boundingBox === null ) {
  20835. const box = new Box3();
  20836. const index = geometry.index;
  20837. const position = geometry.attributes.position;
  20838. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20839. let iv = i;
  20840. if ( index ) {
  20841. iv = index.getX( iv );
  20842. }
  20843. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20844. }
  20845. geometryInfo.boundingBox = box;
  20846. }
  20847. target.copy( geometryInfo.boundingBox );
  20848. return target;
  20849. }
  20850. /**
  20851. * Returns the bounding sphere for the given geometry.
  20852. *
  20853. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20854. * @param {Sphere} target - The target object that is used to store the method's result.
  20855. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20856. */
  20857. getBoundingSphereAt( geometryId, target ) {
  20858. if ( geometryId >= this._geometryCount ) {
  20859. return null;
  20860. }
  20861. // compute bounding sphere
  20862. const geometry = this.geometry;
  20863. const geometryInfo = this._geometryInfo[ geometryId ];
  20864. if ( geometryInfo.boundingSphere === null ) {
  20865. const sphere = new Sphere();
  20866. this.getBoundingBoxAt( geometryId, _box$1 );
  20867. _box$1.getCenter( sphere.center );
  20868. const index = geometry.index;
  20869. const position = geometry.attributes.position;
  20870. let maxRadiusSq = 0;
  20871. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20872. let iv = i;
  20873. if ( index ) {
  20874. iv = index.getX( iv );
  20875. }
  20876. _vector$5.fromBufferAttribute( position, iv );
  20877. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20878. }
  20879. sphere.radius = Math.sqrt( maxRadiusSq );
  20880. geometryInfo.boundingSphere = sphere;
  20881. }
  20882. target.copy( geometryInfo.boundingSphere );
  20883. return target;
  20884. }
  20885. /**
  20886. * Sets the given local transformation matrix to the defined instance.
  20887. * Negatively scaled matrices are not supported.
  20888. *
  20889. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20890. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20891. * @return {BatchedMesh} A reference to this batched mesh.
  20892. */
  20893. setMatrixAt( instanceId, matrix ) {
  20894. this.validateInstanceId( instanceId );
  20895. const matricesTexture = this._matricesTexture;
  20896. const matricesArray = this._matricesTexture.image.data;
  20897. matrix.toArray( matricesArray, instanceId * 16 );
  20898. matricesTexture.needsUpdate = true;
  20899. return this;
  20900. }
  20901. /**
  20902. * Returns the local transformation matrix of the defined instance.
  20903. *
  20904. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20905. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20906. * @return {Matrix4} The instance's local transformation matrix.
  20907. */
  20908. getMatrixAt( instanceId, matrix ) {
  20909. this.validateInstanceId( instanceId );
  20910. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20911. }
  20912. /**
  20913. * Sets the given color to the defined instance.
  20914. *
  20915. * @param {number} instanceId - The ID of an instance to set the color of.
  20916. * @param {Color|Vector4} color - The color to set the instance to. Use a `Vector4` to also define alpha.
  20917. * @return {BatchedMesh} A reference to this batched mesh.
  20918. */
  20919. setColorAt( instanceId, color ) {
  20920. this.validateInstanceId( instanceId );
  20921. if ( this._colorsTexture === null ) {
  20922. this._initColorsTexture();
  20923. }
  20924. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20925. this._colorsTexture.needsUpdate = true;
  20926. return this;
  20927. }
  20928. /**
  20929. * Returns the color of the defined instance.
  20930. *
  20931. * @param {number} instanceId - The ID of an instance to get the color of.
  20932. * @param {Color|Vector4} color - The target object that is used to store the method's result.
  20933. * @return {Color|Vector4} The instance's color. Use a `Vector4` to also retrieve alpha.
  20934. */
  20935. getColorAt( instanceId, color ) {
  20936. this.validateInstanceId( instanceId );
  20937. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20938. }
  20939. /**
  20940. * Sets the visibility of the instance.
  20941. *
  20942. * @param {number} instanceId - The id of the instance to set the visibility of.
  20943. * @param {boolean} visible - Whether the instance is visible or not.
  20944. * @return {BatchedMesh} A reference to this batched mesh.
  20945. */
  20946. setVisibleAt( instanceId, visible ) {
  20947. this.validateInstanceId( instanceId );
  20948. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20949. return this;
  20950. }
  20951. this._instanceInfo[ instanceId ].visible = visible;
  20952. this._visibilityChanged = true;
  20953. return this;
  20954. }
  20955. /**
  20956. * Returns the visibility state of the defined instance.
  20957. *
  20958. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20959. * @return {boolean} Whether the instance is visible or not.
  20960. */
  20961. getVisibleAt( instanceId ) {
  20962. this.validateInstanceId( instanceId );
  20963. return this._instanceInfo[ instanceId ].visible;
  20964. }
  20965. /**
  20966. * Sets the geometry ID of the instance at the given index.
  20967. *
  20968. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20969. * @param {number} geometryId - The geometry ID to be use by the instance.
  20970. * @return {BatchedMesh} A reference to this batched mesh.
  20971. */
  20972. setGeometryIdAt( instanceId, geometryId ) {
  20973. this.validateInstanceId( instanceId );
  20974. this.validateGeometryId( geometryId );
  20975. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20976. return this;
  20977. }
  20978. /**
  20979. * Returns the geometry ID of the defined instance.
  20980. *
  20981. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20982. * @return {number} The instance's geometry ID.
  20983. */
  20984. getGeometryIdAt( instanceId ) {
  20985. this.validateInstanceId( instanceId );
  20986. return this._instanceInfo[ instanceId ].geometryIndex;
  20987. }
  20988. /**
  20989. * Get the range representing the subset of triangles related to the attached geometry,
  20990. * indicating the starting offset and count, or `null` if invalid.
  20991. *
  20992. * @param {number} geometryId - The id of the geometry to get the range of.
  20993. * @param {Object} [target] - The target object that is used to store the method's result.
  20994. * @return {{
  20995. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20996. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20997. * start:number,count:number
  20998. * }} The result object with range data.
  20999. */
  21000. getGeometryRangeAt( geometryId, target = {} ) {
  21001. this.validateGeometryId( geometryId );
  21002. const geometryInfo = this._geometryInfo[ geometryId ];
  21003. target.vertexStart = geometryInfo.vertexStart;
  21004. target.vertexCount = geometryInfo.vertexCount;
  21005. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  21006. target.indexStart = geometryInfo.indexStart;
  21007. target.indexCount = geometryInfo.indexCount;
  21008. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  21009. target.start = geometryInfo.start;
  21010. target.count = geometryInfo.count;
  21011. return target;
  21012. }
  21013. /**
  21014. * Resizes the necessary buffers to support the provided number of instances.
  21015. * If the provided arguments shrink the number of instances but there are not enough
  21016. * unused Ids at the end of the list then an error is thrown.
  21017. *
  21018. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  21019. */
  21020. setInstanceCount( maxInstanceCount ) {
  21021. // shrink the available instances as much as possible
  21022. const availableInstanceIds = this._availableInstanceIds;
  21023. const instanceInfo = this._instanceInfo;
  21024. availableInstanceIds.sort( ascIdSort );
  21025. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  21026. instanceInfo.pop();
  21027. availableInstanceIds.pop();
  21028. }
  21029. // throw an error if it can't be shrunk to the desired size
  21030. if ( maxInstanceCount < instanceInfo.length ) {
  21031. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  21032. }
  21033. // copy the multi draw counts
  21034. const multiDrawCounts = new Int32Array( maxInstanceCount );
  21035. const multiDrawStarts = new Int32Array( maxInstanceCount );
  21036. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  21037. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  21038. this._multiDrawCounts = multiDrawCounts;
  21039. this._multiDrawStarts = multiDrawStarts;
  21040. this._maxInstanceCount = maxInstanceCount;
  21041. // update texture data for instance sampling
  21042. const indirectTexture = this._indirectTexture;
  21043. const matricesTexture = this._matricesTexture;
  21044. const colorsTexture = this._colorsTexture;
  21045. indirectTexture.dispose();
  21046. this._initIndirectTexture();
  21047. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  21048. matricesTexture.dispose();
  21049. this._initMatricesTexture();
  21050. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  21051. if ( colorsTexture ) {
  21052. colorsTexture.dispose();
  21053. this._initColorsTexture();
  21054. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  21055. }
  21056. }
  21057. /**
  21058. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  21059. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  21060. * end of the geometry attributes then an error is thrown.
  21061. *
  21062. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  21063. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  21064. */
  21065. setGeometrySize( maxVertexCount, maxIndexCount ) {
  21066. // Check if we can shrink to the requested vertex attribute size
  21067. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  21068. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  21069. if ( requiredVertexLength > maxVertexCount ) {
  21070. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  21071. }
  21072. // Check if we can shrink to the requested index attribute size
  21073. if ( this.geometry.index ) {
  21074. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  21075. if ( requiredIndexLength > maxIndexCount ) {
  21076. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  21077. }
  21078. }
  21079. //
  21080. // dispose of the previous geometry
  21081. const oldGeometry = this.geometry;
  21082. oldGeometry.dispose();
  21083. // recreate the geometry needed based on the previous variant
  21084. this._maxVertexCount = maxVertexCount;
  21085. this._maxIndexCount = maxIndexCount;
  21086. if ( this._geometryInitialized ) {
  21087. this._geometryInitialized = false;
  21088. this.geometry = new BufferGeometry();
  21089. this._initializeGeometry( oldGeometry );
  21090. }
  21091. // copy data from the previous geometry
  21092. const geometry = this.geometry;
  21093. if ( oldGeometry.index ) {
  21094. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  21095. }
  21096. for ( const key in oldGeometry.attributes ) {
  21097. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  21098. }
  21099. }
  21100. raycast( raycaster, intersects ) {
  21101. const instanceInfo = this._instanceInfo;
  21102. const geometryInfoList = this._geometryInfo;
  21103. const matrixWorld = this.matrixWorld;
  21104. const batchGeometry = this.geometry;
  21105. // iterate over each geometry
  21106. _mesh.material = this.material;
  21107. _mesh.geometry.index = batchGeometry.index;
  21108. _mesh.geometry.attributes = batchGeometry.attributes;
  21109. if ( _mesh.geometry.boundingBox === null ) {
  21110. _mesh.geometry.boundingBox = new Box3();
  21111. }
  21112. if ( _mesh.geometry.boundingSphere === null ) {
  21113. _mesh.geometry.boundingSphere = new Sphere();
  21114. }
  21115. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21116. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  21117. continue;
  21118. }
  21119. const geometryId = instanceInfo[ i ].geometryIndex;
  21120. const geometryInfo = geometryInfoList[ geometryId ];
  21121. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  21122. // get the intersects
  21123. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  21124. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  21125. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  21126. _mesh.raycast( raycaster, _batchIntersects );
  21127. // add batch id to the intersects
  21128. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  21129. const intersect = _batchIntersects[ j ];
  21130. intersect.object = this;
  21131. intersect.batchId = i;
  21132. intersects.push( intersect );
  21133. }
  21134. _batchIntersects.length = 0;
  21135. }
  21136. _mesh.material = null;
  21137. _mesh.geometry.index = null;
  21138. _mesh.geometry.attributes = {};
  21139. _mesh.geometry.setDrawRange( 0, Infinity );
  21140. }
  21141. copy( source ) {
  21142. super.copy( source );
  21143. this.geometry = source.geometry.clone();
  21144. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  21145. this.sortObjects = source.sortObjects;
  21146. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  21147. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  21148. this._geometryInfo = source._geometryInfo.map( info => ( {
  21149. ...info,
  21150. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  21151. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  21152. } ) );
  21153. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  21154. this._availableInstanceIds = source._availableInstanceIds.slice();
  21155. this._availableGeometryIds = source._availableGeometryIds.slice();
  21156. this._nextIndexStart = source._nextIndexStart;
  21157. this._nextVertexStart = source._nextVertexStart;
  21158. this._geometryCount = source._geometryCount;
  21159. this._maxInstanceCount = source._maxInstanceCount;
  21160. this._maxVertexCount = source._maxVertexCount;
  21161. this._maxIndexCount = source._maxIndexCount;
  21162. this._geometryInitialized = source._geometryInitialized;
  21163. this._multiDrawCounts = source._multiDrawCounts.slice();
  21164. this._multiDrawStarts = source._multiDrawStarts.slice();
  21165. this._indirectTexture = source._indirectTexture.clone();
  21166. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  21167. this._matricesTexture = source._matricesTexture.clone();
  21168. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  21169. if ( this._colorsTexture !== null ) {
  21170. this._colorsTexture = source._colorsTexture.clone();
  21171. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  21172. }
  21173. return this;
  21174. }
  21175. /**
  21176. * Frees the GPU-related resources allocated by this instance. Call this
  21177. * method whenever this instance is no longer used in your app.
  21178. */
  21179. dispose() {
  21180. // Assuming the geometry is not shared with other meshes
  21181. this.geometry.dispose();
  21182. this._matricesTexture.dispose();
  21183. this._matricesTexture = null;
  21184. this._indirectTexture.dispose();
  21185. this._indirectTexture = null;
  21186. if ( this._colorsTexture !== null ) {
  21187. this._colorsTexture.dispose();
  21188. this._colorsTexture = null;
  21189. }
  21190. }
  21191. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  21192. // if visibility has not changed and frustum culling and object sorting is not required
  21193. // then skip iterating over all items
  21194. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  21195. return;
  21196. }
  21197. // the indexed version of the multi draw function requires specifying the start
  21198. // offset in bytes.
  21199. const index = geometry.getIndex();
  21200. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  21201. const instanceInfo = this._instanceInfo;
  21202. const multiDrawStarts = this._multiDrawStarts;
  21203. const multiDrawCounts = this._multiDrawCounts;
  21204. const geometryInfoList = this._geometryInfo;
  21205. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  21206. const indirectTexture = this._indirectTexture;
  21207. const indirectArray = indirectTexture.image.data;
  21208. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  21209. // prepare the frustum in the local frame
  21210. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  21211. _matrix$1
  21212. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  21213. .multiply( this.matrixWorld );
  21214. _frustum.setFromProjectionMatrix(
  21215. _matrix$1,
  21216. camera.coordinateSystem,
  21217. camera.reversedDepth
  21218. );
  21219. }
  21220. let multiDrawCount = 0;
  21221. if ( this.sortObjects ) {
  21222. // get the camera position in the local frame
  21223. _matrix$1.copy( this.matrixWorld ).invert();
  21224. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  21225. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  21226. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21227. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21228. const geometryId = instanceInfo[ i ].geometryIndex;
  21229. // get the bounds in world space
  21230. this.getMatrixAt( i, _matrix$1 );
  21231. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21232. // determine whether the batched geometry is within the frustum
  21233. let culled = false;
  21234. if ( perObjectFrustumCulled ) {
  21235. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21236. }
  21237. if ( ! culled ) {
  21238. // get the distance from camera used for sorting
  21239. const geometryInfo = geometryInfoList[ geometryId ];
  21240. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  21241. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  21242. }
  21243. }
  21244. }
  21245. // Sort the draw ranges and prep for rendering
  21246. const list = _renderList.list;
  21247. const customSort = this.customSort;
  21248. if ( customSort === null ) {
  21249. list.sort( material.transparent ? sortTransparent : sortOpaque );
  21250. } else {
  21251. customSort.call( this, list, camera );
  21252. }
  21253. for ( let i = 0, l = list.length; i < l; i ++ ) {
  21254. const item = list[ i ];
  21255. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  21256. multiDrawCounts[ multiDrawCount ] = item.count;
  21257. indirectArray[ multiDrawCount ] = item.index;
  21258. multiDrawCount ++;
  21259. }
  21260. _renderList.reset();
  21261. } else {
  21262. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21263. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21264. const geometryId = instanceInfo[ i ].geometryIndex;
  21265. // determine whether the batched geometry is within the frustum
  21266. let culled = false;
  21267. if ( perObjectFrustumCulled ) {
  21268. // get the bounds in world space
  21269. this.getMatrixAt( i, _matrix$1 );
  21270. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21271. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21272. }
  21273. if ( ! culled ) {
  21274. const geometryInfo = geometryInfoList[ geometryId ];
  21275. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  21276. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  21277. indirectArray[ multiDrawCount ] = i;
  21278. multiDrawCount ++;
  21279. }
  21280. }
  21281. }
  21282. }
  21283. indirectTexture.needsUpdate = true;
  21284. this._multiDrawCount = multiDrawCount;
  21285. this._visibilityChanged = false;
  21286. }
  21287. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  21288. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  21289. }
  21290. }
  21291. /**
  21292. * A material for rendering line primitives.
  21293. *
  21294. * Materials define the appearance of renderable 3D objects.
  21295. *
  21296. * ```js
  21297. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  21298. * ```
  21299. *
  21300. * @augments Material
  21301. */
  21302. class LineBasicMaterial extends Material {
  21303. /**
  21304. * Constructs a new line basic material.
  21305. *
  21306. * @param {Object} [parameters] - An object with one or more properties
  21307. * defining the material's appearance. Any property of the material
  21308. * (including any property from inherited materials) can be passed
  21309. * in here. Color values can be passed any type of value accepted
  21310. * by {@link Color#set}.
  21311. */
  21312. constructor( parameters ) {
  21313. super();
  21314. /**
  21315. * This flag can be used for type testing.
  21316. *
  21317. * @type {boolean}
  21318. * @readonly
  21319. * @default true
  21320. */
  21321. this.isLineBasicMaterial = true;
  21322. this.type = 'LineBasicMaterial';
  21323. /**
  21324. * Color of the material.
  21325. *
  21326. * @type {Color}
  21327. * @default (1,1,1)
  21328. */
  21329. this.color = new Color( 0xffffff );
  21330. /**
  21331. * Sets the color of the lines using data from a texture. The texture map
  21332. * color is modulated by the diffuse `color`.
  21333. *
  21334. * @type {?Texture}
  21335. * @default null
  21336. */
  21337. this.map = null;
  21338. /**
  21339. * Controls line thickness or lines.
  21340. *
  21341. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21342. * ignore this setting and always render line primitives with a
  21343. * width of one pixel.
  21344. *
  21345. * @type {number}
  21346. * @default 1
  21347. */
  21348. this.linewidth = 1;
  21349. /**
  21350. * Defines appearance of line ends.
  21351. *
  21352. * Can only be used with {@link SVGRenderer}.
  21353. *
  21354. * @type {('butt'|'round'|'square')}
  21355. * @default 'round'
  21356. */
  21357. this.linecap = 'round';
  21358. /**
  21359. * Defines appearance of line joints.
  21360. *
  21361. * Can only be used with {@link SVGRenderer}.
  21362. *
  21363. * @type {('round'|'bevel'|'miter')}
  21364. * @default 'round'
  21365. */
  21366. this.linejoin = 'round';
  21367. /**
  21368. * Whether the material is affected by fog or not.
  21369. *
  21370. * @type {boolean}
  21371. * @default true
  21372. */
  21373. this.fog = true;
  21374. this.setValues( parameters );
  21375. }
  21376. copy( source ) {
  21377. super.copy( source );
  21378. this.color.copy( source.color );
  21379. this.map = source.map;
  21380. this.linewidth = source.linewidth;
  21381. this.linecap = source.linecap;
  21382. this.linejoin = source.linejoin;
  21383. this.fog = source.fog;
  21384. return this;
  21385. }
  21386. }
  21387. const _vStart = /*@__PURE__*/ new Vector3();
  21388. const _vEnd = /*@__PURE__*/ new Vector3();
  21389. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21390. const _ray$1 = /*@__PURE__*/ new Ray();
  21391. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21392. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21393. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21394. /**
  21395. * A continuous line. The line are rendered by connecting consecutive
  21396. * vertices with straight lines.
  21397. *
  21398. * ```js
  21399. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21400. *
  21401. * const points = [];
  21402. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21403. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21404. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21405. *
  21406. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21407. *
  21408. * const line = new THREE.Line( geometry, material );
  21409. * scene.add( line );
  21410. * ```
  21411. *
  21412. * @augments Object3D
  21413. */
  21414. class Line extends Object3D {
  21415. /**
  21416. * Constructs a new line.
  21417. *
  21418. * @param {BufferGeometry} [geometry] - The line geometry.
  21419. * @param {Material|Array<Material>} [material] - The line material.
  21420. */
  21421. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21422. super();
  21423. /**
  21424. * This flag can be used for type testing.
  21425. *
  21426. * @type {boolean}
  21427. * @readonly
  21428. * @default true
  21429. */
  21430. this.isLine = true;
  21431. this.type = 'Line';
  21432. /**
  21433. * The line geometry.
  21434. *
  21435. * @type {BufferGeometry}
  21436. */
  21437. this.geometry = geometry;
  21438. /**
  21439. * The line material.
  21440. *
  21441. * @type {Material|Array<Material>}
  21442. * @default LineBasicMaterial
  21443. */
  21444. this.material = material;
  21445. /**
  21446. * A dictionary representing the morph targets in the geometry. The key is the
  21447. * morph targets name, the value its attribute index. This member is `undefined`
  21448. * by default and only set when morph targets are detected in the geometry.
  21449. *
  21450. * @type {Object<string,number>|undefined}
  21451. * @default undefined
  21452. */
  21453. this.morphTargetDictionary = undefined;
  21454. /**
  21455. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21456. * is applied. This member is `undefined` by default and only set when morph targets are
  21457. * detected in the geometry.
  21458. *
  21459. * @type {Array<number>|undefined}
  21460. * @default undefined
  21461. */
  21462. this.morphTargetInfluences = undefined;
  21463. this.updateMorphTargets();
  21464. }
  21465. copy( source, recursive ) {
  21466. super.copy( source, recursive );
  21467. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21468. this.geometry = source.geometry;
  21469. return this;
  21470. }
  21471. /**
  21472. * Computes an array of distance values which are necessary for rendering dashed lines.
  21473. * For each vertex in the geometry, the method calculates the cumulative length from the
  21474. * current point to the very beginning of the line.
  21475. *
  21476. * @return {Line} A reference to this line.
  21477. */
  21478. computeLineDistances() {
  21479. const geometry = this.geometry;
  21480. // we assume non-indexed geometry
  21481. if ( geometry.index === null ) {
  21482. const positionAttribute = geometry.attributes.position;
  21483. const lineDistances = [ 0 ];
  21484. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21485. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21486. _vEnd.fromBufferAttribute( positionAttribute, i );
  21487. lineDistances[ i ] = lineDistances[ i - 1 ];
  21488. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21489. }
  21490. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21491. } else {
  21492. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21493. }
  21494. return this;
  21495. }
  21496. /**
  21497. * Computes intersection points between a casted ray and this line.
  21498. *
  21499. * @param {Raycaster} raycaster - The raycaster.
  21500. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21501. */
  21502. raycast( raycaster, intersects ) {
  21503. const geometry = this.geometry;
  21504. const matrixWorld = this.matrixWorld;
  21505. const threshold = raycaster.params.Line.threshold;
  21506. const drawRange = geometry.drawRange;
  21507. // Checking boundingSphere distance to ray
  21508. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21509. _sphere$1.copy( geometry.boundingSphere );
  21510. _sphere$1.applyMatrix4( matrixWorld );
  21511. _sphere$1.radius += threshold;
  21512. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21513. //
  21514. _inverseMatrix$1.copy( matrixWorld ).invert();
  21515. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21516. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21517. const localThresholdSq = localThreshold * localThreshold;
  21518. const step = this.isLineSegments ? 2 : 1;
  21519. const index = geometry.index;
  21520. const attributes = geometry.attributes;
  21521. const positionAttribute = attributes.position;
  21522. if ( index !== null ) {
  21523. const start = Math.max( 0, drawRange.start );
  21524. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21525. for ( let i = start, l = end - 1; i < l; i += step ) {
  21526. const a = index.getX( i );
  21527. const b = index.getX( i + 1 );
  21528. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21529. if ( intersect ) {
  21530. intersects.push( intersect );
  21531. }
  21532. }
  21533. if ( this.isLineLoop ) {
  21534. const a = index.getX( end - 1 );
  21535. const b = index.getX( start );
  21536. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21537. if ( intersect ) {
  21538. intersects.push( intersect );
  21539. }
  21540. }
  21541. } else {
  21542. const start = Math.max( 0, drawRange.start );
  21543. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21544. for ( let i = start, l = end - 1; i < l; i += step ) {
  21545. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21546. if ( intersect ) {
  21547. intersects.push( intersect );
  21548. }
  21549. }
  21550. if ( this.isLineLoop ) {
  21551. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21552. if ( intersect ) {
  21553. intersects.push( intersect );
  21554. }
  21555. }
  21556. }
  21557. }
  21558. /**
  21559. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21560. * to make sure existing morph targets can influence this 3D object.
  21561. */
  21562. updateMorphTargets() {
  21563. const geometry = this.geometry;
  21564. const morphAttributes = geometry.morphAttributes;
  21565. const keys = Object.keys( morphAttributes );
  21566. if ( keys.length > 0 ) {
  21567. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21568. if ( morphAttribute !== undefined ) {
  21569. this.morphTargetInfluences = [];
  21570. this.morphTargetDictionary = {};
  21571. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21572. const name = morphAttribute[ m ].name || String( m );
  21573. this.morphTargetInfluences.push( 0 );
  21574. this.morphTargetDictionary[ name ] = m;
  21575. }
  21576. }
  21577. }
  21578. }
  21579. }
  21580. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21581. const positionAttribute = object.geometry.attributes.position;
  21582. _vStart.fromBufferAttribute( positionAttribute, a );
  21583. _vEnd.fromBufferAttribute( positionAttribute, b );
  21584. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21585. if ( distSq > thresholdSq ) return;
  21586. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21587. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21588. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21589. return {
  21590. distance: distance,
  21591. // What do we want? intersection point on the ray or on the segment??
  21592. // point: raycaster.ray.at( distance ),
  21593. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21594. index: i,
  21595. face: null,
  21596. faceIndex: null,
  21597. barycoord: null,
  21598. object: object
  21599. };
  21600. }
  21601. const _start = /*@__PURE__*/ new Vector3();
  21602. const _end = /*@__PURE__*/ new Vector3();
  21603. /**
  21604. * A series of lines drawn between pairs of vertices.
  21605. *
  21606. * @augments Line
  21607. */
  21608. class LineSegments extends Line {
  21609. /**
  21610. * Constructs a new line segments.
  21611. *
  21612. * @param {BufferGeometry} [geometry] - The line geometry.
  21613. * @param {Material|Array<Material>} [material] - The line material.
  21614. */
  21615. constructor( geometry, material ) {
  21616. super( geometry, material );
  21617. /**
  21618. * This flag can be used for type testing.
  21619. *
  21620. * @type {boolean}
  21621. * @readonly
  21622. * @default true
  21623. */
  21624. this.isLineSegments = true;
  21625. this.type = 'LineSegments';
  21626. }
  21627. computeLineDistances() {
  21628. const geometry = this.geometry;
  21629. // we assume non-indexed geometry
  21630. if ( geometry.index === null ) {
  21631. const positionAttribute = geometry.attributes.position;
  21632. const lineDistances = [];
  21633. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21634. _start.fromBufferAttribute( positionAttribute, i );
  21635. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21636. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21637. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21638. }
  21639. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21640. } else {
  21641. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21642. }
  21643. return this;
  21644. }
  21645. }
  21646. /**
  21647. * A continuous line. This is nearly the same as {@link Line} the only difference
  21648. * is that the last vertex is connected with the first vertex in order to close
  21649. * the line to form a loop.
  21650. *
  21651. * @augments Line
  21652. */
  21653. class LineLoop extends Line {
  21654. /**
  21655. * Constructs a new line loop.
  21656. *
  21657. * @param {BufferGeometry} [geometry] - The line geometry.
  21658. * @param {Material|Array<Material>} [material] - The line material.
  21659. */
  21660. constructor( geometry, material ) {
  21661. super( geometry, material );
  21662. /**
  21663. * This flag can be used for type testing.
  21664. *
  21665. * @type {boolean}
  21666. * @readonly
  21667. * @default true
  21668. */
  21669. this.isLineLoop = true;
  21670. this.type = 'LineLoop';
  21671. }
  21672. }
  21673. /**
  21674. * A material for rendering point primitives.
  21675. *
  21676. * Materials define the appearance of renderable 3D objects.
  21677. *
  21678. * ```js
  21679. * const vertices = [];
  21680. *
  21681. * for ( let i = 0; i < 10000; i ++ ) {
  21682. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21683. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21684. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21685. *
  21686. * vertices.push( x, y, z );
  21687. * }
  21688. *
  21689. * const geometry = new THREE.BufferGeometry();
  21690. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21691. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21692. * const points = new THREE.Points( geometry, material );
  21693. * scene.add( points );
  21694. * ```
  21695. *
  21696. * @augments Material
  21697. */
  21698. class PointsMaterial extends Material {
  21699. /**
  21700. * Constructs a new points material.
  21701. *
  21702. * @param {Object} [parameters] - An object with one or more properties
  21703. * defining the material's appearance. Any property of the material
  21704. * (including any property from inherited materials) can be passed
  21705. * in here. Color values can be passed any type of value accepted
  21706. * by {@link Color#set}.
  21707. */
  21708. constructor( parameters ) {
  21709. super();
  21710. /**
  21711. * This flag can be used for type testing.
  21712. *
  21713. * @type {boolean}
  21714. * @readonly
  21715. * @default true
  21716. */
  21717. this.isPointsMaterial = true;
  21718. this.type = 'PointsMaterial';
  21719. /**
  21720. * Color of the material.
  21721. *
  21722. * @type {Color}
  21723. * @default (1,1,1)
  21724. */
  21725. this.color = new Color( 0xffffff );
  21726. /**
  21727. * The color map. May optionally include an alpha channel, typically combined
  21728. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21729. * color is modulated by the diffuse `color`.
  21730. *
  21731. * @type {?Texture}
  21732. * @default null
  21733. */
  21734. this.map = null;
  21735. /**
  21736. * The alpha map is a grayscale texture that controls the opacity across the
  21737. * surface (black: fully transparent; white: fully opaque).
  21738. *
  21739. * Only the color of the texture is used, ignoring the alpha channel if one
  21740. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21741. * when sampling this texture due to the extra bit of precision provided for
  21742. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21743. * luminance/alpha textures will also still work as expected.
  21744. *
  21745. * @type {?Texture}
  21746. * @default null
  21747. */
  21748. this.alphaMap = null;
  21749. /**
  21750. * Defines the size of the points in pixels.
  21751. *
  21752. * 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).
  21753. *
  21754. * @type {number}
  21755. * @default 1
  21756. */
  21757. this.size = 1;
  21758. /**
  21759. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21760. *
  21761. * @type {boolean}
  21762. * @default true
  21763. */
  21764. this.sizeAttenuation = true;
  21765. /**
  21766. * Whether the material is affected by fog or not.
  21767. *
  21768. * @type {boolean}
  21769. * @default true
  21770. */
  21771. this.fog = true;
  21772. this.setValues( parameters );
  21773. }
  21774. copy( source ) {
  21775. super.copy( source );
  21776. this.color.copy( source.color );
  21777. this.map = source.map;
  21778. this.alphaMap = source.alphaMap;
  21779. this.size = source.size;
  21780. this.sizeAttenuation = source.sizeAttenuation;
  21781. this.fog = source.fog;
  21782. return this;
  21783. }
  21784. }
  21785. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21786. const _ray = /*@__PURE__*/ new Ray();
  21787. const _sphere = /*@__PURE__*/ new Sphere();
  21788. const _position$2 = /*@__PURE__*/ new Vector3();
  21789. /**
  21790. * A class for displaying points or point clouds.
  21791. *
  21792. * @augments Object3D
  21793. */
  21794. class Points extends Object3D {
  21795. /**
  21796. * Constructs a new point cloud.
  21797. *
  21798. * @param {BufferGeometry} [geometry] - The points geometry.
  21799. * @param {Material|Array<Material>} [material] - The points material.
  21800. */
  21801. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21802. super();
  21803. /**
  21804. * This flag can be used for type testing.
  21805. *
  21806. * @type {boolean}
  21807. * @readonly
  21808. * @default true
  21809. */
  21810. this.isPoints = true;
  21811. this.type = 'Points';
  21812. /**
  21813. * The points geometry.
  21814. *
  21815. * @type {BufferGeometry}
  21816. */
  21817. this.geometry = geometry;
  21818. /**
  21819. * The line material.
  21820. *
  21821. * @type {Material|Array<Material>}
  21822. * @default PointsMaterial
  21823. */
  21824. this.material = material;
  21825. /**
  21826. * A dictionary representing the morph targets in the geometry. The key is the
  21827. * morph targets name, the value its attribute index. This member is `undefined`
  21828. * by default and only set when morph targets are detected in the geometry.
  21829. *
  21830. * @type {Object<string,number>|undefined}
  21831. * @default undefined
  21832. */
  21833. this.morphTargetDictionary = undefined;
  21834. /**
  21835. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21836. * is applied. This member is `undefined` by default and only set when morph targets are
  21837. * detected in the geometry.
  21838. *
  21839. * @type {Array<number>|undefined}
  21840. * @default undefined
  21841. */
  21842. this.morphTargetInfluences = undefined;
  21843. this.updateMorphTargets();
  21844. }
  21845. copy( source, recursive ) {
  21846. super.copy( source, recursive );
  21847. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21848. this.geometry = source.geometry;
  21849. return this;
  21850. }
  21851. /**
  21852. * Computes intersection points between a casted ray and this point cloud.
  21853. *
  21854. * @param {Raycaster} raycaster - The raycaster.
  21855. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21856. */
  21857. raycast( raycaster, intersects ) {
  21858. const geometry = this.geometry;
  21859. const matrixWorld = this.matrixWorld;
  21860. const threshold = raycaster.params.Points.threshold;
  21861. const drawRange = geometry.drawRange;
  21862. // Checking boundingSphere distance to ray
  21863. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21864. _sphere.copy( geometry.boundingSphere );
  21865. _sphere.applyMatrix4( matrixWorld );
  21866. _sphere.radius += threshold;
  21867. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21868. //
  21869. _inverseMatrix.copy( matrixWorld ).invert();
  21870. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21871. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21872. const localThresholdSq = localThreshold * localThreshold;
  21873. const index = geometry.index;
  21874. const attributes = geometry.attributes;
  21875. const positionAttribute = attributes.position;
  21876. if ( index !== null ) {
  21877. const start = Math.max( 0, drawRange.start );
  21878. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21879. for ( let i = start, il = end; i < il; i ++ ) {
  21880. const a = index.getX( i );
  21881. _position$2.fromBufferAttribute( positionAttribute, a );
  21882. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21883. }
  21884. } else {
  21885. const start = Math.max( 0, drawRange.start );
  21886. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21887. for ( let i = start, l = end; i < l; i ++ ) {
  21888. _position$2.fromBufferAttribute( positionAttribute, i );
  21889. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21890. }
  21891. }
  21892. }
  21893. /**
  21894. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21895. * to make sure existing morph targets can influence this 3D object.
  21896. */
  21897. updateMorphTargets() {
  21898. const geometry = this.geometry;
  21899. const morphAttributes = geometry.morphAttributes;
  21900. const keys = Object.keys( morphAttributes );
  21901. if ( keys.length > 0 ) {
  21902. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21903. if ( morphAttribute !== undefined ) {
  21904. this.morphTargetInfluences = [];
  21905. this.morphTargetDictionary = {};
  21906. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21907. const name = morphAttribute[ m ].name || String( m );
  21908. this.morphTargetInfluences.push( 0 );
  21909. this.morphTargetDictionary[ name ] = m;
  21910. }
  21911. }
  21912. }
  21913. }
  21914. }
  21915. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21916. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21917. if ( rayPointDistanceSq < localThresholdSq ) {
  21918. const intersectPoint = new Vector3();
  21919. _ray.closestPointToPoint( point, intersectPoint );
  21920. intersectPoint.applyMatrix4( matrixWorld );
  21921. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21922. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21923. intersects.push( {
  21924. distance: distance,
  21925. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21926. point: intersectPoint,
  21927. index: index,
  21928. face: null,
  21929. faceIndex: null,
  21930. barycoord: null,
  21931. object: object
  21932. } );
  21933. }
  21934. }
  21935. /**
  21936. * A texture for use with a video.
  21937. *
  21938. * ```js
  21939. * // assuming you have created a HTML video element with id="video"
  21940. * const video = document.getElementById( 'video' );
  21941. * const texture = new THREE.VideoTexture( video );
  21942. * ```
  21943. *
  21944. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21945. * set to THREE.SRGBColorSpace.
  21946. *
  21947. * Note: After the initial use of a texture, its dimensions, format, and type
  21948. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21949. *
  21950. * @augments Texture
  21951. */
  21952. class VideoTexture extends Texture {
  21953. /**
  21954. * Constructs a new video texture.
  21955. *
  21956. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21957. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21958. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21959. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21960. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21961. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21962. * @param {number} [format=RGBAFormat] - The texture format.
  21963. * @param {number} [type=UnsignedByteType] - The texture type.
  21964. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21965. */
  21966. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21967. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21968. /**
  21969. * This flag can be used for type testing.
  21970. *
  21971. * @type {boolean}
  21972. * @readonly
  21973. * @default true
  21974. */
  21975. this.isVideoTexture = true;
  21976. /**
  21977. * Whether to generate mipmaps (if possible) for a texture.
  21978. *
  21979. * Overwritten and set to `false` by default.
  21980. *
  21981. * @type {boolean}
  21982. * @default false
  21983. */
  21984. this.generateMipmaps = false;
  21985. /**
  21986. * The video frame request callback identifier, which is a positive integer.
  21987. *
  21988. * Value of 0 represents no scheduled rVFC.
  21989. *
  21990. * @private
  21991. * @type {number}
  21992. */
  21993. this._requestVideoFrameCallbackId = 0;
  21994. const scope = this;
  21995. function updateVideo() {
  21996. scope.needsUpdate = true;
  21997. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21998. }
  21999. if ( 'requestVideoFrameCallback' in video ) {
  22000. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  22001. }
  22002. }
  22003. clone() {
  22004. return new this.constructor( this.image ).copy( this );
  22005. }
  22006. /**
  22007. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  22008. * to `true` every time a new frame is available.
  22009. *
  22010. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  22011. */
  22012. update() {
  22013. const video = this.image;
  22014. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  22015. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  22016. this.needsUpdate = true;
  22017. }
  22018. }
  22019. dispose() {
  22020. if ( this._requestVideoFrameCallbackId !== 0 ) {
  22021. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  22022. this._requestVideoFrameCallbackId = 0;
  22023. }
  22024. super.dispose();
  22025. }
  22026. }
  22027. /**
  22028. * This class can be used as an alternative way to define video data. Instead of using
  22029. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  22030. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  22031. * video frames are decoded with the WebCodecs API.
  22032. *
  22033. * ```js
  22034. * const texture = new THREE.VideoFrameTexture();
  22035. * texture.setFrame( frame );
  22036. * ```
  22037. *
  22038. * @augments VideoTexture
  22039. */
  22040. class VideoFrameTexture extends VideoTexture {
  22041. /**
  22042. * Constructs a new video frame texture.
  22043. *
  22044. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22045. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22046. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22047. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22048. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22049. * @param {number} [format=RGBAFormat] - The texture format.
  22050. * @param {number} [type=UnsignedByteType] - The texture type.
  22051. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22052. */
  22053. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22054. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22055. /**
  22056. * This flag can be used for type testing.
  22057. *
  22058. * @type {boolean}
  22059. * @readonly
  22060. * @default true
  22061. */
  22062. this.isVideoFrameTexture = true;
  22063. }
  22064. /**
  22065. * This method overwritten with an empty implementation since
  22066. * this type of texture is updated via `setFrame()`.
  22067. */
  22068. update() {}
  22069. clone() {
  22070. return new this.constructor().copy( this ); // restoring Texture.clone()
  22071. }
  22072. /**
  22073. * Sets the current frame of the video. This will automatically update the texture
  22074. * so the data can be used for rendering.
  22075. *
  22076. * @param {VideoFrame} frame - The video frame.
  22077. */
  22078. setFrame( frame ) {
  22079. this.image = frame;
  22080. this.needsUpdate = true;
  22081. }
  22082. }
  22083. /**
  22084. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  22085. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  22086. * as a texture for further usage.
  22087. *
  22088. * ```js
  22089. * const pixelRatio = window.devicePixelRatio;
  22090. * const textureSize = 128 * pixelRatio;
  22091. *
  22092. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  22093. *
  22094. * // calculate start position for copying part of the frame data
  22095. * const vector = new Vector2();
  22096. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  22097. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  22098. *
  22099. * renderer.render( scene, camera );
  22100. *
  22101. * // copy part of the rendered frame into the framebuffer texture
  22102. * renderer.copyFramebufferToTexture( frameTexture, vector );
  22103. * ```
  22104. *
  22105. * @augments Texture
  22106. */
  22107. class FramebufferTexture extends Texture {
  22108. /**
  22109. * Constructs a new framebuffer texture.
  22110. *
  22111. * @param {number} [width] - The width of the texture.
  22112. * @param {number} [height] - The height of the texture.
  22113. */
  22114. constructor( width, height ) {
  22115. super( { width, height } );
  22116. /**
  22117. * This flag can be used for type testing.
  22118. *
  22119. * @type {boolean}
  22120. * @readonly
  22121. * @default true
  22122. */
  22123. this.isFramebufferTexture = true;
  22124. /**
  22125. * How the texture is sampled when a texel covers more than one pixel.
  22126. *
  22127. * Overwritten and set to `NearestFilter` by default to disable filtering.
  22128. *
  22129. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  22130. * @default NearestFilter
  22131. */
  22132. this.magFilter = NearestFilter;
  22133. /**
  22134. * How the texture is sampled when a texel covers less than one pixel.
  22135. *
  22136. * Overwritten and set to `NearestFilter` by default to disable filtering.
  22137. *
  22138. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  22139. * @default NearestFilter
  22140. */
  22141. this.minFilter = NearestFilter;
  22142. /**
  22143. * Whether to generate mipmaps (if possible) for a texture.
  22144. *
  22145. * Overwritten and set to `false` by default.
  22146. *
  22147. * @type {boolean}
  22148. * @default false
  22149. */
  22150. this.generateMipmaps = false;
  22151. this.needsUpdate = true;
  22152. }
  22153. }
  22154. /**
  22155. * Creates a texture based on data in compressed form.
  22156. *
  22157. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22158. *
  22159. * @augments Texture
  22160. */
  22161. class CompressedTexture extends Texture {
  22162. /**
  22163. * Constructs a new compressed texture.
  22164. *
  22165. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22166. * the data and dimensions.
  22167. * @param {number} width - The width of the texture.
  22168. * @param {number} height - The height of the texture.
  22169. * @param {number} [format=RGBAFormat] - The texture format.
  22170. * @param {number} [type=UnsignedByteType] - The texture type.
  22171. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22172. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22173. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22174. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22175. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22176. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22177. * @param {string} [colorSpace=NoColorSpace] - The color space.
  22178. */
  22179. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  22180. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  22181. /**
  22182. * This flag can be used for type testing.
  22183. *
  22184. * @type {boolean}
  22185. * @readonly
  22186. * @default true
  22187. */
  22188. this.isCompressedTexture = true;
  22189. /**
  22190. * The image property of a compressed texture just defines its dimensions.
  22191. *
  22192. * @type {{width:number,height:number}}
  22193. */
  22194. this.image = { width: width, height: height };
  22195. /**
  22196. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  22197. *
  22198. * @type {Array<Object>}
  22199. */
  22200. this.mipmaps = mipmaps;
  22201. /**
  22202. * If set to `true`, the texture is flipped along the vertical axis when
  22203. * uploaded to the GPU.
  22204. *
  22205. * Overwritten and set to `false` by default since it is not possible to
  22206. * flip compressed textures.
  22207. *
  22208. * @type {boolean}
  22209. * @default false
  22210. * @readonly
  22211. */
  22212. this.flipY = false;
  22213. /**
  22214. * Whether to generate mipmaps (if possible) for a texture.
  22215. *
  22216. * Overwritten and set to `false` by default since it is not
  22217. * possible to generate mipmaps for compressed data. Mipmaps
  22218. * must be embedded in the compressed texture file.
  22219. *
  22220. * @type {boolean}
  22221. * @default false
  22222. * @readonly
  22223. */
  22224. this.generateMipmaps = false;
  22225. }
  22226. }
  22227. /**
  22228. * Creates a texture 2D array based on data in compressed form.
  22229. *
  22230. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22231. *
  22232. * @augments CompressedTexture
  22233. */
  22234. class CompressedArrayTexture extends CompressedTexture {
  22235. /**
  22236. * Constructs a new compressed array texture.
  22237. *
  22238. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22239. * the data and dimensions.
  22240. * @param {number} width - The width of the texture.
  22241. * @param {number} height - The height of the texture.
  22242. * @param {number} depth - The depth of the texture.
  22243. * @param {number} [format=RGBAFormat] - The min filter value.
  22244. * @param {number} [type=UnsignedByteType] - The min filter value.
  22245. */
  22246. constructor( mipmaps, width, height, depth, format, type ) {
  22247. super( mipmaps, width, height, format, type );
  22248. /**
  22249. * This flag can be used for type testing.
  22250. *
  22251. * @type {boolean}
  22252. * @readonly
  22253. * @default true
  22254. */
  22255. this.isCompressedArrayTexture = true;
  22256. /**
  22257. * The image property of a compressed texture just defines its dimensions.
  22258. *
  22259. * @name CompressedArrayTexture#image
  22260. * @type {{width:number,height:number,depth:number}}
  22261. */
  22262. this.image.depth = depth;
  22263. /**
  22264. * This defines how the texture is wrapped in the depth and corresponds to
  22265. * *W* in UVW mapping.
  22266. *
  22267. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  22268. * @default ClampToEdgeWrapping
  22269. */
  22270. this.wrapR = ClampToEdgeWrapping;
  22271. /**
  22272. * A set of all layers which need to be updated in the texture.
  22273. *
  22274. * @type {Set<number>}
  22275. */
  22276. this.layerUpdates = new Set();
  22277. }
  22278. /**
  22279. * Describes that a specific layer of the texture needs to be updated.
  22280. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  22281. * entire compressed texture array is sent to the GPU. Marking specific
  22282. * layers will only transmit subsets of all mipmaps associated with a
  22283. * specific depth in the array which is often much more performant.
  22284. *
  22285. * @param {number} layerIndex - The layer index that should be updated.
  22286. */
  22287. addLayerUpdate( layerIndex ) {
  22288. this.layerUpdates.add( layerIndex );
  22289. }
  22290. /**
  22291. * Resets the layer updates registry.
  22292. */
  22293. clearLayerUpdates() {
  22294. this.layerUpdates.clear();
  22295. }
  22296. }
  22297. /**
  22298. * Creates a cube texture based on data in compressed form.
  22299. *
  22300. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22301. *
  22302. * @augments CompressedTexture
  22303. */
  22304. class CompressedCubeTexture extends CompressedTexture {
  22305. /**
  22306. * Constructs a new compressed texture.
  22307. *
  22308. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  22309. * @param {number} [format=RGBAFormat] - The texture format.
  22310. * @param {number} [type=UnsignedByteType] - The texture type.
  22311. */
  22312. constructor( images, format, type ) {
  22313. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  22314. /**
  22315. * This flag can be used for type testing.
  22316. *
  22317. * @type {boolean}
  22318. * @readonly
  22319. * @default true
  22320. */
  22321. this.isCompressedCubeTexture = true;
  22322. /**
  22323. * This flag can be used for type testing.
  22324. *
  22325. * @type {boolean}
  22326. * @readonly
  22327. * @default true
  22328. */
  22329. this.isCubeTexture = true;
  22330. this.image = images;
  22331. }
  22332. }
  22333. /**
  22334. * Creates a texture from a canvas element.
  22335. *
  22336. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22337. * to `true` immediately since a canvas can directly be used for rendering.
  22338. *
  22339. * @augments Texture
  22340. */
  22341. class CanvasTexture extends Texture {
  22342. /**
  22343. * Constructs a new texture.
  22344. *
  22345. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22346. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22347. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22348. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22349. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22350. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22351. * @param {number} [format=RGBAFormat] - The texture format.
  22352. * @param {number} [type=UnsignedByteType] - The texture type.
  22353. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22354. */
  22355. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22356. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22357. /**
  22358. * This flag can be used for type testing.
  22359. *
  22360. * @type {boolean}
  22361. * @readonly
  22362. * @default true
  22363. */
  22364. this.isCanvasTexture = true;
  22365. this.needsUpdate = true;
  22366. }
  22367. }
  22368. /**
  22369. * This class can be used to automatically save the depth information of a
  22370. * rendering into a texture.
  22371. *
  22372. * @augments Texture
  22373. */
  22374. class DepthTexture extends Texture {
  22375. /**
  22376. * Constructs a new depth texture.
  22377. *
  22378. * @param {number} width - The width of the texture.
  22379. * @param {number} height - The height of the texture.
  22380. * @param {number} [type=UnsignedIntType] - The texture type.
  22381. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22382. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22383. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22384. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22385. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22386. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22387. * @param {number} [format=DepthFormat] - The texture format.
  22388. * @param {number} [depth=1] - The depth of the texture.
  22389. */
  22390. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22391. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22392. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22393. }
  22394. const image = { width: width, height: height, depth: depth };
  22395. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22396. /**
  22397. * This flag can be used for type testing.
  22398. *
  22399. * @type {boolean}
  22400. * @readonly
  22401. * @default true
  22402. */
  22403. this.isDepthTexture = true;
  22404. /**
  22405. * If set to `true`, the texture is flipped along the vertical axis when
  22406. * uploaded to the GPU.
  22407. *
  22408. * Overwritten and set to `false` by default.
  22409. *
  22410. * @type {boolean}
  22411. * @default false
  22412. */
  22413. this.flipY = false;
  22414. /**
  22415. * Whether to generate mipmaps (if possible) for a texture.
  22416. *
  22417. * Overwritten and set to `false` by default.
  22418. *
  22419. * @type {boolean}
  22420. * @default false
  22421. */
  22422. this.generateMipmaps = false;
  22423. /**
  22424. * Code corresponding to the depth compare function.
  22425. *
  22426. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22427. * @default null
  22428. */
  22429. this.compareFunction = null;
  22430. }
  22431. copy( source ) {
  22432. super.copy( source );
  22433. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22434. this.compareFunction = source.compareFunction;
  22435. return this;
  22436. }
  22437. toJSON( meta ) {
  22438. const data = super.toJSON( meta );
  22439. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22440. return data;
  22441. }
  22442. }
  22443. /**
  22444. * This class can be used to automatically save the depth information of a
  22445. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  22446. *
  22447. * @augments DepthTexture
  22448. */
  22449. class CubeDepthTexture extends DepthTexture {
  22450. /**
  22451. * Constructs a new cube depth texture.
  22452. *
  22453. * @param {number} size - The size (width and height) of each cube face.
  22454. * @param {number} [type=UnsignedIntType] - The texture type.
  22455. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  22456. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22457. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22458. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  22459. * @param {number} [minFilter=NearestFilter] - The min filter value.
  22460. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22461. * @param {number} [format=DepthFormat] - The texture format.
  22462. */
  22463. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  22464. // Create 6 identical image descriptors for the cube faces
  22465. const image = { width: size, height: size, depth: 1 };
  22466. const images = [ image, image, image, image, image, image ];
  22467. // Call DepthTexture constructor with width, height
  22468. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  22469. // Replace the single image with the array of 6 images
  22470. this.image = images;
  22471. /**
  22472. * This flag can be used for type testing.
  22473. *
  22474. * @type {boolean}
  22475. * @readonly
  22476. * @default true
  22477. */
  22478. this.isCubeDepthTexture = true;
  22479. /**
  22480. * Set to true for cube texture handling in WebGLTextures.
  22481. *
  22482. * @type {boolean}
  22483. * @readonly
  22484. * @default true
  22485. */
  22486. this.isCubeTexture = true;
  22487. }
  22488. /**
  22489. * Alias for {@link CubeDepthTexture#image}.
  22490. *
  22491. * @type {Array<Image>}
  22492. */
  22493. get images() {
  22494. return this.image;
  22495. }
  22496. set images( value ) {
  22497. this.image = value;
  22498. }
  22499. }
  22500. /**
  22501. * Represents a texture created externally with the same renderer context.
  22502. *
  22503. * This may be a texture from a protected media stream, device camera feed,
  22504. * or other data feeds like a depth sensor.
  22505. *
  22506. * Note that this class is only supported in {@link WebGLRenderer}, and in
  22507. * the {@link WebGPURenderer} WebGPU backend.
  22508. *
  22509. * @augments Texture
  22510. */
  22511. class ExternalTexture extends Texture {
  22512. /**
  22513. * Creates a new raw texture.
  22514. *
  22515. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  22516. */
  22517. constructor( sourceTexture = null ) {
  22518. super();
  22519. /**
  22520. * The external source texture.
  22521. *
  22522. * @type {?(WebGLTexture|GPUTexture)}
  22523. * @default null
  22524. */
  22525. this.sourceTexture = sourceTexture;
  22526. /**
  22527. * This flag can be used for type testing.
  22528. *
  22529. * @type {boolean}
  22530. * @readonly
  22531. * @default true
  22532. */
  22533. this.isExternalTexture = true;
  22534. }
  22535. copy( source ) {
  22536. super.copy( source );
  22537. this.sourceTexture = source.sourceTexture;
  22538. return this;
  22539. }
  22540. }
  22541. /**
  22542. * A geometry class for representing a capsule.
  22543. *
  22544. * ```js
  22545. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22546. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22547. * const capsule = new THREE.Mesh( geometry, material );
  22548. * scene.add( capsule );
  22549. * ```
  22550. *
  22551. * @augments BufferGeometry
  22552. * @demo scenes/geometry-browser.html#CapsuleGeometry
  22553. */
  22554. class CapsuleGeometry extends BufferGeometry {
  22555. /**
  22556. * Constructs a new capsule geometry.
  22557. *
  22558. * @param {number} [radius=1] - Radius of the capsule.
  22559. * @param {number} [height=1] - Height of the middle section.
  22560. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22561. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22562. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22563. */
  22564. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22565. super();
  22566. this.type = 'CapsuleGeometry';
  22567. /**
  22568. * Holds the constructor parameters that have been
  22569. * used to generate the geometry. Any modification
  22570. * after instantiation does not change the geometry.
  22571. *
  22572. * @type {Object}
  22573. */
  22574. this.parameters = {
  22575. radius: radius,
  22576. height: height,
  22577. capSegments: capSegments,
  22578. radialSegments: radialSegments,
  22579. heightSegments: heightSegments,
  22580. };
  22581. height = Math.max( 0, height );
  22582. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22583. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22584. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22585. // buffers
  22586. const indices = [];
  22587. const vertices = [];
  22588. const normals = [];
  22589. const uvs = [];
  22590. // helper variables
  22591. const halfHeight = height / 2;
  22592. const capArcLength = ( Math.PI / 2 ) * radius;
  22593. const cylinderPartLength = height;
  22594. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22595. const numVerticalSegments = capSegments * 2 + heightSegments;
  22596. const verticesPerRow = radialSegments + 1;
  22597. const normal = new Vector3();
  22598. const vertex = new Vector3();
  22599. // generate vertices, normals, and uvs
  22600. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22601. let currentArcLength = 0;
  22602. let profileY = 0;
  22603. let profileRadius = 0;
  22604. let normalYComponent = 0;
  22605. if ( iy <= capSegments ) {
  22606. // bottom cap
  22607. const segmentProgress = iy / capSegments;
  22608. const angle = ( segmentProgress * Math.PI ) / 2;
  22609. profileY = - halfHeight - radius * Math.cos( angle );
  22610. profileRadius = radius * Math.sin( angle );
  22611. normalYComponent = - radius * Math.cos( angle );
  22612. currentArcLength = segmentProgress * capArcLength;
  22613. } else if ( iy <= capSegments + heightSegments ) {
  22614. // middle section
  22615. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22616. profileY = - halfHeight + segmentProgress * height;
  22617. profileRadius = radius;
  22618. normalYComponent = 0;
  22619. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22620. } else {
  22621. // top cap
  22622. const segmentProgress =
  22623. ( iy - capSegments - heightSegments ) / capSegments;
  22624. const angle = ( segmentProgress * Math.PI ) / 2;
  22625. profileY = halfHeight + radius * Math.sin( angle );
  22626. profileRadius = radius * Math.cos( angle );
  22627. normalYComponent = radius * Math.sin( angle );
  22628. currentArcLength =
  22629. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22630. }
  22631. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22632. // special case for the poles
  22633. let uOffset = 0;
  22634. if ( iy === 0 ) {
  22635. uOffset = 0.5 / radialSegments;
  22636. } else if ( iy === numVerticalSegments ) {
  22637. uOffset = -0.5 / radialSegments;
  22638. }
  22639. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22640. const u = ix / radialSegments;
  22641. const theta = u * Math.PI * 2;
  22642. const sinTheta = Math.sin( theta );
  22643. const cosTheta = Math.cos( theta );
  22644. // vertex
  22645. vertex.x = - profileRadius * cosTheta;
  22646. vertex.y = profileY;
  22647. vertex.z = profileRadius * sinTheta;
  22648. vertices.push( vertex.x, vertex.y, vertex.z );
  22649. // normal
  22650. normal.set(
  22651. - profileRadius * cosTheta,
  22652. normalYComponent,
  22653. profileRadius * sinTheta
  22654. );
  22655. normal.normalize();
  22656. normals.push( normal.x, normal.y, normal.z );
  22657. // uv
  22658. uvs.push( u + uOffset, v );
  22659. }
  22660. if ( iy > 0 ) {
  22661. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22662. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22663. const i1 = prevIndexRow + ix;
  22664. const i2 = prevIndexRow + ix + 1;
  22665. const i3 = iy * verticesPerRow + ix;
  22666. const i4 = iy * verticesPerRow + ix + 1;
  22667. indices.push( i1, i2, i3 );
  22668. indices.push( i2, i4, i3 );
  22669. }
  22670. }
  22671. }
  22672. // build geometry
  22673. this.setIndex( indices );
  22674. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22675. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22676. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22677. }
  22678. copy( source ) {
  22679. super.copy( source );
  22680. this.parameters = Object.assign( {}, source.parameters );
  22681. return this;
  22682. }
  22683. /**
  22684. * Factory method for creating an instance of this class from the given
  22685. * JSON object.
  22686. *
  22687. * @param {Object} data - A JSON object representing the serialized geometry.
  22688. * @return {CapsuleGeometry} A new instance.
  22689. */
  22690. static fromJSON( data ) {
  22691. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22692. }
  22693. }
  22694. /**
  22695. * A simple shape of Euclidean geometry. It is constructed from a
  22696. * number of triangular segments that are oriented around a central point and
  22697. * extend as far out as a given radius. It is built counter-clockwise from a
  22698. * start angle and a given central angle. It can also be used to create
  22699. * regular polygons, where the number of segments determines the number of
  22700. * sides.
  22701. *
  22702. * ```js
  22703. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22704. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22705. * const circle = new THREE.Mesh( geometry, material );
  22706. * scene.add( circle )
  22707. * ```
  22708. *
  22709. * @augments BufferGeometry
  22710. * @demo scenes/geometry-browser.html#CircleGeometry
  22711. */
  22712. class CircleGeometry extends BufferGeometry {
  22713. /**
  22714. * Constructs a new circle geometry.
  22715. *
  22716. * @param {number} [radius=1] - Radius of the circle.
  22717. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22718. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22719. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22720. * of the circular sector in radians. The default value results in a complete circle.
  22721. */
  22722. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22723. super();
  22724. this.type = 'CircleGeometry';
  22725. /**
  22726. * Holds the constructor parameters that have been
  22727. * used to generate the geometry. Any modification
  22728. * after instantiation does not change the geometry.
  22729. *
  22730. * @type {Object}
  22731. */
  22732. this.parameters = {
  22733. radius: radius,
  22734. segments: segments,
  22735. thetaStart: thetaStart,
  22736. thetaLength: thetaLength
  22737. };
  22738. segments = Math.max( 3, segments );
  22739. // buffers
  22740. const indices = [];
  22741. const vertices = [];
  22742. const normals = [];
  22743. const uvs = [];
  22744. // helper variables
  22745. const vertex = new Vector3();
  22746. const uv = new Vector2();
  22747. // center point
  22748. vertices.push( 0, 0, 0 );
  22749. normals.push( 0, 0, 1 );
  22750. uvs.push( 0.5, 0.5 );
  22751. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22752. const segment = thetaStart + s / segments * thetaLength;
  22753. // vertex
  22754. vertex.x = radius * Math.cos( segment );
  22755. vertex.y = radius * Math.sin( segment );
  22756. vertices.push( vertex.x, vertex.y, vertex.z );
  22757. // normal
  22758. normals.push( 0, 0, 1 );
  22759. // uvs
  22760. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22761. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22762. uvs.push( uv.x, uv.y );
  22763. }
  22764. // indices
  22765. for ( let i = 1; i <= segments; i ++ ) {
  22766. indices.push( i, i + 1, 0 );
  22767. }
  22768. // build geometry
  22769. this.setIndex( indices );
  22770. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22771. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22772. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22773. }
  22774. copy( source ) {
  22775. super.copy( source );
  22776. this.parameters = Object.assign( {}, source.parameters );
  22777. return this;
  22778. }
  22779. /**
  22780. * Factory method for creating an instance of this class from the given
  22781. * JSON object.
  22782. *
  22783. * @param {Object} data - A JSON object representing the serialized geometry.
  22784. * @return {CircleGeometry} A new instance.
  22785. */
  22786. static fromJSON( data ) {
  22787. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22788. }
  22789. }
  22790. /**
  22791. * A geometry class for representing a cylinder.
  22792. *
  22793. * ```js
  22794. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22795. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22796. * const cylinder = new THREE.Mesh( geometry, material );
  22797. * scene.add( cylinder );
  22798. * ```
  22799. *
  22800. * @augments BufferGeometry
  22801. * @demo scenes/geometry-browser.html#CylinderGeometry
  22802. */
  22803. class CylinderGeometry extends BufferGeometry {
  22804. /**
  22805. * Constructs a new cylinder geometry.
  22806. *
  22807. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22808. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22809. * @param {number} [height=1] - Height of the cylinder.
  22810. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22811. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22812. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22813. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22814. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22815. * The default value results in a complete cylinder.
  22816. */
  22817. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22818. super();
  22819. this.type = 'CylinderGeometry';
  22820. /**
  22821. * Holds the constructor parameters that have been
  22822. * used to generate the geometry. Any modification
  22823. * after instantiation does not change the geometry.
  22824. *
  22825. * @type {Object}
  22826. */
  22827. this.parameters = {
  22828. radiusTop: radiusTop,
  22829. radiusBottom: radiusBottom,
  22830. height: height,
  22831. radialSegments: radialSegments,
  22832. heightSegments: heightSegments,
  22833. openEnded: openEnded,
  22834. thetaStart: thetaStart,
  22835. thetaLength: thetaLength
  22836. };
  22837. const scope = this;
  22838. radialSegments = Math.floor( radialSegments );
  22839. heightSegments = Math.floor( heightSegments );
  22840. // buffers
  22841. const indices = [];
  22842. const vertices = [];
  22843. const normals = [];
  22844. const uvs = [];
  22845. // helper variables
  22846. let index = 0;
  22847. const indexArray = [];
  22848. const halfHeight = height / 2;
  22849. let groupStart = 0;
  22850. // generate geometry
  22851. generateTorso();
  22852. if ( openEnded === false ) {
  22853. if ( radiusTop > 0 ) generateCap( true );
  22854. if ( radiusBottom > 0 ) generateCap( false );
  22855. }
  22856. // build geometry
  22857. this.setIndex( indices );
  22858. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22859. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22860. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22861. function generateTorso() {
  22862. const normal = new Vector3();
  22863. const vertex = new Vector3();
  22864. let groupCount = 0;
  22865. // this will be used to calculate the normal
  22866. const slope = ( radiusBottom - radiusTop ) / height;
  22867. // generate vertices, normals and uvs
  22868. for ( let y = 0; y <= heightSegments; y ++ ) {
  22869. const indexRow = [];
  22870. const v = y / heightSegments;
  22871. // calculate the radius of the current row
  22872. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22873. for ( let x = 0; x <= radialSegments; x ++ ) {
  22874. const u = x / radialSegments;
  22875. const theta = u * thetaLength + thetaStart;
  22876. const sinTheta = Math.sin( theta );
  22877. const cosTheta = Math.cos( theta );
  22878. // vertex
  22879. vertex.x = radius * sinTheta;
  22880. vertex.y = - v * height + halfHeight;
  22881. vertex.z = radius * cosTheta;
  22882. vertices.push( vertex.x, vertex.y, vertex.z );
  22883. // normal
  22884. normal.set( sinTheta, slope, cosTheta ).normalize();
  22885. normals.push( normal.x, normal.y, normal.z );
  22886. // uv
  22887. uvs.push( u, 1 - v );
  22888. // save index of vertex in respective row
  22889. indexRow.push( index ++ );
  22890. }
  22891. // now save vertices of the row in our index array
  22892. indexArray.push( indexRow );
  22893. }
  22894. // generate indices
  22895. for ( let x = 0; x < radialSegments; x ++ ) {
  22896. for ( let y = 0; y < heightSegments; y ++ ) {
  22897. // we use the index array to access the correct indices
  22898. const a = indexArray[ y ][ x ];
  22899. const b = indexArray[ y + 1 ][ x ];
  22900. const c = indexArray[ y + 1 ][ x + 1 ];
  22901. const d = indexArray[ y ][ x + 1 ];
  22902. // faces
  22903. if ( radiusTop > 0 || y !== 0 ) {
  22904. indices.push( a, b, d );
  22905. groupCount += 3;
  22906. }
  22907. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22908. indices.push( b, c, d );
  22909. groupCount += 3;
  22910. }
  22911. }
  22912. }
  22913. // add a group to the geometry. this will ensure multi material support
  22914. scope.addGroup( groupStart, groupCount, 0 );
  22915. // calculate new start value for groups
  22916. groupStart += groupCount;
  22917. }
  22918. function generateCap( top ) {
  22919. // save the index of the first center vertex
  22920. const centerIndexStart = index;
  22921. const uv = new Vector2();
  22922. const vertex = new Vector3();
  22923. let groupCount = 0;
  22924. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22925. const sign = ( top === true ) ? 1 : -1;
  22926. // first we generate the center vertex data of the cap.
  22927. // because the geometry needs one set of uvs per face,
  22928. // we must generate a center vertex per face/segment
  22929. for ( let x = 1; x <= radialSegments; x ++ ) {
  22930. // vertex
  22931. vertices.push( 0, halfHeight * sign, 0 );
  22932. // normal
  22933. normals.push( 0, sign, 0 );
  22934. // uv
  22935. uvs.push( 0.5, 0.5 );
  22936. // increase index
  22937. index ++;
  22938. }
  22939. // save the index of the last center vertex
  22940. const centerIndexEnd = index;
  22941. // now we generate the surrounding vertices, normals and uvs
  22942. for ( let x = 0; x <= radialSegments; x ++ ) {
  22943. const u = x / radialSegments;
  22944. const theta = u * thetaLength + thetaStart;
  22945. const cosTheta = Math.cos( theta );
  22946. const sinTheta = Math.sin( theta );
  22947. // vertex
  22948. vertex.x = radius * sinTheta;
  22949. vertex.y = halfHeight * sign;
  22950. vertex.z = radius * cosTheta;
  22951. vertices.push( vertex.x, vertex.y, vertex.z );
  22952. // normal
  22953. normals.push( 0, sign, 0 );
  22954. // uv
  22955. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22956. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22957. uvs.push( uv.x, uv.y );
  22958. // increase index
  22959. index ++;
  22960. }
  22961. // generate indices
  22962. for ( let x = 0; x < radialSegments; x ++ ) {
  22963. const c = centerIndexStart + x;
  22964. const i = centerIndexEnd + x;
  22965. if ( top === true ) {
  22966. // face top
  22967. indices.push( i, i + 1, c );
  22968. } else {
  22969. // face bottom
  22970. indices.push( i + 1, i, c );
  22971. }
  22972. groupCount += 3;
  22973. }
  22974. // add a group to the geometry. this will ensure multi material support
  22975. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22976. // calculate new start value for groups
  22977. groupStart += groupCount;
  22978. }
  22979. }
  22980. copy( source ) {
  22981. super.copy( source );
  22982. this.parameters = Object.assign( {}, source.parameters );
  22983. return this;
  22984. }
  22985. /**
  22986. * Factory method for creating an instance of this class from the given
  22987. * JSON object.
  22988. *
  22989. * @param {Object} data - A JSON object representing the serialized geometry.
  22990. * @return {CylinderGeometry} A new instance.
  22991. */
  22992. static fromJSON( data ) {
  22993. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22994. }
  22995. }
  22996. /**
  22997. * A geometry class for representing a cone.
  22998. *
  22999. * ```js
  23000. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  23001. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23002. * const cone = new THREE.Mesh(geometry, material );
  23003. * scene.add( cone );
  23004. * ```
  23005. *
  23006. * @augments CylinderGeometry
  23007. * @demo scenes/geometry-browser.html#ConeGeometry
  23008. */
  23009. class ConeGeometry extends CylinderGeometry {
  23010. /**
  23011. * Constructs a new cone geometry.
  23012. *
  23013. * @param {number} [radius=1] - Radius of the cone base.
  23014. * @param {number} [height=1] - Height of the cone.
  23015. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  23016. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  23017. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  23018. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  23019. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  23020. * The default value results in a complete cone.
  23021. */
  23022. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23023. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  23024. this.type = 'ConeGeometry';
  23025. /**
  23026. * Holds the constructor parameters that have been
  23027. * used to generate the geometry. Any modification
  23028. * after instantiation does not change the geometry.
  23029. *
  23030. * @type {Object}
  23031. */
  23032. this.parameters = {
  23033. radius: radius,
  23034. height: height,
  23035. radialSegments: radialSegments,
  23036. heightSegments: heightSegments,
  23037. openEnded: openEnded,
  23038. thetaStart: thetaStart,
  23039. thetaLength: thetaLength
  23040. };
  23041. }
  23042. /**
  23043. * Factory method for creating an instance of this class from the given
  23044. * JSON object.
  23045. *
  23046. * @param {Object} data - A JSON object representing the serialized geometry.
  23047. * @return {ConeGeometry} A new instance.
  23048. */
  23049. static fromJSON( data ) {
  23050. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  23051. }
  23052. }
  23053. /**
  23054. * A polyhedron is a solid in three dimensions with flat faces. This class
  23055. * will take an array of vertices, project them onto a sphere, and then
  23056. * divide them up to the desired level of detail.
  23057. *
  23058. * @augments BufferGeometry
  23059. */
  23060. class PolyhedronGeometry extends BufferGeometry {
  23061. /**
  23062. * Constructs a new polyhedron geometry.
  23063. *
  23064. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  23065. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  23066. * @param {number} [radius=1] - The radius of the shape.
  23067. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  23068. */
  23069. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  23070. super();
  23071. this.type = 'PolyhedronGeometry';
  23072. /**
  23073. * Holds the constructor parameters that have been
  23074. * used to generate the geometry. Any modification
  23075. * after instantiation does not change the geometry.
  23076. *
  23077. * @type {Object}
  23078. */
  23079. this.parameters = {
  23080. vertices: vertices,
  23081. indices: indices,
  23082. radius: radius,
  23083. detail: detail
  23084. };
  23085. // default buffer data
  23086. const vertexBuffer = [];
  23087. const uvBuffer = [];
  23088. // the subdivision creates the vertex buffer data
  23089. subdivide( detail );
  23090. // all vertices should lie on a conceptual sphere with a given radius
  23091. applyRadius( radius );
  23092. // finally, create the uv data
  23093. generateUVs();
  23094. // build non-indexed geometry
  23095. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  23096. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  23097. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  23098. if ( detail === 0 ) {
  23099. this.computeVertexNormals(); // flat normals
  23100. } else {
  23101. this.normalizeNormals(); // smooth normals
  23102. }
  23103. // helper functions
  23104. function subdivide( detail ) {
  23105. const a = new Vector3();
  23106. const b = new Vector3();
  23107. const c = new Vector3();
  23108. // iterate over all faces and apply a subdivision with the given detail value
  23109. for ( let i = 0; i < indices.length; i += 3 ) {
  23110. // get the vertices of the face
  23111. getVertexByIndex( indices[ i + 0 ], a );
  23112. getVertexByIndex( indices[ i + 1 ], b );
  23113. getVertexByIndex( indices[ i + 2 ], c );
  23114. // perform subdivision
  23115. subdivideFace( a, b, c, detail );
  23116. }
  23117. }
  23118. function subdivideFace( a, b, c, detail ) {
  23119. const cols = detail + 1;
  23120. // we use this multidimensional array as a data structure for creating the subdivision
  23121. const v = [];
  23122. // construct all of the vertices for this subdivision
  23123. for ( let i = 0; i <= cols; i ++ ) {
  23124. v[ i ] = [];
  23125. const aj = a.clone().lerp( c, i / cols );
  23126. const bj = b.clone().lerp( c, i / cols );
  23127. const rows = cols - i;
  23128. for ( let j = 0; j <= rows; j ++ ) {
  23129. if ( j === 0 && i === cols ) {
  23130. v[ i ][ j ] = aj;
  23131. } else {
  23132. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  23133. }
  23134. }
  23135. }
  23136. // construct all of the faces
  23137. for ( let i = 0; i < cols; i ++ ) {
  23138. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  23139. const k = Math.floor( j / 2 );
  23140. if ( j % 2 === 0 ) {
  23141. pushVertex( v[ i ][ k + 1 ] );
  23142. pushVertex( v[ i + 1 ][ k ] );
  23143. pushVertex( v[ i ][ k ] );
  23144. } else {
  23145. pushVertex( v[ i ][ k + 1 ] );
  23146. pushVertex( v[ i + 1 ][ k + 1 ] );
  23147. pushVertex( v[ i + 1 ][ k ] );
  23148. }
  23149. }
  23150. }
  23151. }
  23152. function applyRadius( radius ) {
  23153. const vertex = new Vector3();
  23154. // iterate over the entire buffer and apply the radius to each vertex
  23155. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  23156. vertex.x = vertexBuffer[ i + 0 ];
  23157. vertex.y = vertexBuffer[ i + 1 ];
  23158. vertex.z = vertexBuffer[ i + 2 ];
  23159. vertex.normalize().multiplyScalar( radius );
  23160. vertexBuffer[ i + 0 ] = vertex.x;
  23161. vertexBuffer[ i + 1 ] = vertex.y;
  23162. vertexBuffer[ i + 2 ] = vertex.z;
  23163. }
  23164. }
  23165. function generateUVs() {
  23166. const vertex = new Vector3();
  23167. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  23168. vertex.x = vertexBuffer[ i + 0 ];
  23169. vertex.y = vertexBuffer[ i + 1 ];
  23170. vertex.z = vertexBuffer[ i + 2 ];
  23171. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  23172. const v = inclination( vertex ) / Math.PI + 0.5;
  23173. uvBuffer.push( u, 1 - v );
  23174. }
  23175. correctUVs();
  23176. correctSeam();
  23177. }
  23178. function correctSeam() {
  23179. // handle case when face straddles the seam, see #3269
  23180. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  23181. // uv data of a single face
  23182. const x0 = uvBuffer[ i + 0 ];
  23183. const x1 = uvBuffer[ i + 2 ];
  23184. const x2 = uvBuffer[ i + 4 ];
  23185. const max = Math.max( x0, x1, x2 );
  23186. const min = Math.min( x0, x1, x2 );
  23187. // 0.9 is somewhat arbitrary
  23188. if ( max > 0.9 && min < 0.1 ) {
  23189. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  23190. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  23191. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  23192. }
  23193. }
  23194. }
  23195. function pushVertex( vertex ) {
  23196. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  23197. }
  23198. function getVertexByIndex( index, vertex ) {
  23199. const stride = index * 3;
  23200. vertex.x = vertices[ stride + 0 ];
  23201. vertex.y = vertices[ stride + 1 ];
  23202. vertex.z = vertices[ stride + 2 ];
  23203. }
  23204. function correctUVs() {
  23205. const a = new Vector3();
  23206. const b = new Vector3();
  23207. const c = new Vector3();
  23208. const centroid = new Vector3();
  23209. const uvA = new Vector2();
  23210. const uvB = new Vector2();
  23211. const uvC = new Vector2();
  23212. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  23213. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  23214. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  23215. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  23216. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  23217. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  23218. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  23219. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  23220. const azi = azimuth( centroid );
  23221. correctUV( uvA, j + 0, a, azi );
  23222. correctUV( uvB, j + 2, b, azi );
  23223. correctUV( uvC, j + 4, c, azi );
  23224. }
  23225. }
  23226. function correctUV( uv, stride, vector, azimuth ) {
  23227. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  23228. uvBuffer[ stride ] = uv.x - 1;
  23229. }
  23230. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  23231. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  23232. }
  23233. }
  23234. // Angle around the Y axis, counter-clockwise when looking from above.
  23235. function azimuth( vector ) {
  23236. return Math.atan2( vector.z, - vector.x );
  23237. }
  23238. // Angle above the XZ plane.
  23239. function inclination( vector ) {
  23240. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23241. }
  23242. }
  23243. copy( source ) {
  23244. super.copy( source );
  23245. this.parameters = Object.assign( {}, source.parameters );
  23246. return this;
  23247. }
  23248. /**
  23249. * Factory method for creating an instance of this class from the given
  23250. * JSON object.
  23251. *
  23252. * @param {Object} data - A JSON object representing the serialized geometry.
  23253. * @return {PolyhedronGeometry} A new instance.
  23254. */
  23255. static fromJSON( data ) {
  23256. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  23257. }
  23258. }
  23259. /**
  23260. * A geometry class for representing a dodecahedron.
  23261. *
  23262. * ```js
  23263. * const geometry = new THREE.DodecahedronGeometry();
  23264. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23265. * const dodecahedron = new THREE.Mesh( geometry, material );
  23266. * scene.add( dodecahedron );
  23267. * ```
  23268. *
  23269. * @augments PolyhedronGeometry
  23270. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  23271. */
  23272. class DodecahedronGeometry extends PolyhedronGeometry {
  23273. /**
  23274. * Constructs a new dodecahedron geometry.
  23275. *
  23276. * @param {number} [radius=1] - Radius of the dodecahedron.
  23277. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  23278. */
  23279. constructor( radius = 1, detail = 0 ) {
  23280. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23281. const r = 1 / t;
  23282. const vertices = [
  23283. // (±1, ±1, ±1)
  23284. -1, -1, -1, -1, -1, 1,
  23285. -1, 1, -1, -1, 1, 1,
  23286. 1, -1, -1, 1, -1, 1,
  23287. 1, 1, -1, 1, 1, 1,
  23288. // (0, ±1/φ, ±φ)
  23289. 0, - r, - t, 0, - r, t,
  23290. 0, r, - t, 0, r, t,
  23291. // (±1/φ, ±φ, 0)
  23292. - r, - t, 0, - r, t, 0,
  23293. r, - t, 0, r, t, 0,
  23294. // (±φ, 0, ±1/φ)
  23295. - t, 0, - r, t, 0, - r,
  23296. - t, 0, r, t, 0, r
  23297. ];
  23298. const indices = [
  23299. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23300. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23301. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23302. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23303. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23304. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23305. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23306. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23307. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23308. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23309. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23310. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23311. ];
  23312. super( vertices, indices, radius, detail );
  23313. this.type = 'DodecahedronGeometry';
  23314. /**
  23315. * Holds the constructor parameters that have been
  23316. * used to generate the geometry. Any modification
  23317. * after instantiation does not change the geometry.
  23318. *
  23319. * @type {Object}
  23320. */
  23321. this.parameters = {
  23322. radius: radius,
  23323. detail: detail
  23324. };
  23325. }
  23326. /**
  23327. * Factory method for creating an instance of this class from the given
  23328. * JSON object.
  23329. *
  23330. * @param {Object} data - A JSON object representing the serialized geometry.
  23331. * @return {DodecahedronGeometry} A new instance.
  23332. */
  23333. static fromJSON( data ) {
  23334. return new DodecahedronGeometry( data.radius, data.detail );
  23335. }
  23336. }
  23337. const _v0 = /*@__PURE__*/ new Vector3();
  23338. const _v1$1 = /*@__PURE__*/ new Vector3();
  23339. const _normal = /*@__PURE__*/ new Vector3();
  23340. const _triangle = /*@__PURE__*/ new Triangle();
  23341. /**
  23342. * Can be used as a helper object to view the edges of a geometry.
  23343. *
  23344. * ```js
  23345. * const geometry = new THREE.BoxGeometry();
  23346. * const edges = new THREE.EdgesGeometry( geometry );
  23347. * const line = new THREE.LineSegments( edges );
  23348. * scene.add( line );
  23349. * ```
  23350. *
  23351. * Note: It is not yet possible to serialize/deserialize instances of this class.
  23352. *
  23353. * @augments BufferGeometry
  23354. */
  23355. class EdgesGeometry extends BufferGeometry {
  23356. /**
  23357. * Constructs a new edges geometry.
  23358. *
  23359. * @param {?BufferGeometry} [geometry=null] - The geometry.
  23360. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  23361. * between the face normals of the adjoining faces exceeds this value.
  23362. */
  23363. constructor( geometry = null, thresholdAngle = 1 ) {
  23364. super();
  23365. this.type = 'EdgesGeometry';
  23366. /**
  23367. * Holds the constructor parameters that have been
  23368. * used to generate the geometry. Any modification
  23369. * after instantiation does not change the geometry.
  23370. *
  23371. * @type {Object}
  23372. */
  23373. this.parameters = {
  23374. geometry: geometry,
  23375. thresholdAngle: thresholdAngle
  23376. };
  23377. if ( geometry !== null ) {
  23378. const precisionPoints = 4;
  23379. const precision = Math.pow( 10, precisionPoints );
  23380. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  23381. const indexAttr = geometry.getIndex();
  23382. const positionAttr = geometry.getAttribute( 'position' );
  23383. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23384. const indexArr = [ 0, 0, 0 ];
  23385. const vertKeys = [ 'a', 'b', 'c' ];
  23386. const hashes = new Array( 3 );
  23387. const edgeData = {};
  23388. const vertices = [];
  23389. for ( let i = 0; i < indexCount; i += 3 ) {
  23390. if ( indexAttr ) {
  23391. indexArr[ 0 ] = indexAttr.getX( i );
  23392. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  23393. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  23394. } else {
  23395. indexArr[ 0 ] = i;
  23396. indexArr[ 1 ] = i + 1;
  23397. indexArr[ 2 ] = i + 2;
  23398. }
  23399. const { a, b, c } = _triangle;
  23400. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  23401. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  23402. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  23403. _triangle.getNormal( _normal );
  23404. // create hashes for the edge from the vertices
  23405. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  23406. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  23407. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  23408. // skip degenerate triangles
  23409. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  23410. continue;
  23411. }
  23412. // iterate over every edge
  23413. for ( let j = 0; j < 3; j ++ ) {
  23414. // get the first and next vertex making up the edge
  23415. const jNext = ( j + 1 ) % 3;
  23416. const vecHash0 = hashes[ j ];
  23417. const vecHash1 = hashes[ jNext ];
  23418. const v0 = _triangle[ vertKeys[ j ] ];
  23419. const v1 = _triangle[ vertKeys[ jNext ] ];
  23420. const hash = `${ vecHash0 }_${ vecHash1 }`;
  23421. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  23422. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  23423. // if we found a sibling edge add it into the vertex array if
  23424. // it meets the angle threshold and delete the edge from the map.
  23425. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  23426. vertices.push( v0.x, v0.y, v0.z );
  23427. vertices.push( v1.x, v1.y, v1.z );
  23428. }
  23429. edgeData[ reverseHash ] = null;
  23430. } else if ( ! ( hash in edgeData ) ) {
  23431. // if we've already got an edge here then skip adding a new one
  23432. edgeData[ hash ] = {
  23433. index0: indexArr[ j ],
  23434. index1: indexArr[ jNext ],
  23435. normal: _normal.clone(),
  23436. };
  23437. }
  23438. }
  23439. }
  23440. // iterate over all remaining, unmatched edges and add them to the vertex array
  23441. for ( const key in edgeData ) {
  23442. if ( edgeData[ key ] ) {
  23443. const { index0, index1 } = edgeData[ key ];
  23444. _v0.fromBufferAttribute( positionAttr, index0 );
  23445. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23446. vertices.push( _v0.x, _v0.y, _v0.z );
  23447. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23448. }
  23449. }
  23450. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23451. }
  23452. }
  23453. copy( source ) {
  23454. super.copy( source );
  23455. this.parameters = Object.assign( {}, source.parameters );
  23456. return this;
  23457. }
  23458. }
  23459. /**
  23460. * An abstract base class for creating an analytic curve object that contains methods
  23461. * for interpolation.
  23462. *
  23463. * @abstract
  23464. */
  23465. class Curve {
  23466. /**
  23467. * Constructs a new curve.
  23468. */
  23469. constructor() {
  23470. /**
  23471. * The type property is used for detecting the object type
  23472. * in context of serialization/deserialization.
  23473. *
  23474. * @type {string}
  23475. * @readonly
  23476. */
  23477. this.type = 'Curve';
  23478. /**
  23479. * This value determines the amount of divisions when calculating the
  23480. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23481. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23482. * recommended to increase the value of this property if the curve is very large.
  23483. *
  23484. * @type {number}
  23485. * @default 200
  23486. */
  23487. this.arcLengthDivisions = 200;
  23488. /**
  23489. * Must be set to `true` if the curve parameters have changed.
  23490. *
  23491. * @type {boolean}
  23492. * @default false
  23493. */
  23494. this.needsUpdate = false;
  23495. /**
  23496. * An internal cache that holds precomputed curve length values.
  23497. *
  23498. * @private
  23499. * @type {?Array<number>}
  23500. * @default null
  23501. */
  23502. this.cacheArcLengths = null;
  23503. }
  23504. /**
  23505. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23506. * for the given interpolation factor.
  23507. *
  23508. * @abstract
  23509. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23510. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23511. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23512. */
  23513. getPoint( /* t, optionalTarget */ ) {
  23514. warn( 'Curve: .getPoint() not implemented.' );
  23515. }
  23516. /**
  23517. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23518. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23519. * of the curve which equidistant samples.
  23520. *
  23521. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23522. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23523. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23524. */
  23525. getPointAt( u, optionalTarget ) {
  23526. const t = this.getUtoTmapping( u );
  23527. return this.getPoint( t, optionalTarget );
  23528. }
  23529. /**
  23530. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23531. * the curve shape.
  23532. *
  23533. * @param {number} [divisions=5] - The number of divisions.
  23534. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23535. */
  23536. getPoints( divisions = 5 ) {
  23537. const points = [];
  23538. for ( let d = 0; d <= divisions; d ++ ) {
  23539. points.push( this.getPoint( d / divisions ) );
  23540. }
  23541. return points;
  23542. }
  23543. // Get sequence of points using getPointAt( u )
  23544. /**
  23545. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23546. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23547. * curve.
  23548. *
  23549. * @param {number} [divisions=5] - The number of divisions.
  23550. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23551. */
  23552. getSpacedPoints( divisions = 5 ) {
  23553. const points = [];
  23554. for ( let d = 0; d <= divisions; d ++ ) {
  23555. points.push( this.getPointAt( d / divisions ) );
  23556. }
  23557. return points;
  23558. }
  23559. /**
  23560. * Returns the total arc length of the curve.
  23561. *
  23562. * @return {number} The length of the curve.
  23563. */
  23564. getLength() {
  23565. const lengths = this.getLengths();
  23566. return lengths[ lengths.length - 1 ];
  23567. }
  23568. /**
  23569. * Returns an array of cumulative segment lengths of the curve.
  23570. *
  23571. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23572. * @return {Array<number>} An array holding the cumulative segment lengths.
  23573. */
  23574. getLengths( divisions = this.arcLengthDivisions ) {
  23575. if ( this.cacheArcLengths &&
  23576. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23577. ! this.needsUpdate ) {
  23578. return this.cacheArcLengths;
  23579. }
  23580. this.needsUpdate = false;
  23581. const cache = [];
  23582. let current, last = this.getPoint( 0 );
  23583. let sum = 0;
  23584. cache.push( 0 );
  23585. for ( let p = 1; p <= divisions; p ++ ) {
  23586. current = this.getPoint( p / divisions );
  23587. sum += current.distanceTo( last );
  23588. cache.push( sum );
  23589. last = current;
  23590. }
  23591. this.cacheArcLengths = cache;
  23592. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23593. }
  23594. /**
  23595. * Update the cumulative segment distance cache. The method must be called
  23596. * every time curve parameters are changed. If an updated curve is part of a
  23597. * composed curve like {@link CurvePath}, this method must be called on the
  23598. * composed curve, too.
  23599. */
  23600. updateArcLengths() {
  23601. this.needsUpdate = true;
  23602. this.getLengths();
  23603. }
  23604. /**
  23605. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23606. * interpolation factor in the same range that can be ued to sample equidistant points
  23607. * from a curve.
  23608. *
  23609. * @param {number} u - The interpolation factor.
  23610. * @param {?number} distance - An optional distance on the curve.
  23611. * @return {number} The updated interpolation factor.
  23612. */
  23613. getUtoTmapping( u, distance = null ) {
  23614. const arcLengths = this.getLengths();
  23615. let i = 0;
  23616. const il = arcLengths.length;
  23617. let targetArcLength; // The targeted u distance value to get
  23618. if ( distance ) {
  23619. targetArcLength = distance;
  23620. } else {
  23621. targetArcLength = u * arcLengths[ il - 1 ];
  23622. }
  23623. // binary search for the index with largest value smaller than target u distance
  23624. let low = 0, high = il - 1, comparison;
  23625. while ( low <= high ) {
  23626. 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
  23627. comparison = arcLengths[ i ] - targetArcLength;
  23628. if ( comparison < 0 ) {
  23629. low = i + 1;
  23630. } else if ( comparison > 0 ) {
  23631. high = i - 1;
  23632. } else {
  23633. high = i;
  23634. break;
  23635. // DONE
  23636. }
  23637. }
  23638. i = high;
  23639. if ( arcLengths[ i ] === targetArcLength ) {
  23640. return i / ( il - 1 );
  23641. }
  23642. // we could get finer grain at lengths, or use simple interpolation between two points
  23643. const lengthBefore = arcLengths[ i ];
  23644. const lengthAfter = arcLengths[ i + 1 ];
  23645. const segmentLength = lengthAfter - lengthBefore;
  23646. // determine where we are between the 'before' and 'after' points
  23647. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23648. // add that fractional amount to t
  23649. const t = ( i + segmentFraction ) / ( il - 1 );
  23650. return t;
  23651. }
  23652. /**
  23653. * Returns a unit vector tangent for the given interpolation factor.
  23654. * If the derived curve does not implement its tangent derivation,
  23655. * two points a small delta apart will be used to find its gradient
  23656. * which seems to give a reasonable approximation.
  23657. *
  23658. * @param {number} t - The interpolation factor.
  23659. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23660. * @return {(Vector2|Vector3)} The tangent vector.
  23661. */
  23662. getTangent( t, optionalTarget ) {
  23663. const delta = 0.0001;
  23664. let t1 = t - delta;
  23665. let t2 = t + delta;
  23666. // Capping in case of danger
  23667. if ( t1 < 0 ) t1 = 0;
  23668. if ( t2 > 1 ) t2 = 1;
  23669. const pt1 = this.getPoint( t1 );
  23670. const pt2 = this.getPoint( t2 );
  23671. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23672. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23673. return tangent;
  23674. }
  23675. /**
  23676. * Same as {@link Curve#getTangent} but with equidistant samples.
  23677. *
  23678. * @param {number} u - The interpolation factor.
  23679. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23680. * @return {(Vector2|Vector3)} The tangent vector.
  23681. * @see {@link Curve#getPointAt}
  23682. */
  23683. getTangentAt( u, optionalTarget ) {
  23684. const t = this.getUtoTmapping( u );
  23685. return this.getTangent( t, optionalTarget );
  23686. }
  23687. /**
  23688. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23689. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23690. *
  23691. * @param {number} segments - The number of segments.
  23692. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23693. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23694. */
  23695. computeFrenetFrames( segments, closed = false ) {
  23696. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23697. const normal = new Vector3();
  23698. const tangents = [];
  23699. const normals = [];
  23700. const binormals = [];
  23701. const vec = new Vector3();
  23702. const mat = new Matrix4();
  23703. // compute the tangent vectors for each segment on the curve
  23704. for ( let i = 0; i <= segments; i ++ ) {
  23705. const u = i / segments;
  23706. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23707. }
  23708. // select an initial normal vector perpendicular to the first tangent vector,
  23709. // and in the direction of the minimum tangent xyz component
  23710. normals[ 0 ] = new Vector3();
  23711. binormals[ 0 ] = new Vector3();
  23712. let min = Number.MAX_VALUE;
  23713. const tx = Math.abs( tangents[ 0 ].x );
  23714. const ty = Math.abs( tangents[ 0 ].y );
  23715. const tz = Math.abs( tangents[ 0 ].z );
  23716. if ( tx <= min ) {
  23717. min = tx;
  23718. normal.set( 1, 0, 0 );
  23719. }
  23720. if ( ty <= min ) {
  23721. min = ty;
  23722. normal.set( 0, 1, 0 );
  23723. }
  23724. if ( tz <= min ) {
  23725. normal.set( 0, 0, 1 );
  23726. }
  23727. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23728. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23729. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23730. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23731. for ( let i = 1; i <= segments; i ++ ) {
  23732. normals[ i ] = normals[ i - 1 ].clone();
  23733. binormals[ i ] = binormals[ i - 1 ].clone();
  23734. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23735. if ( vec.length() > Number.EPSILON ) {
  23736. vec.normalize();
  23737. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23738. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23739. }
  23740. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23741. }
  23742. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23743. if ( closed === true ) {
  23744. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23745. theta /= segments;
  23746. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23747. theta = - theta;
  23748. }
  23749. for ( let i = 1; i <= segments; i ++ ) {
  23750. // twist a little...
  23751. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23752. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23753. }
  23754. }
  23755. return {
  23756. tangents: tangents,
  23757. normals: normals,
  23758. binormals: binormals
  23759. };
  23760. }
  23761. /**
  23762. * Returns a new curve with copied values from this instance.
  23763. *
  23764. * @return {Curve} A clone of this instance.
  23765. */
  23766. clone() {
  23767. return new this.constructor().copy( this );
  23768. }
  23769. /**
  23770. * Copies the values of the given curve to this instance.
  23771. *
  23772. * @param {Curve} source - The curve to copy.
  23773. * @return {Curve} A reference to this curve.
  23774. */
  23775. copy( source ) {
  23776. this.arcLengthDivisions = source.arcLengthDivisions;
  23777. return this;
  23778. }
  23779. /**
  23780. * Serializes the curve into JSON.
  23781. *
  23782. * @return {Object} A JSON object representing the serialized curve.
  23783. * @see {@link ObjectLoader#parse}
  23784. */
  23785. toJSON() {
  23786. const data = {
  23787. metadata: {
  23788. version: 4.7,
  23789. type: 'Curve',
  23790. generator: 'Curve.toJSON'
  23791. }
  23792. };
  23793. data.arcLengthDivisions = this.arcLengthDivisions;
  23794. data.type = this.type;
  23795. return data;
  23796. }
  23797. /**
  23798. * Deserializes the curve from the given JSON.
  23799. *
  23800. * @param {Object} json - The JSON holding the serialized curve.
  23801. * @return {Curve} A reference to this curve.
  23802. */
  23803. fromJSON( json ) {
  23804. this.arcLengthDivisions = json.arcLengthDivisions;
  23805. return this;
  23806. }
  23807. }
  23808. /**
  23809. * A curve representing an ellipse.
  23810. *
  23811. * ```js
  23812. * const curve = new THREE.EllipseCurve(
  23813. * 0, 0,
  23814. * 10, 10,
  23815. * 0, 2 * Math.PI,
  23816. * false,
  23817. * 0
  23818. * );
  23819. *
  23820. * const points = curve.getPoints( 50 );
  23821. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23822. *
  23823. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23824. *
  23825. * // Create the final object to add to the scene
  23826. * const ellipse = new THREE.Line( geometry, material );
  23827. * ```
  23828. *
  23829. * @augments Curve
  23830. */
  23831. class EllipseCurve extends Curve {
  23832. /**
  23833. * Constructs a new ellipse curve.
  23834. *
  23835. * @param {number} [aX=0] - The X center of the ellipse.
  23836. * @param {number} [aY=0] - The Y center of the ellipse.
  23837. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23838. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23839. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23840. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23841. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23842. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23843. */
  23844. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23845. super();
  23846. /**
  23847. * This flag can be used for type testing.
  23848. *
  23849. * @type {boolean}
  23850. * @readonly
  23851. * @default true
  23852. */
  23853. this.isEllipseCurve = true;
  23854. this.type = 'EllipseCurve';
  23855. /**
  23856. * The X center of the ellipse.
  23857. *
  23858. * @type {number}
  23859. * @default 0
  23860. */
  23861. this.aX = aX;
  23862. /**
  23863. * The Y center of the ellipse.
  23864. *
  23865. * @type {number}
  23866. * @default 0
  23867. */
  23868. this.aY = aY;
  23869. /**
  23870. * The radius of the ellipse in the x direction.
  23871. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23872. *
  23873. * @type {number}
  23874. * @default 1
  23875. */
  23876. this.xRadius = xRadius;
  23877. /**
  23878. * The radius of the ellipse in the y direction.
  23879. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23880. *
  23881. * @type {number}
  23882. * @default 1
  23883. */
  23884. this.yRadius = yRadius;
  23885. /**
  23886. * The start angle of the curve in radians starting from the positive X axis.
  23887. *
  23888. * @type {number}
  23889. * @default 0
  23890. */
  23891. this.aStartAngle = aStartAngle;
  23892. /**
  23893. * The end angle of the curve in radians starting from the positive X axis.
  23894. *
  23895. * @type {number}
  23896. * @default Math.PI*2
  23897. */
  23898. this.aEndAngle = aEndAngle;
  23899. /**
  23900. * Whether the ellipse is drawn clockwise or not.
  23901. *
  23902. * @type {boolean}
  23903. * @default false
  23904. */
  23905. this.aClockwise = aClockwise;
  23906. /**
  23907. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23908. *
  23909. * @type {number}
  23910. * @default 0
  23911. */
  23912. this.aRotation = aRotation;
  23913. }
  23914. /**
  23915. * Returns a point on the curve.
  23916. *
  23917. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23918. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23919. * @return {Vector2} The position on the curve.
  23920. */
  23921. getPoint( t, optionalTarget = new Vector2() ) {
  23922. const point = optionalTarget;
  23923. const twoPi = Math.PI * 2;
  23924. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23925. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23926. // ensures that deltaAngle is 0 .. 2 PI
  23927. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23928. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23929. if ( deltaAngle < Number.EPSILON ) {
  23930. if ( samePoints ) {
  23931. deltaAngle = 0;
  23932. } else {
  23933. deltaAngle = twoPi;
  23934. }
  23935. }
  23936. if ( this.aClockwise === true && ! samePoints ) {
  23937. if ( deltaAngle === twoPi ) {
  23938. deltaAngle = - twoPi;
  23939. } else {
  23940. deltaAngle = deltaAngle - twoPi;
  23941. }
  23942. }
  23943. const angle = this.aStartAngle + t * deltaAngle;
  23944. let x = this.aX + this.xRadius * Math.cos( angle );
  23945. let y = this.aY + this.yRadius * Math.sin( angle );
  23946. if ( this.aRotation !== 0 ) {
  23947. const cos = Math.cos( this.aRotation );
  23948. const sin = Math.sin( this.aRotation );
  23949. const tx = x - this.aX;
  23950. const ty = y - this.aY;
  23951. // Rotate the point about the center of the ellipse.
  23952. x = tx * cos - ty * sin + this.aX;
  23953. y = tx * sin + ty * cos + this.aY;
  23954. }
  23955. return point.set( x, y );
  23956. }
  23957. copy( source ) {
  23958. super.copy( source );
  23959. this.aX = source.aX;
  23960. this.aY = source.aY;
  23961. this.xRadius = source.xRadius;
  23962. this.yRadius = source.yRadius;
  23963. this.aStartAngle = source.aStartAngle;
  23964. this.aEndAngle = source.aEndAngle;
  23965. this.aClockwise = source.aClockwise;
  23966. this.aRotation = source.aRotation;
  23967. return this;
  23968. }
  23969. toJSON() {
  23970. const data = super.toJSON();
  23971. data.aX = this.aX;
  23972. data.aY = this.aY;
  23973. data.xRadius = this.xRadius;
  23974. data.yRadius = this.yRadius;
  23975. data.aStartAngle = this.aStartAngle;
  23976. data.aEndAngle = this.aEndAngle;
  23977. data.aClockwise = this.aClockwise;
  23978. data.aRotation = this.aRotation;
  23979. return data;
  23980. }
  23981. fromJSON( json ) {
  23982. super.fromJSON( json );
  23983. this.aX = json.aX;
  23984. this.aY = json.aY;
  23985. this.xRadius = json.xRadius;
  23986. this.yRadius = json.yRadius;
  23987. this.aStartAngle = json.aStartAngle;
  23988. this.aEndAngle = json.aEndAngle;
  23989. this.aClockwise = json.aClockwise;
  23990. this.aRotation = json.aRotation;
  23991. return this;
  23992. }
  23993. }
  23994. /**
  23995. * A curve representing an arc.
  23996. *
  23997. * @augments EllipseCurve
  23998. */
  23999. class ArcCurve extends EllipseCurve {
  24000. /**
  24001. * Constructs a new arc curve.
  24002. *
  24003. * @param {number} [aX=0] - The X center of the ellipse.
  24004. * @param {number} [aY=0] - The Y center of the ellipse.
  24005. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  24006. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  24007. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  24008. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  24009. */
  24010. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24011. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24012. /**
  24013. * This flag can be used for type testing.
  24014. *
  24015. * @type {boolean}
  24016. * @readonly
  24017. * @default true
  24018. */
  24019. this.isArcCurve = true;
  24020. this.type = 'ArcCurve';
  24021. }
  24022. }
  24023. function CubicPoly() {
  24024. /**
  24025. * Centripetal CatmullRom Curve - which is useful for avoiding
  24026. * cusps and self-intersections in non-uniform catmull rom curves.
  24027. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24028. *
  24029. * curve.type accepts centripetal(default), chordal and catmullrom
  24030. * curve.tension is used for catmullrom which defaults to 0.5
  24031. */
  24032. /*
  24033. Based on an optimized c++ solution in
  24034. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24035. - http://ideone.com/NoEbVM
  24036. This CubicPoly class could be used for reusing some variables and calculations,
  24037. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24038. which can be placed in CurveUtils.
  24039. */
  24040. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  24041. /*
  24042. * Compute coefficients for a cubic polynomial
  24043. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24044. * such that
  24045. * p(0) = x0, p(1) = x1
  24046. * and
  24047. * p'(0) = t0, p'(1) = t1.
  24048. */
  24049. function init( x0, x1, t0, t1 ) {
  24050. c0 = x0;
  24051. c1 = t0;
  24052. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  24053. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24054. }
  24055. return {
  24056. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  24057. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24058. },
  24059. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24060. // compute tangents when parameterized in [t1,t2]
  24061. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24062. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24063. // rescale tangents for parametrization in [0,1]
  24064. t1 *= dt1;
  24065. t2 *= dt1;
  24066. init( x1, x2, t1, t2 );
  24067. },
  24068. calc: function ( t ) {
  24069. const t2 = t * t;
  24070. const t3 = t2 * t;
  24071. return c0 + c1 * t + c2 * t2 + c3 * t3;
  24072. }
  24073. };
  24074. }
  24075. //
  24076. const tmp = /*@__PURE__*/ new Vector3();
  24077. const px = /*@__PURE__*/ new CubicPoly();
  24078. const py = /*@__PURE__*/ new CubicPoly();
  24079. const pz = /*@__PURE__*/ new CubicPoly();
  24080. /**
  24081. * A curve representing a Catmull-Rom spline.
  24082. *
  24083. * ```js
  24084. * //Create a closed wavey loop
  24085. * const curve = new THREE.CatmullRomCurve3( [
  24086. * new THREE.Vector3( -10, 0, 10 ),
  24087. * new THREE.Vector3( -5, 5, 5 ),
  24088. * new THREE.Vector3( 0, 0, 0 ),
  24089. * new THREE.Vector3( 5, -5, 5 ),
  24090. * new THREE.Vector3( 10, 0, 10 )
  24091. * ] );
  24092. *
  24093. * const points = curve.getPoints( 50 );
  24094. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24095. *
  24096. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24097. *
  24098. * // Create the final object to add to the scene
  24099. * const curveObject = new THREE.Line( geometry, material );
  24100. * ```
  24101. *
  24102. * @augments Curve
  24103. */
  24104. class CatmullRomCurve3 extends Curve {
  24105. /**
  24106. * Constructs a new Catmull-Rom curve.
  24107. *
  24108. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  24109. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  24110. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  24111. * @param {number} [tension=0.5] - Tension of the curve.
  24112. */
  24113. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  24114. super();
  24115. /**
  24116. * This flag can be used for type testing.
  24117. *
  24118. * @type {boolean}
  24119. * @readonly
  24120. * @default true
  24121. */
  24122. this.isCatmullRomCurve3 = true;
  24123. this.type = 'CatmullRomCurve3';
  24124. /**
  24125. * An array of 3D points defining the curve.
  24126. *
  24127. * @type {Array<Vector3>}
  24128. */
  24129. this.points = points;
  24130. /**
  24131. * Whether the curve is closed or not.
  24132. *
  24133. * @type {boolean}
  24134. * @default false
  24135. */
  24136. this.closed = closed;
  24137. /**
  24138. * The curve type.
  24139. *
  24140. * @type {('centripetal'|'chordal'|'catmullrom')}
  24141. * @default 'centripetal'
  24142. */
  24143. this.curveType = curveType;
  24144. /**
  24145. * Tension of the curve.
  24146. *
  24147. * @type {number}
  24148. * @default 0.5
  24149. */
  24150. this.tension = tension;
  24151. }
  24152. /**
  24153. * Returns a point on the curve.
  24154. *
  24155. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24156. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24157. * @return {Vector3} The position on the curve.
  24158. */
  24159. getPoint( t, optionalTarget = new Vector3() ) {
  24160. const point = optionalTarget;
  24161. const points = this.points;
  24162. const l = points.length;
  24163. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24164. let intPoint = Math.floor( p );
  24165. let weight = p - intPoint;
  24166. if ( this.closed ) {
  24167. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  24168. } else if ( weight === 0 && intPoint === l - 1 ) {
  24169. intPoint = l - 2;
  24170. weight = 1;
  24171. }
  24172. let p0, p3; // 4 points (p1 & p2 defined below)
  24173. if ( this.closed || intPoint > 0 ) {
  24174. p0 = points[ ( intPoint - 1 ) % l ];
  24175. } else {
  24176. // extrapolate first point
  24177. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24178. p0 = tmp;
  24179. }
  24180. const p1 = points[ intPoint % l ];
  24181. const p2 = points[ ( intPoint + 1 ) % l ];
  24182. if ( this.closed || intPoint + 2 < l ) {
  24183. p3 = points[ ( intPoint + 2 ) % l ];
  24184. } else {
  24185. // extrapolate last point
  24186. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24187. p3 = tmp;
  24188. }
  24189. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  24190. // init Centripetal / Chordal Catmull-Rom
  24191. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  24192. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24193. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24194. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24195. // safety check for repeated points
  24196. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24197. if ( dt0 < 1e-4 ) dt0 = dt1;
  24198. if ( dt2 < 1e-4 ) dt2 = dt1;
  24199. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24200. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24201. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24202. } else if ( this.curveType === 'catmullrom' ) {
  24203. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  24204. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  24205. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  24206. }
  24207. point.set(
  24208. px.calc( weight ),
  24209. py.calc( weight ),
  24210. pz.calc( weight )
  24211. );
  24212. return point;
  24213. }
  24214. copy( source ) {
  24215. super.copy( source );
  24216. this.points = [];
  24217. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24218. const point = source.points[ i ];
  24219. this.points.push( point.clone() );
  24220. }
  24221. this.closed = source.closed;
  24222. this.curveType = source.curveType;
  24223. this.tension = source.tension;
  24224. return this;
  24225. }
  24226. toJSON() {
  24227. const data = super.toJSON();
  24228. data.points = [];
  24229. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24230. const point = this.points[ i ];
  24231. data.points.push( point.toArray() );
  24232. }
  24233. data.closed = this.closed;
  24234. data.curveType = this.curveType;
  24235. data.tension = this.tension;
  24236. return data;
  24237. }
  24238. fromJSON( json ) {
  24239. super.fromJSON( json );
  24240. this.points = [];
  24241. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24242. const point = json.points[ i ];
  24243. this.points.push( new Vector3().fromArray( point ) );
  24244. }
  24245. this.closed = json.closed;
  24246. this.curveType = json.curveType;
  24247. this.tension = json.tension;
  24248. return this;
  24249. }
  24250. }
  24251. /**
  24252. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  24253. *
  24254. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  24255. *
  24256. * @module Interpolations
  24257. */
  24258. /**
  24259. * Computes a point on a Catmull-Rom spline.
  24260. *
  24261. * @param {number} t - The interpolation factor.
  24262. * @param {number} p0 - The first control point.
  24263. * @param {number} p1 - The second control point.
  24264. * @param {number} p2 - The third control point.
  24265. * @param {number} p3 - The fourth control point.
  24266. * @return {number} The calculated point on a Catmull-Rom spline.
  24267. */
  24268. function CatmullRom( t, p0, p1, p2, p3 ) {
  24269. const v0 = ( p2 - p0 ) * 0.5;
  24270. const v1 = ( p3 - p1 ) * 0.5;
  24271. const t2 = t * t;
  24272. const t3 = t * t2;
  24273. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  24274. }
  24275. //
  24276. function QuadraticBezierP0( t, p ) {
  24277. const k = 1 - t;
  24278. return k * k * p;
  24279. }
  24280. function QuadraticBezierP1( t, p ) {
  24281. return 2 * ( 1 - t ) * t * p;
  24282. }
  24283. function QuadraticBezierP2( t, p ) {
  24284. return t * t * p;
  24285. }
  24286. /**
  24287. * Computes a point on a Quadratic Bezier curve.
  24288. *
  24289. * @param {number} t - The interpolation factor.
  24290. * @param {number} p0 - The first control point.
  24291. * @param {number} p1 - The second control point.
  24292. * @param {number} p2 - The third control point.
  24293. * @return {number} The calculated point on a Quadratic Bezier curve.
  24294. */
  24295. function QuadraticBezier( t, p0, p1, p2 ) {
  24296. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  24297. QuadraticBezierP2( t, p2 );
  24298. }
  24299. //
  24300. function CubicBezierP0( t, p ) {
  24301. const k = 1 - t;
  24302. return k * k * k * p;
  24303. }
  24304. function CubicBezierP1( t, p ) {
  24305. const k = 1 - t;
  24306. return 3 * k * k * t * p;
  24307. }
  24308. function CubicBezierP2( t, p ) {
  24309. return 3 * ( 1 - t ) * t * t * p;
  24310. }
  24311. function CubicBezierP3( t, p ) {
  24312. return t * t * t * p;
  24313. }
  24314. /**
  24315. * Computes a point on a Cubic Bezier curve.
  24316. *
  24317. * @param {number} t - The interpolation factor.
  24318. * @param {number} p0 - The first control point.
  24319. * @param {number} p1 - The second control point.
  24320. * @param {number} p2 - The third control point.
  24321. * @param {number} p3 - The fourth control point.
  24322. * @return {number} The calculated point on a Cubic Bezier curve.
  24323. */
  24324. function CubicBezier( t, p0, p1, p2, p3 ) {
  24325. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  24326. CubicBezierP3( t, p3 );
  24327. }
  24328. /**
  24329. * A curve representing a 2D Cubic Bezier curve.
  24330. *
  24331. * ```js
  24332. * const curve = new THREE.CubicBezierCurve(
  24333. * new THREE.Vector2( - 0, 0 ),
  24334. * new THREE.Vector2( - 5, 15 ),
  24335. * new THREE.Vector2( 20, 15 ),
  24336. * new THREE.Vector2( 10, 0 )
  24337. * );
  24338. *
  24339. * const points = curve.getPoints( 50 );
  24340. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24341. *
  24342. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24343. *
  24344. * // Create the final object to add to the scene
  24345. * const curveObject = new THREE.Line( geometry, material );
  24346. * ```
  24347. *
  24348. * @augments Curve
  24349. */
  24350. class CubicBezierCurve extends Curve {
  24351. /**
  24352. * Constructs a new Cubic Bezier curve.
  24353. *
  24354. * @param {Vector2} [v0] - The start point.
  24355. * @param {Vector2} [v1] - The first control point.
  24356. * @param {Vector2} [v2] - The second control point.
  24357. * @param {Vector2} [v3] - The end point.
  24358. */
  24359. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  24360. super();
  24361. /**
  24362. * This flag can be used for type testing.
  24363. *
  24364. * @type {boolean}
  24365. * @readonly
  24366. * @default true
  24367. */
  24368. this.isCubicBezierCurve = true;
  24369. this.type = 'CubicBezierCurve';
  24370. /**
  24371. * The start point.
  24372. *
  24373. * @type {Vector2}
  24374. */
  24375. this.v0 = v0;
  24376. /**
  24377. * The first control point.
  24378. *
  24379. * @type {Vector2}
  24380. */
  24381. this.v1 = v1;
  24382. /**
  24383. * The second control point.
  24384. *
  24385. * @type {Vector2}
  24386. */
  24387. this.v2 = v2;
  24388. /**
  24389. * The end point.
  24390. *
  24391. * @type {Vector2}
  24392. */
  24393. this.v3 = v3;
  24394. }
  24395. /**
  24396. * Returns a point on the curve.
  24397. *
  24398. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24399. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24400. * @return {Vector2} The position on the curve.
  24401. */
  24402. getPoint( t, optionalTarget = new Vector2() ) {
  24403. const point = optionalTarget;
  24404. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24405. point.set(
  24406. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24407. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24408. );
  24409. return point;
  24410. }
  24411. copy( source ) {
  24412. super.copy( source );
  24413. this.v0.copy( source.v0 );
  24414. this.v1.copy( source.v1 );
  24415. this.v2.copy( source.v2 );
  24416. this.v3.copy( source.v3 );
  24417. return this;
  24418. }
  24419. toJSON() {
  24420. const data = super.toJSON();
  24421. data.v0 = this.v0.toArray();
  24422. data.v1 = this.v1.toArray();
  24423. data.v2 = this.v2.toArray();
  24424. data.v3 = this.v3.toArray();
  24425. return data;
  24426. }
  24427. fromJSON( json ) {
  24428. super.fromJSON( json );
  24429. this.v0.fromArray( json.v0 );
  24430. this.v1.fromArray( json.v1 );
  24431. this.v2.fromArray( json.v2 );
  24432. this.v3.fromArray( json.v3 );
  24433. return this;
  24434. }
  24435. }
  24436. /**
  24437. * A curve representing a 3D Cubic Bezier curve.
  24438. *
  24439. * @augments Curve
  24440. */
  24441. class CubicBezierCurve3 extends Curve {
  24442. /**
  24443. * Constructs a new Cubic Bezier curve.
  24444. *
  24445. * @param {Vector3} [v0] - The start point.
  24446. * @param {Vector3} [v1] - The first control point.
  24447. * @param {Vector3} [v2] - The second control point.
  24448. * @param {Vector3} [v3] - The end point.
  24449. */
  24450. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24451. super();
  24452. /**
  24453. * This flag can be used for type testing.
  24454. *
  24455. * @type {boolean}
  24456. * @readonly
  24457. * @default true
  24458. */
  24459. this.isCubicBezierCurve3 = true;
  24460. this.type = 'CubicBezierCurve3';
  24461. /**
  24462. * The start point.
  24463. *
  24464. * @type {Vector3}
  24465. */
  24466. this.v0 = v0;
  24467. /**
  24468. * The first control point.
  24469. *
  24470. * @type {Vector3}
  24471. */
  24472. this.v1 = v1;
  24473. /**
  24474. * The second control point.
  24475. *
  24476. * @type {Vector3}
  24477. */
  24478. this.v2 = v2;
  24479. /**
  24480. * The end point.
  24481. *
  24482. * @type {Vector3}
  24483. */
  24484. this.v3 = v3;
  24485. }
  24486. /**
  24487. * Returns a point on the curve.
  24488. *
  24489. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24490. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24491. * @return {Vector3} The position on the curve.
  24492. */
  24493. getPoint( t, optionalTarget = new Vector3() ) {
  24494. const point = optionalTarget;
  24495. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24496. point.set(
  24497. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24498. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24499. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24500. );
  24501. return point;
  24502. }
  24503. copy( source ) {
  24504. super.copy( source );
  24505. this.v0.copy( source.v0 );
  24506. this.v1.copy( source.v1 );
  24507. this.v2.copy( source.v2 );
  24508. this.v3.copy( source.v3 );
  24509. return this;
  24510. }
  24511. toJSON() {
  24512. const data = super.toJSON();
  24513. data.v0 = this.v0.toArray();
  24514. data.v1 = this.v1.toArray();
  24515. data.v2 = this.v2.toArray();
  24516. data.v3 = this.v3.toArray();
  24517. return data;
  24518. }
  24519. fromJSON( json ) {
  24520. super.fromJSON( json );
  24521. this.v0.fromArray( json.v0 );
  24522. this.v1.fromArray( json.v1 );
  24523. this.v2.fromArray( json.v2 );
  24524. this.v3.fromArray( json.v3 );
  24525. return this;
  24526. }
  24527. }
  24528. /**
  24529. * A curve representing a 2D line segment.
  24530. *
  24531. * @augments Curve
  24532. */
  24533. class LineCurve extends Curve {
  24534. /**
  24535. * Constructs a new line curve.
  24536. *
  24537. * @param {Vector2} [v1] - The start point.
  24538. * @param {Vector2} [v2] - The end point.
  24539. */
  24540. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24541. super();
  24542. /**
  24543. * This flag can be used for type testing.
  24544. *
  24545. * @type {boolean}
  24546. * @readonly
  24547. * @default true
  24548. */
  24549. this.isLineCurve = true;
  24550. this.type = 'LineCurve';
  24551. /**
  24552. * The start point.
  24553. *
  24554. * @type {Vector2}
  24555. */
  24556. this.v1 = v1;
  24557. /**
  24558. * The end point.
  24559. *
  24560. * @type {Vector2}
  24561. */
  24562. this.v2 = v2;
  24563. }
  24564. /**
  24565. * Returns a point on the line.
  24566. *
  24567. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24568. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24569. * @return {Vector2} The position on the line.
  24570. */
  24571. getPoint( t, optionalTarget = new Vector2() ) {
  24572. const point = optionalTarget;
  24573. if ( t === 1 ) {
  24574. point.copy( this.v2 );
  24575. } else {
  24576. point.copy( this.v2 ).sub( this.v1 );
  24577. point.multiplyScalar( t ).add( this.v1 );
  24578. }
  24579. return point;
  24580. }
  24581. // Line curve is linear, so we can overwrite default getPointAt
  24582. getPointAt( u, optionalTarget ) {
  24583. return this.getPoint( u, optionalTarget );
  24584. }
  24585. getTangent( t, optionalTarget = new Vector2() ) {
  24586. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24587. }
  24588. getTangentAt( u, optionalTarget ) {
  24589. return this.getTangent( u, optionalTarget );
  24590. }
  24591. copy( source ) {
  24592. super.copy( source );
  24593. this.v1.copy( source.v1 );
  24594. this.v2.copy( source.v2 );
  24595. return this;
  24596. }
  24597. toJSON() {
  24598. const data = super.toJSON();
  24599. data.v1 = this.v1.toArray();
  24600. data.v2 = this.v2.toArray();
  24601. return data;
  24602. }
  24603. fromJSON( json ) {
  24604. super.fromJSON( json );
  24605. this.v1.fromArray( json.v1 );
  24606. this.v2.fromArray( json.v2 );
  24607. return this;
  24608. }
  24609. }
  24610. /**
  24611. * A curve representing a 3D line segment.
  24612. *
  24613. * @augments Curve
  24614. */
  24615. class LineCurve3 extends Curve {
  24616. /**
  24617. * Constructs a new line curve.
  24618. *
  24619. * @param {Vector3} [v1] - The start point.
  24620. * @param {Vector3} [v2] - The end point.
  24621. */
  24622. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24623. super();
  24624. /**
  24625. * This flag can be used for type testing.
  24626. *
  24627. * @type {boolean}
  24628. * @readonly
  24629. * @default true
  24630. */
  24631. this.isLineCurve3 = true;
  24632. this.type = 'LineCurve3';
  24633. /**
  24634. * The start point.
  24635. *
  24636. * @type {Vector3}
  24637. */
  24638. this.v1 = v1;
  24639. /**
  24640. * The end point.
  24641. *
  24642. * @type {Vector2}
  24643. */
  24644. this.v2 = v2;
  24645. }
  24646. /**
  24647. * Returns a point on the line.
  24648. *
  24649. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24650. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24651. * @return {Vector3} The position on the line.
  24652. */
  24653. getPoint( t, optionalTarget = new Vector3() ) {
  24654. const point = optionalTarget;
  24655. if ( t === 1 ) {
  24656. point.copy( this.v2 );
  24657. } else {
  24658. point.copy( this.v2 ).sub( this.v1 );
  24659. point.multiplyScalar( t ).add( this.v1 );
  24660. }
  24661. return point;
  24662. }
  24663. // Line curve is linear, so we can overwrite default getPointAt
  24664. getPointAt( u, optionalTarget ) {
  24665. return this.getPoint( u, optionalTarget );
  24666. }
  24667. getTangent( t, optionalTarget = new Vector3() ) {
  24668. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24669. }
  24670. getTangentAt( u, optionalTarget ) {
  24671. return this.getTangent( u, optionalTarget );
  24672. }
  24673. copy( source ) {
  24674. super.copy( source );
  24675. this.v1.copy( source.v1 );
  24676. this.v2.copy( source.v2 );
  24677. return this;
  24678. }
  24679. toJSON() {
  24680. const data = super.toJSON();
  24681. data.v1 = this.v1.toArray();
  24682. data.v2 = this.v2.toArray();
  24683. return data;
  24684. }
  24685. fromJSON( json ) {
  24686. super.fromJSON( json );
  24687. this.v1.fromArray( json.v1 );
  24688. this.v2.fromArray( json.v2 );
  24689. return this;
  24690. }
  24691. }
  24692. /**
  24693. * A curve representing a 2D Quadratic Bezier curve.
  24694. *
  24695. * ```js
  24696. * const curve = new THREE.QuadraticBezierCurve(
  24697. * new THREE.Vector2( - 10, 0 ),
  24698. * new THREE.Vector2( 20, 15 ),
  24699. * new THREE.Vector2( 10, 0 )
  24700. * )
  24701. *
  24702. * const points = curve.getPoints( 50 );
  24703. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24704. *
  24705. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24706. *
  24707. * // Create the final object to add to the scene
  24708. * const curveObject = new THREE.Line( geometry, material );
  24709. * ```
  24710. *
  24711. * @augments Curve
  24712. */
  24713. class QuadraticBezierCurve extends Curve {
  24714. /**
  24715. * Constructs a new Quadratic Bezier curve.
  24716. *
  24717. * @param {Vector2} [v0] - The start point.
  24718. * @param {Vector2} [v1] - The control point.
  24719. * @param {Vector2} [v2] - The end point.
  24720. */
  24721. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24722. super();
  24723. /**
  24724. * This flag can be used for type testing.
  24725. *
  24726. * @type {boolean}
  24727. * @readonly
  24728. * @default true
  24729. */
  24730. this.isQuadraticBezierCurve = true;
  24731. this.type = 'QuadraticBezierCurve';
  24732. /**
  24733. * The start point.
  24734. *
  24735. * @type {Vector2}
  24736. */
  24737. this.v0 = v0;
  24738. /**
  24739. * The control point.
  24740. *
  24741. * @type {Vector2}
  24742. */
  24743. this.v1 = v1;
  24744. /**
  24745. * The end point.
  24746. *
  24747. * @type {Vector2}
  24748. */
  24749. this.v2 = v2;
  24750. }
  24751. /**
  24752. * Returns a point on the curve.
  24753. *
  24754. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24755. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24756. * @return {Vector2} The position on the curve.
  24757. */
  24758. getPoint( t, optionalTarget = new Vector2() ) {
  24759. const point = optionalTarget;
  24760. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24761. point.set(
  24762. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24763. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24764. );
  24765. return point;
  24766. }
  24767. copy( source ) {
  24768. super.copy( source );
  24769. this.v0.copy( source.v0 );
  24770. this.v1.copy( source.v1 );
  24771. this.v2.copy( source.v2 );
  24772. return this;
  24773. }
  24774. toJSON() {
  24775. const data = super.toJSON();
  24776. data.v0 = this.v0.toArray();
  24777. data.v1 = this.v1.toArray();
  24778. data.v2 = this.v2.toArray();
  24779. return data;
  24780. }
  24781. fromJSON( json ) {
  24782. super.fromJSON( json );
  24783. this.v0.fromArray( json.v0 );
  24784. this.v1.fromArray( json.v1 );
  24785. this.v2.fromArray( json.v2 );
  24786. return this;
  24787. }
  24788. }
  24789. /**
  24790. * A curve representing a 3D Quadratic Bezier curve.
  24791. *
  24792. * @augments Curve
  24793. */
  24794. class QuadraticBezierCurve3 extends Curve {
  24795. /**
  24796. * Constructs a new Quadratic Bezier curve.
  24797. *
  24798. * @param {Vector3} [v0] - The start point.
  24799. * @param {Vector3} [v1] - The control point.
  24800. * @param {Vector3} [v2] - The end point.
  24801. */
  24802. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24803. super();
  24804. /**
  24805. * This flag can be used for type testing.
  24806. *
  24807. * @type {boolean}
  24808. * @readonly
  24809. * @default true
  24810. */
  24811. this.isQuadraticBezierCurve3 = true;
  24812. this.type = 'QuadraticBezierCurve3';
  24813. /**
  24814. * The start point.
  24815. *
  24816. * @type {Vector3}
  24817. */
  24818. this.v0 = v0;
  24819. /**
  24820. * The control point.
  24821. *
  24822. * @type {Vector3}
  24823. */
  24824. this.v1 = v1;
  24825. /**
  24826. * The end point.
  24827. *
  24828. * @type {Vector3}
  24829. */
  24830. this.v2 = v2;
  24831. }
  24832. /**
  24833. * Returns a point on the curve.
  24834. *
  24835. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24836. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24837. * @return {Vector3} The position on the curve.
  24838. */
  24839. getPoint( t, optionalTarget = new Vector3() ) {
  24840. const point = optionalTarget;
  24841. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24842. point.set(
  24843. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24844. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24845. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24846. );
  24847. return point;
  24848. }
  24849. copy( source ) {
  24850. super.copy( source );
  24851. this.v0.copy( source.v0 );
  24852. this.v1.copy( source.v1 );
  24853. this.v2.copy( source.v2 );
  24854. return this;
  24855. }
  24856. toJSON() {
  24857. const data = super.toJSON();
  24858. data.v0 = this.v0.toArray();
  24859. data.v1 = this.v1.toArray();
  24860. data.v2 = this.v2.toArray();
  24861. return data;
  24862. }
  24863. fromJSON( json ) {
  24864. super.fromJSON( json );
  24865. this.v0.fromArray( json.v0 );
  24866. this.v1.fromArray( json.v1 );
  24867. this.v2.fromArray( json.v2 );
  24868. return this;
  24869. }
  24870. }
  24871. /**
  24872. * A curve representing a 2D spline curve.
  24873. *
  24874. * ```js
  24875. * // Create a sine-like wave
  24876. * const curve = new THREE.SplineCurve( [
  24877. * new THREE.Vector2( -10, 0 ),
  24878. * new THREE.Vector2( -5, 5 ),
  24879. * new THREE.Vector2( 0, 0 ),
  24880. * new THREE.Vector2( 5, -5 ),
  24881. * new THREE.Vector2( 10, 0 )
  24882. * ] );
  24883. *
  24884. * const points = curve.getPoints( 50 );
  24885. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24886. *
  24887. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24888. *
  24889. * // Create the final object to add to the scene
  24890. * const splineObject = new THREE.Line( geometry, material );
  24891. * ```
  24892. *
  24893. * @augments Curve
  24894. */
  24895. class SplineCurve extends Curve {
  24896. /**
  24897. * Constructs a new 2D spline curve.
  24898. *
  24899. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24900. */
  24901. constructor( points = [] ) {
  24902. super();
  24903. /**
  24904. * This flag can be used for type testing.
  24905. *
  24906. * @type {boolean}
  24907. * @readonly
  24908. * @default true
  24909. */
  24910. this.isSplineCurve = true;
  24911. this.type = 'SplineCurve';
  24912. /**
  24913. * An array of 2D points defining the curve.
  24914. *
  24915. * @type {Array<Vector2>}
  24916. */
  24917. this.points = points;
  24918. }
  24919. /**
  24920. * Returns a point on the curve.
  24921. *
  24922. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24923. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24924. * @return {Vector2} The position on the curve.
  24925. */
  24926. getPoint( t, optionalTarget = new Vector2() ) {
  24927. const point = optionalTarget;
  24928. const points = this.points;
  24929. const p = ( points.length - 1 ) * t;
  24930. const intPoint = Math.floor( p );
  24931. const weight = p - intPoint;
  24932. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24933. const p1 = points[ intPoint ];
  24934. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24935. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24936. point.set(
  24937. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24938. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24939. );
  24940. return point;
  24941. }
  24942. copy( source ) {
  24943. super.copy( source );
  24944. this.points = [];
  24945. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24946. const point = source.points[ i ];
  24947. this.points.push( point.clone() );
  24948. }
  24949. return this;
  24950. }
  24951. toJSON() {
  24952. const data = super.toJSON();
  24953. data.points = [];
  24954. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24955. const point = this.points[ i ];
  24956. data.points.push( point.toArray() );
  24957. }
  24958. return data;
  24959. }
  24960. fromJSON( json ) {
  24961. super.fromJSON( json );
  24962. this.points = [];
  24963. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24964. const point = json.points[ i ];
  24965. this.points.push( new Vector2().fromArray( point ) );
  24966. }
  24967. return this;
  24968. }
  24969. }
  24970. var Curves = /*#__PURE__*/Object.freeze({
  24971. __proto__: null,
  24972. ArcCurve: ArcCurve,
  24973. CatmullRomCurve3: CatmullRomCurve3,
  24974. CubicBezierCurve: CubicBezierCurve,
  24975. CubicBezierCurve3: CubicBezierCurve3,
  24976. EllipseCurve: EllipseCurve,
  24977. LineCurve: LineCurve,
  24978. LineCurve3: LineCurve3,
  24979. QuadraticBezierCurve: QuadraticBezierCurve,
  24980. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24981. SplineCurve: SplineCurve
  24982. });
  24983. /**
  24984. * A base class extending {@link Curve}. `CurvePath` is simply an
  24985. * array of connected curves, but retains the API of a curve.
  24986. *
  24987. * @augments Curve
  24988. */
  24989. class CurvePath extends Curve {
  24990. /**
  24991. * Constructs a new curve path.
  24992. */
  24993. constructor() {
  24994. super();
  24995. this.type = 'CurvePath';
  24996. /**
  24997. * An array of curves defining the
  24998. * path.
  24999. *
  25000. * @type {Array<Curve>}
  25001. */
  25002. this.curves = [];
  25003. /**
  25004. * Whether the path should automatically be closed
  25005. * by a line curve.
  25006. *
  25007. * @type {boolean}
  25008. * @default false
  25009. */
  25010. this.autoClose = false;
  25011. }
  25012. /**
  25013. * Adds a curve to this curve path.
  25014. *
  25015. * @param {Curve} curve - The curve to add.
  25016. */
  25017. add( curve ) {
  25018. this.curves.push( curve );
  25019. }
  25020. /**
  25021. * Adds a line curve to close the path.
  25022. *
  25023. * @return {CurvePath} A reference to this curve path.
  25024. */
  25025. closePath() {
  25026. // Add a line curve if start and end of lines are not connected
  25027. const startPoint = this.curves[ 0 ].getPoint( 0 );
  25028. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  25029. if ( ! startPoint.equals( endPoint ) ) {
  25030. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  25031. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  25032. }
  25033. return this;
  25034. }
  25035. /**
  25036. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  25037. * for the given interpolation factor.
  25038. *
  25039. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  25040. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  25041. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  25042. */
  25043. getPoint( t, optionalTarget ) {
  25044. // To get accurate point with reference to
  25045. // entire path distance at time t,
  25046. // following has to be done:
  25047. // 1. Length of each sub path have to be known
  25048. // 2. Locate and identify type of curve
  25049. // 3. Get t for the curve
  25050. // 4. Return curve.getPointAt(t')
  25051. const d = t * this.getLength();
  25052. const curveLengths = this.getCurveLengths();
  25053. let i = 0;
  25054. // To think about boundaries points.
  25055. while ( i < curveLengths.length ) {
  25056. if ( curveLengths[ i ] >= d ) {
  25057. const diff = curveLengths[ i ] - d;
  25058. const curve = this.curves[ i ];
  25059. const segmentLength = curve.getLength();
  25060. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  25061. return curve.getPointAt( u, optionalTarget );
  25062. }
  25063. i ++;
  25064. }
  25065. return null;
  25066. // loop where sum != 0, sum > d , sum+1 <d
  25067. }
  25068. getLength() {
  25069. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  25070. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  25071. // getPoint() depends on getLength
  25072. const lens = this.getCurveLengths();
  25073. return lens[ lens.length - 1 ];
  25074. }
  25075. updateArcLengths() {
  25076. // cacheLengths must be recalculated.
  25077. this.needsUpdate = true;
  25078. this.cacheLengths = null;
  25079. this.getCurveLengths();
  25080. }
  25081. /**
  25082. * Returns list of cumulative curve lengths of the defined curves.
  25083. *
  25084. * @return {Array<number>} The curve lengths.
  25085. */
  25086. getCurveLengths() {
  25087. // Compute lengths and cache them
  25088. // We cannot overwrite getLengths() because UtoT mapping uses it.
  25089. // We use cache values if curves and cache array are same length
  25090. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  25091. return this.cacheLengths;
  25092. }
  25093. // Get length of sub-curve
  25094. // Push sums into cached array
  25095. const lengths = [];
  25096. let sums = 0;
  25097. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  25098. sums += this.curves[ i ].getLength();
  25099. lengths.push( sums );
  25100. }
  25101. this.cacheLengths = lengths;
  25102. return lengths;
  25103. }
  25104. getSpacedPoints( divisions = 40 ) {
  25105. const points = [];
  25106. for ( let i = 0; i <= divisions; i ++ ) {
  25107. points.push( this.getPoint( i / divisions ) );
  25108. }
  25109. if ( this.autoClose ) {
  25110. points.push( points[ 0 ] );
  25111. }
  25112. return points;
  25113. }
  25114. getPoints( divisions = 12 ) {
  25115. const points = [];
  25116. let last;
  25117. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  25118. const curve = curves[ i ];
  25119. const resolution = curve.isEllipseCurve ? divisions * 2
  25120. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  25121. : curve.isSplineCurve ? divisions * curve.points.length
  25122. : divisions;
  25123. const pts = curve.getPoints( resolution );
  25124. for ( let j = 0; j < pts.length; j ++ ) {
  25125. const point = pts[ j ];
  25126. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  25127. points.push( point );
  25128. last = point;
  25129. }
  25130. }
  25131. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  25132. points.push( points[ 0 ] );
  25133. }
  25134. return points;
  25135. }
  25136. copy( source ) {
  25137. super.copy( source );
  25138. this.curves = [];
  25139. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  25140. const curve = source.curves[ i ];
  25141. this.curves.push( curve.clone() );
  25142. }
  25143. this.autoClose = source.autoClose;
  25144. return this;
  25145. }
  25146. toJSON() {
  25147. const data = super.toJSON();
  25148. data.autoClose = this.autoClose;
  25149. data.curves = [];
  25150. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  25151. const curve = this.curves[ i ];
  25152. data.curves.push( curve.toJSON() );
  25153. }
  25154. return data;
  25155. }
  25156. fromJSON( json ) {
  25157. super.fromJSON( json );
  25158. this.autoClose = json.autoClose;
  25159. this.curves = [];
  25160. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  25161. const curve = json.curves[ i ];
  25162. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  25163. }
  25164. return this;
  25165. }
  25166. }
  25167. /**
  25168. * A 2D path representation. The class provides methods for creating paths
  25169. * and contours of 2D shapes similar to the 2D Canvas API.
  25170. *
  25171. * ```js
  25172. * const path = new THREE.Path();
  25173. *
  25174. * path.lineTo( 0, 0.8 );
  25175. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  25176. * path.lineTo( 1, 1 );
  25177. *
  25178. * const points = path.getPoints();
  25179. *
  25180. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  25181. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  25182. *
  25183. * const line = new THREE.Line( geometry, material );
  25184. * scene.add( line );
  25185. * ```
  25186. *
  25187. * @augments CurvePath
  25188. */
  25189. class Path extends CurvePath {
  25190. /**
  25191. * Constructs a new path.
  25192. *
  25193. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  25194. */
  25195. constructor( points ) {
  25196. super();
  25197. this.type = 'Path';
  25198. /**
  25199. * The current offset of the path. Any new curve added will start here.
  25200. *
  25201. * @type {Vector2}
  25202. */
  25203. this.currentPoint = new Vector2();
  25204. if ( points ) {
  25205. this.setFromPoints( points );
  25206. }
  25207. }
  25208. /**
  25209. * Creates a path from the given list of points. The points are added
  25210. * to the path as instances of {@link LineCurve}.
  25211. *
  25212. * @param {Array<Vector2>} points - An array of 2D points.
  25213. * @return {Path} A reference to this path.
  25214. */
  25215. setFromPoints( points ) {
  25216. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  25217. for ( let i = 1, l = points.length; i < l; i ++ ) {
  25218. this.lineTo( points[ i ].x, points[ i ].y );
  25219. }
  25220. return this;
  25221. }
  25222. /**
  25223. * Moves {@link Path#currentPoint} to the given point.
  25224. *
  25225. * @param {number} x - The x coordinate.
  25226. * @param {number} y - The y coordinate.
  25227. * @return {Path} A reference to this path.
  25228. */
  25229. moveTo( x, y ) {
  25230. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25231. return this;
  25232. }
  25233. /**
  25234. * Adds an instance of {@link LineCurve} to the path by connecting
  25235. * the current point with the given one.
  25236. *
  25237. * @param {number} x - The x coordinate of the end point.
  25238. * @param {number} y - The y coordinate of the end point.
  25239. * @return {Path} A reference to this path.
  25240. */
  25241. lineTo( x, y ) {
  25242. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25243. this.curves.push( curve );
  25244. this.currentPoint.set( x, y );
  25245. return this;
  25246. }
  25247. /**
  25248. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  25249. * the current point with the given one.
  25250. *
  25251. * @param {number} aCPx - The x coordinate of the control point.
  25252. * @param {number} aCPy - The y coordinate of the control point.
  25253. * @param {number} aX - The x coordinate of the end point.
  25254. * @param {number} aY - The y coordinate of the end point.
  25255. * @return {Path} A reference to this path.
  25256. */
  25257. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  25258. const curve = new QuadraticBezierCurve(
  25259. this.currentPoint.clone(),
  25260. new Vector2( aCPx, aCPy ),
  25261. new Vector2( aX, aY )
  25262. );
  25263. this.curves.push( curve );
  25264. this.currentPoint.set( aX, aY );
  25265. return this;
  25266. }
  25267. /**
  25268. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  25269. * the current point with the given one.
  25270. *
  25271. * @param {number} aCP1x - The x coordinate of the first control point.
  25272. * @param {number} aCP1y - The y coordinate of the first control point.
  25273. * @param {number} aCP2x - The x coordinate of the second control point.
  25274. * @param {number} aCP2y - The y coordinate of the second control point.
  25275. * @param {number} aX - The x coordinate of the end point.
  25276. * @param {number} aY - The y coordinate of the end point.
  25277. * @return {Path} A reference to this path.
  25278. */
  25279. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25280. const curve = new CubicBezierCurve(
  25281. this.currentPoint.clone(),
  25282. new Vector2( aCP1x, aCP1y ),
  25283. new Vector2( aCP2x, aCP2y ),
  25284. new Vector2( aX, aY )
  25285. );
  25286. this.curves.push( curve );
  25287. this.currentPoint.set( aX, aY );
  25288. return this;
  25289. }
  25290. /**
  25291. * Adds an instance of {@link SplineCurve} to the path by connecting
  25292. * the current point with the given list of points.
  25293. *
  25294. * @param {Array<Vector2>} pts - An array of points in 2D space.
  25295. * @return {Path} A reference to this path.
  25296. */
  25297. splineThru( pts ) {
  25298. const npts = [ this.currentPoint.clone() ].concat( pts );
  25299. const curve = new SplineCurve( npts );
  25300. this.curves.push( curve );
  25301. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25302. return this;
  25303. }
  25304. /**
  25305. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  25306. * to the current point.
  25307. *
  25308. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  25309. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  25310. * @param {number} [aRadius=1] - The radius of the arc.
  25311. * @param {number} [aStartAngle=0] - The start angle in radians.
  25312. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25313. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25314. * @return {Path} A reference to this path.
  25315. */
  25316. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25317. const x0 = this.currentPoint.x;
  25318. const y0 = this.currentPoint.y;
  25319. this.absarc( aX + x0, aY + y0, aRadius,
  25320. aStartAngle, aEndAngle, aClockwise );
  25321. return this;
  25322. }
  25323. /**
  25324. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  25325. *
  25326. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  25327. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  25328. * @param {number} [aRadius=1] - The radius of the arc.
  25329. * @param {number} [aStartAngle=0] - The start angle in radians.
  25330. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25331. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25332. * @return {Path} A reference to this path.
  25333. */
  25334. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25335. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25336. return this;
  25337. }
  25338. /**
  25339. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  25340. * to the current point
  25341. *
  25342. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  25343. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  25344. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25345. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25346. * @param {number} [aStartAngle=0] - The start angle in radians.
  25347. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25348. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25349. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25350. * @return {Path} A reference to this path.
  25351. */
  25352. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25353. const x0 = this.currentPoint.x;
  25354. const y0 = this.currentPoint.y;
  25355. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25356. return this;
  25357. }
  25358. /**
  25359. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  25360. *
  25361. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  25362. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  25363. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25364. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25365. * @param {number} [aStartAngle=0] - The start angle in radians.
  25366. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25367. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25368. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25369. * @return {Path} A reference to this path.
  25370. */
  25371. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25372. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25373. if ( this.curves.length > 0 ) {
  25374. // if a previous curve is present, attempt to join
  25375. const firstPoint = curve.getPoint( 0 );
  25376. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25377. this.lineTo( firstPoint.x, firstPoint.y );
  25378. }
  25379. }
  25380. this.curves.push( curve );
  25381. const lastPoint = curve.getPoint( 1 );
  25382. this.currentPoint.copy( lastPoint );
  25383. return this;
  25384. }
  25385. copy( source ) {
  25386. super.copy( source );
  25387. this.currentPoint.copy( source.currentPoint );
  25388. return this;
  25389. }
  25390. toJSON() {
  25391. const data = super.toJSON();
  25392. data.currentPoint = this.currentPoint.toArray();
  25393. return data;
  25394. }
  25395. fromJSON( json ) {
  25396. super.fromJSON( json );
  25397. this.currentPoint.fromArray( json.currentPoint );
  25398. return this;
  25399. }
  25400. }
  25401. /**
  25402. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  25403. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  25404. * points, or to get triangulated faces.
  25405. *
  25406. * ```js
  25407. * const heartShape = new THREE.Shape();
  25408. *
  25409. * heartShape.moveTo( 25, 25 );
  25410. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  25411. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  25412. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  25413. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  25414. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  25415. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  25416. *
  25417. * const extrudeSettings = {
  25418. * depth: 8,
  25419. * bevelEnabled: true,
  25420. * bevelSegments: 2,
  25421. * steps: 2,
  25422. * bevelSize: 1,
  25423. * bevelThickness: 1
  25424. * };
  25425. *
  25426. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  25427. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  25428. * ```
  25429. *
  25430. * @augments Path
  25431. */
  25432. class Shape extends Path {
  25433. /**
  25434. * Constructs a new shape.
  25435. *
  25436. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25437. */
  25438. constructor( points ) {
  25439. super( points );
  25440. /**
  25441. * The UUID of the shape.
  25442. *
  25443. * @type {string}
  25444. * @readonly
  25445. */
  25446. this.uuid = generateUUID();
  25447. this.type = 'Shape';
  25448. /**
  25449. * Defines the holes in the shape. Hole definitions must use the
  25450. * opposite winding order (CW/CCW) than the outer shape.
  25451. *
  25452. * @type {Array<Path>}
  25453. * @readonly
  25454. */
  25455. this.holes = [];
  25456. }
  25457. /**
  25458. * Returns an array representing each contour of the holes
  25459. * as a list of 2D points.
  25460. *
  25461. * @param {number} divisions - The fineness of the result.
  25462. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25463. */
  25464. getPointsHoles( divisions ) {
  25465. const holesPts = [];
  25466. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25467. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25468. }
  25469. return holesPts;
  25470. }
  25471. // get points of shape and holes (keypoints based on segments parameter)
  25472. /**
  25473. * Returns an object that holds contour data for the shape and its holes as
  25474. * arrays of 2D points.
  25475. *
  25476. * @param {number} divisions - The fineness of the result.
  25477. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25478. */
  25479. extractPoints( divisions ) {
  25480. return {
  25481. shape: this.getPoints( divisions ),
  25482. holes: this.getPointsHoles( divisions )
  25483. };
  25484. }
  25485. copy( source ) {
  25486. super.copy( source );
  25487. this.holes = [];
  25488. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25489. const hole = source.holes[ i ];
  25490. this.holes.push( hole.clone() );
  25491. }
  25492. return this;
  25493. }
  25494. toJSON() {
  25495. const data = super.toJSON();
  25496. data.uuid = this.uuid;
  25497. data.holes = [];
  25498. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25499. const hole = this.holes[ i ];
  25500. data.holes.push( hole.toJSON() );
  25501. }
  25502. return data;
  25503. }
  25504. fromJSON( json ) {
  25505. super.fromJSON( json );
  25506. this.uuid = json.uuid;
  25507. this.holes = [];
  25508. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25509. const hole = json.holes[ i ];
  25510. this.holes.push( new Path().fromJSON( hole ) );
  25511. }
  25512. return this;
  25513. }
  25514. }
  25515. /* eslint-disable */
  25516. // copy of mapbox/earcut version 3.0.2
  25517. // https://github.com/mapbox/earcut/tree/v3.0.2
  25518. function earcut(data, holeIndices, dim = 2) {
  25519. const hasHoles = holeIndices && holeIndices.length;
  25520. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25521. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25522. const triangles = [];
  25523. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25524. let minX, minY, invSize;
  25525. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25526. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25527. if (data.length > 80 * dim) {
  25528. minX = data[0];
  25529. minY = data[1];
  25530. let maxX = minX;
  25531. let maxY = minY;
  25532. for (let i = dim; i < outerLen; i += dim) {
  25533. const x = data[i];
  25534. const y = data[i + 1];
  25535. if (x < minX) minX = x;
  25536. if (y < minY) minY = y;
  25537. if (x > maxX) maxX = x;
  25538. if (y > maxY) maxY = y;
  25539. }
  25540. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25541. invSize = Math.max(maxX - minX, maxY - minY);
  25542. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25543. }
  25544. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25545. return triangles;
  25546. }
  25547. // create a circular doubly linked list from polygon points in the specified winding order
  25548. function linkedList(data, start, end, dim, clockwise) {
  25549. let last;
  25550. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25551. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25552. } else {
  25553. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25554. }
  25555. if (last && equals(last, last.next)) {
  25556. removeNode(last);
  25557. last = last.next;
  25558. }
  25559. return last;
  25560. }
  25561. // eliminate colinear or duplicate points
  25562. function filterPoints(start, end) {
  25563. if (!start) return start;
  25564. if (!end) end = start;
  25565. let p = start,
  25566. again;
  25567. do {
  25568. again = false;
  25569. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25570. removeNode(p);
  25571. p = end = p.prev;
  25572. if (p === p.next) break;
  25573. again = true;
  25574. } else {
  25575. p = p.next;
  25576. }
  25577. } while (again || p !== end);
  25578. return end;
  25579. }
  25580. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25581. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25582. if (!ear) return;
  25583. // interlink polygon nodes in z-order
  25584. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25585. let stop = ear;
  25586. // iterate through ears, slicing them one by one
  25587. while (ear.prev !== ear.next) {
  25588. const prev = ear.prev;
  25589. const next = ear.next;
  25590. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25591. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25592. removeNode(ear);
  25593. // skipping the next vertex leads to less sliver triangles
  25594. ear = next.next;
  25595. stop = next.next;
  25596. continue;
  25597. }
  25598. ear = next;
  25599. // if we looped through the whole remaining polygon and can't find any more ears
  25600. if (ear === stop) {
  25601. // try filtering points and slicing again
  25602. if (!pass) {
  25603. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25604. // if this didn't work, try curing all small self-intersections locally
  25605. } else if (pass === 1) {
  25606. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25607. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25608. // as a last resort, try splitting the remaining polygon into two
  25609. } else if (pass === 2) {
  25610. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25611. }
  25612. break;
  25613. }
  25614. }
  25615. }
  25616. // check whether a polygon node forms a valid ear with adjacent nodes
  25617. function isEar(ear) {
  25618. const a = ear.prev,
  25619. b = ear,
  25620. c = ear.next;
  25621. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25622. // now make sure we don't have other points inside the potential ear
  25623. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25624. // triangle bbox
  25625. const x0 = Math.min(ax, bx, cx),
  25626. y0 = Math.min(ay, by, cy),
  25627. x1 = Math.max(ax, bx, cx),
  25628. y1 = Math.max(ay, by, cy);
  25629. let p = c.next;
  25630. while (p !== a) {
  25631. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25632. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25633. area(p.prev, p, p.next) >= 0) return false;
  25634. p = p.next;
  25635. }
  25636. return true;
  25637. }
  25638. function isEarHashed(ear, minX, minY, invSize) {
  25639. const a = ear.prev,
  25640. b = ear,
  25641. c = ear.next;
  25642. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25643. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25644. // triangle bbox
  25645. const x0 = Math.min(ax, bx, cx),
  25646. y0 = Math.min(ay, by, cy),
  25647. x1 = Math.max(ax, bx, cx),
  25648. y1 = Math.max(ay, by, cy);
  25649. // z-order range for the current triangle bbox;
  25650. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25651. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25652. let p = ear.prevZ,
  25653. n = ear.nextZ;
  25654. // look for points inside the triangle in both directions
  25655. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25656. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25657. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25658. p = p.prevZ;
  25659. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25660. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25661. n = n.nextZ;
  25662. }
  25663. // look for remaining points in decreasing z-order
  25664. while (p && p.z >= minZ) {
  25665. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25666. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25667. p = p.prevZ;
  25668. }
  25669. // look for remaining points in increasing z-order
  25670. while (n && n.z <= maxZ) {
  25671. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25672. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25673. n = n.nextZ;
  25674. }
  25675. return true;
  25676. }
  25677. // go through all polygon nodes and cure small local self-intersections
  25678. function cureLocalIntersections(start, triangles) {
  25679. let p = start;
  25680. do {
  25681. const a = p.prev,
  25682. b = p.next.next;
  25683. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25684. triangles.push(a.i, p.i, b.i);
  25685. // remove two nodes involved
  25686. removeNode(p);
  25687. removeNode(p.next);
  25688. p = start = b;
  25689. }
  25690. p = p.next;
  25691. } while (p !== start);
  25692. return filterPoints(p);
  25693. }
  25694. // try splitting polygon into two and triangulate them independently
  25695. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25696. // look for a valid diagonal that divides the polygon into two
  25697. let a = start;
  25698. do {
  25699. let b = a.next.next;
  25700. while (b !== a.prev) {
  25701. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25702. // split the polygon in two by the diagonal
  25703. let c = splitPolygon(a, b);
  25704. // filter colinear points around the cuts
  25705. a = filterPoints(a, a.next);
  25706. c = filterPoints(c, c.next);
  25707. // run earcut on each half
  25708. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25709. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25710. return;
  25711. }
  25712. b = b.next;
  25713. }
  25714. a = a.next;
  25715. } while (a !== start);
  25716. }
  25717. // link every hole into the outer loop, producing a single-ring polygon without holes
  25718. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25719. const queue = [];
  25720. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25721. const start = holeIndices[i] * dim;
  25722. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25723. const list = linkedList(data, start, end, dim, false);
  25724. if (list === list.next) list.steiner = true;
  25725. queue.push(getLeftmost(list));
  25726. }
  25727. queue.sort(compareXYSlope);
  25728. // process holes from left to right
  25729. for (let i = 0; i < queue.length; i++) {
  25730. outerNode = eliminateHole(queue[i], outerNode);
  25731. }
  25732. return outerNode;
  25733. }
  25734. function compareXYSlope(a, b) {
  25735. let result = a.x - b.x;
  25736. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25737. // the bridge to the outer shell is always the point that they meet at.
  25738. if (result === 0) {
  25739. result = a.y - b.y;
  25740. if (result === 0) {
  25741. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25742. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25743. result = aSlope - bSlope;
  25744. }
  25745. }
  25746. return result;
  25747. }
  25748. // find a bridge between vertices that connects hole with an outer ring and link it
  25749. function eliminateHole(hole, outerNode) {
  25750. const bridge = findHoleBridge(hole, outerNode);
  25751. if (!bridge) {
  25752. return outerNode;
  25753. }
  25754. const bridgeReverse = splitPolygon(bridge, hole);
  25755. // filter collinear points around the cuts
  25756. filterPoints(bridgeReverse, bridgeReverse.next);
  25757. return filterPoints(bridge, bridge.next);
  25758. }
  25759. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25760. function findHoleBridge(hole, outerNode) {
  25761. let p = outerNode;
  25762. const hx = hole.x;
  25763. const hy = hole.y;
  25764. let qx = -Infinity;
  25765. let m;
  25766. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25767. // segment's endpoint with lesser x will be potential connection point
  25768. // unless they intersect at a vertex, then choose the vertex
  25769. if (equals(hole, p)) return p;
  25770. do {
  25771. if (equals(hole, p.next)) return p.next;
  25772. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25773. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25774. if (x <= hx && x > qx) {
  25775. qx = x;
  25776. m = p.x < p.next.x ? p : p.next;
  25777. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25778. }
  25779. }
  25780. p = p.next;
  25781. } while (p !== outerNode);
  25782. if (!m) return null;
  25783. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25784. // if there are no points found, we have a valid connection;
  25785. // otherwise choose the point of the minimum angle with the ray as connection point
  25786. const stop = m;
  25787. const mx = m.x;
  25788. const my = m.y;
  25789. let tanMin = Infinity;
  25790. p = m;
  25791. do {
  25792. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25793. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25794. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25795. if (locallyInside(p, hole) &&
  25796. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25797. m = p;
  25798. tanMin = tan;
  25799. }
  25800. }
  25801. p = p.next;
  25802. } while (p !== stop);
  25803. return m;
  25804. }
  25805. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25806. function sectorContainsSector(m, p) {
  25807. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25808. }
  25809. // interlink polygon nodes in z-order
  25810. function indexCurve(start, minX, minY, invSize) {
  25811. let p = start;
  25812. do {
  25813. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25814. p.prevZ = p.prev;
  25815. p.nextZ = p.next;
  25816. p = p.next;
  25817. } while (p !== start);
  25818. p.prevZ.nextZ = null;
  25819. p.prevZ = null;
  25820. sortLinked(p);
  25821. }
  25822. // Simon Tatham's linked list merge sort algorithm
  25823. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25824. function sortLinked(list) {
  25825. let numMerges;
  25826. let inSize = 1;
  25827. do {
  25828. let p = list;
  25829. let e;
  25830. list = null;
  25831. let tail = null;
  25832. numMerges = 0;
  25833. while (p) {
  25834. numMerges++;
  25835. let q = p;
  25836. let pSize = 0;
  25837. for (let i = 0; i < inSize; i++) {
  25838. pSize++;
  25839. q = q.nextZ;
  25840. if (!q) break;
  25841. }
  25842. let qSize = inSize;
  25843. while (pSize > 0 || (qSize > 0 && q)) {
  25844. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25845. e = p;
  25846. p = p.nextZ;
  25847. pSize--;
  25848. } else {
  25849. e = q;
  25850. q = q.nextZ;
  25851. qSize--;
  25852. }
  25853. if (tail) tail.nextZ = e;
  25854. else list = e;
  25855. e.prevZ = tail;
  25856. tail = e;
  25857. }
  25858. p = q;
  25859. }
  25860. tail.nextZ = null;
  25861. inSize *= 2;
  25862. } while (numMerges > 1);
  25863. return list;
  25864. }
  25865. // z-order of a point given coords and inverse of the longer side of data bbox
  25866. function zOrder(x, y, minX, minY, invSize) {
  25867. // coords are transformed into non-negative 15-bit integer range
  25868. x = (x - minX) * invSize | 0;
  25869. y = (y - minY) * invSize | 0;
  25870. x = (x | (x << 8)) & 0x00FF00FF;
  25871. x = (x | (x << 4)) & 0x0F0F0F0F;
  25872. x = (x | (x << 2)) & 0x33333333;
  25873. x = (x | (x << 1)) & 0x55555555;
  25874. y = (y | (y << 8)) & 0x00FF00FF;
  25875. y = (y | (y << 4)) & 0x0F0F0F0F;
  25876. y = (y | (y << 2)) & 0x33333333;
  25877. y = (y | (y << 1)) & 0x55555555;
  25878. return x | (y << 1);
  25879. }
  25880. // find the leftmost node of a polygon ring
  25881. function getLeftmost(start) {
  25882. let p = start,
  25883. leftmost = start;
  25884. do {
  25885. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25886. p = p.next;
  25887. } while (p !== start);
  25888. return leftmost;
  25889. }
  25890. // check if a point lies within a convex triangle
  25891. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25892. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25893. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25894. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25895. }
  25896. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25897. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25898. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25899. }
  25900. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25901. function isValidDiagonal(a, b) {
  25902. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25903. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25904. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25905. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25906. }
  25907. // signed area of a triangle
  25908. function area(p, q, r) {
  25909. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25910. }
  25911. // check if two points are equal
  25912. function equals(p1, p2) {
  25913. return p1.x === p2.x && p1.y === p2.y;
  25914. }
  25915. // check if two segments intersect
  25916. function intersects(p1, q1, p2, q2) {
  25917. const o1 = sign(area(p1, q1, p2));
  25918. const o2 = sign(area(p1, q1, q2));
  25919. const o3 = sign(area(p2, q2, p1));
  25920. const o4 = sign(area(p2, q2, q1));
  25921. if (o1 !== o2 && o3 !== o4) return true; // general case
  25922. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25923. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25924. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25925. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25926. return false;
  25927. }
  25928. // for collinear points p, q, r, check if point q lies on segment pr
  25929. function onSegment(p, q, r) {
  25930. 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);
  25931. }
  25932. function sign(num) {
  25933. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25934. }
  25935. // check if a polygon diagonal intersects any polygon segments
  25936. function intersectsPolygon(a, b) {
  25937. let p = a;
  25938. do {
  25939. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25940. intersects(p, p.next, a, b)) return true;
  25941. p = p.next;
  25942. } while (p !== a);
  25943. return false;
  25944. }
  25945. // check if a polygon diagonal is locally inside the polygon
  25946. function locallyInside(a, b) {
  25947. return area(a.prev, a, a.next) < 0 ?
  25948. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25949. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25950. }
  25951. // check if the middle point of a polygon diagonal is inside the polygon
  25952. function middleInside(a, b) {
  25953. let p = a;
  25954. let inside = false;
  25955. const px = (a.x + b.x) / 2;
  25956. const py = (a.y + b.y) / 2;
  25957. do {
  25958. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25959. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25960. inside = !inside;
  25961. p = p.next;
  25962. } while (p !== a);
  25963. return inside;
  25964. }
  25965. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25966. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25967. function splitPolygon(a, b) {
  25968. const a2 = createNode(a.i, a.x, a.y),
  25969. b2 = createNode(b.i, b.x, b.y),
  25970. an = a.next,
  25971. bp = b.prev;
  25972. a.next = b;
  25973. b.prev = a;
  25974. a2.next = an;
  25975. an.prev = a2;
  25976. b2.next = a2;
  25977. a2.prev = b2;
  25978. bp.next = b2;
  25979. b2.prev = bp;
  25980. return b2;
  25981. }
  25982. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25983. function insertNode(i, x, y, last) {
  25984. const p = createNode(i, x, y);
  25985. if (!last) {
  25986. p.prev = p;
  25987. p.next = p;
  25988. } else {
  25989. p.next = last.next;
  25990. p.prev = last;
  25991. last.next.prev = p;
  25992. last.next = p;
  25993. }
  25994. return p;
  25995. }
  25996. function removeNode(p) {
  25997. p.next.prev = p.prev;
  25998. p.prev.next = p.next;
  25999. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  26000. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  26001. }
  26002. function createNode(i, x, y) {
  26003. return {
  26004. i, // vertex index in coordinates array
  26005. x, y, // vertex coordinates
  26006. prev: null, // previous and next vertex nodes in a polygon ring
  26007. next: null,
  26008. z: 0, // z-order curve value
  26009. prevZ: null, // previous and next nodes in z-order
  26010. nextZ: null,
  26011. steiner: false // indicates whether this is a steiner point
  26012. };
  26013. }
  26014. function signedArea(data, start, end, dim) {
  26015. let sum = 0;
  26016. for (let i = start, j = end - dim; i < end; i += dim) {
  26017. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  26018. j = i;
  26019. }
  26020. return sum;
  26021. }
  26022. /**
  26023. * An implementation of the earcut polygon triangulation algorithm.
  26024. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  26025. *
  26026. * @see https://github.com/mapbox/earcut
  26027. */
  26028. class Earcut {
  26029. /**
  26030. * Triangulates the given shape definition by returning an array of triangles.
  26031. *
  26032. * @param {Array<number>} data - An array with 2D points.
  26033. * @param {Array<number>} holeIndices - An array with indices defining holes.
  26034. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  26035. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  26036. * representing vertex indices.
  26037. */
  26038. static triangulate( data, holeIndices, dim = 2 ) {
  26039. return earcut( data, holeIndices, dim );
  26040. }
  26041. }
  26042. /**
  26043. * A class containing utility functions for shapes.
  26044. *
  26045. * @hideconstructor
  26046. */
  26047. class ShapeUtils {
  26048. /**
  26049. * Calculate area of a ( 2D ) contour polygon.
  26050. *
  26051. * @param {Array<Vector2>} contour - An array of 2D points.
  26052. * @return {number} The area.
  26053. */
  26054. static area( contour ) {
  26055. const n = contour.length;
  26056. let a = 0.0;
  26057. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  26058. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  26059. }
  26060. return a * 0.5;
  26061. }
  26062. /**
  26063. * Returns `true` if the given contour uses a clockwise winding order.
  26064. *
  26065. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  26066. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  26067. */
  26068. static isClockWise( pts ) {
  26069. return ShapeUtils.area( pts ) < 0;
  26070. }
  26071. /**
  26072. * Triangulates the given shape definition.
  26073. *
  26074. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  26075. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  26076. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  26077. */
  26078. static triangulateShape( contour, holes ) {
  26079. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  26080. const holeIndices = []; // array of hole indices
  26081. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  26082. removeDupEndPts( contour );
  26083. addContour( vertices, contour );
  26084. //
  26085. let holeIndex = contour.length;
  26086. holes.forEach( removeDupEndPts );
  26087. for ( let i = 0; i < holes.length; i ++ ) {
  26088. holeIndices.push( holeIndex );
  26089. holeIndex += holes[ i ].length;
  26090. addContour( vertices, holes[ i ] );
  26091. }
  26092. //
  26093. const triangles = Earcut.triangulate( vertices, holeIndices );
  26094. //
  26095. for ( let i = 0; i < triangles.length; i += 3 ) {
  26096. faces.push( triangles.slice( i, i + 3 ) );
  26097. }
  26098. return faces;
  26099. }
  26100. }
  26101. function removeDupEndPts( points ) {
  26102. const l = points.length;
  26103. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  26104. points.pop();
  26105. }
  26106. }
  26107. function addContour( vertices, contour ) {
  26108. for ( let i = 0; i < contour.length; i ++ ) {
  26109. vertices.push( contour[ i ].x );
  26110. vertices.push( contour[ i ].y );
  26111. }
  26112. }
  26113. /**
  26114. * Creates extruded geometry from a path shape.
  26115. *
  26116. * ```js
  26117. * const length = 12, width = 8;
  26118. *
  26119. * const shape = new THREE.Shape();
  26120. * shape.moveTo( 0,0 );
  26121. * shape.lineTo( 0, width );
  26122. * shape.lineTo( length, width );
  26123. * shape.lineTo( length, 0 );
  26124. * shape.lineTo( 0, 0 );
  26125. *
  26126. * const geometry = new THREE.ExtrudeGeometry( shape );
  26127. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  26128. * const mesh = new THREE.Mesh( geometry, material ) ;
  26129. * scene.add( mesh );
  26130. * ```
  26131. *
  26132. * @augments BufferGeometry
  26133. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  26134. */
  26135. class ExtrudeGeometry extends BufferGeometry {
  26136. /**
  26137. * Constructs a new extrude geometry.
  26138. *
  26139. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26140. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  26141. */
  26142. 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 = {} ) {
  26143. super();
  26144. this.type = 'ExtrudeGeometry';
  26145. /**
  26146. * Holds the constructor parameters that have been
  26147. * used to generate the geometry. Any modification
  26148. * after instantiation does not change the geometry.
  26149. *
  26150. * @type {Object}
  26151. */
  26152. this.parameters = {
  26153. shapes: shapes,
  26154. options: options
  26155. };
  26156. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  26157. const scope = this;
  26158. const verticesArray = [];
  26159. const uvArray = [];
  26160. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26161. const shape = shapes[ i ];
  26162. addShape( shape );
  26163. }
  26164. // build geometry
  26165. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  26166. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  26167. this.computeVertexNormals();
  26168. // functions
  26169. function addShape( shape ) {
  26170. const placeholder = [];
  26171. // options
  26172. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  26173. const steps = options.steps !== undefined ? options.steps : 1;
  26174. const depth = options.depth !== undefined ? options.depth : 1;
  26175. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  26176. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  26177. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  26178. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  26179. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  26180. const extrudePath = options.extrudePath;
  26181. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  26182. //
  26183. let extrudePts, extrudeByPath = false;
  26184. let splineTube, binormal, normal, position2;
  26185. if ( extrudePath ) {
  26186. extrudePts = extrudePath.getSpacedPoints( steps );
  26187. extrudeByPath = true;
  26188. bevelEnabled = false; // bevels not supported for path extrusion
  26189. // SETUP TNB variables
  26190. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  26191. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  26192. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  26193. binormal = new Vector3();
  26194. normal = new Vector3();
  26195. position2 = new Vector3();
  26196. }
  26197. // Safeguards if bevels are not enabled
  26198. if ( ! bevelEnabled ) {
  26199. bevelSegments = 0;
  26200. bevelThickness = 0;
  26201. bevelSize = 0;
  26202. bevelOffset = 0;
  26203. }
  26204. // Variables initialization
  26205. const shapePoints = shape.extractPoints( curveSegments );
  26206. let vertices = shapePoints.shape;
  26207. const holes = shapePoints.holes;
  26208. const reverse = ! ShapeUtils.isClockWise( vertices );
  26209. if ( reverse ) {
  26210. vertices = vertices.reverse();
  26211. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  26212. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26213. const ahole = holes[ h ];
  26214. if ( ShapeUtils.isClockWise( ahole ) ) {
  26215. holes[ h ] = ahole.reverse();
  26216. }
  26217. }
  26218. }
  26219. /**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.
  26220. * @param {Array<Vector2>} points
  26221. */
  26222. function mergeOverlappingPoints( points ) {
  26223. const THRESHOLD = 1e-10;
  26224. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  26225. let prevPos = points[ 0 ];
  26226. for ( let i = 1; i <= points.length; i ++ ) {
  26227. const currentIndex = i % points.length;
  26228. const currentPos = points[ currentIndex ];
  26229. const dx = currentPos.x - prevPos.x;
  26230. const dy = currentPos.y - prevPos.y;
  26231. const distSq = dx * dx + dy * dy;
  26232. const scalingFactorSqrt = Math.max(
  26233. Math.abs( currentPos.x ),
  26234. Math.abs( currentPos.y ),
  26235. Math.abs( prevPos.x ),
  26236. Math.abs( prevPos.y )
  26237. );
  26238. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  26239. if ( distSq <= thresholdSqScaled ) {
  26240. points.splice( currentIndex, 1 );
  26241. i --;
  26242. continue;
  26243. }
  26244. prevPos = currentPos;
  26245. }
  26246. }
  26247. mergeOverlappingPoints( vertices );
  26248. holes.forEach( mergeOverlappingPoints );
  26249. const numHoles = holes.length;
  26250. /* Vertices */
  26251. const contour = vertices; // vertices has all points but contour has only points of circumference
  26252. for ( let h = 0; h < numHoles; h ++ ) {
  26253. const ahole = holes[ h ];
  26254. vertices = vertices.concat( ahole );
  26255. }
  26256. function scalePt2( pt, vec, size ) {
  26257. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  26258. return pt.clone().addScaledVector( vec, size );
  26259. }
  26260. const vlen = vertices.length;
  26261. // Find directions for point movement
  26262. function getBevelVec( inPt, inPrev, inNext ) {
  26263. // computes for inPt the corresponding point inPt' on a new contour
  26264. // shifted by 1 unit (length of normalized vector) to the left
  26265. // if we walk along contour clockwise, this new contour is outside the old one
  26266. //
  26267. // inPt' is the intersection of the two lines parallel to the two
  26268. // adjacent edges of inPt at a distance of 1 unit on the left side.
  26269. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  26270. // good reading for geometry algorithms (here: line-line intersection)
  26271. // http://geomalgorithms.com/a05-_intersect-1.html
  26272. const v_prev_x = inPt.x - inPrev.x,
  26273. v_prev_y = inPt.y - inPrev.y;
  26274. const v_next_x = inNext.x - inPt.x,
  26275. v_next_y = inNext.y - inPt.y;
  26276. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  26277. // check for collinear edges
  26278. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26279. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  26280. // not collinear
  26281. // length of vectors for normalizing
  26282. const v_prev_len = Math.sqrt( v_prev_lensq );
  26283. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  26284. // shift adjacent points by unit vectors to the left
  26285. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  26286. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  26287. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  26288. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  26289. // scaling factor for v_prev to intersection point
  26290. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  26291. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  26292. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26293. // vector from inPt to intersection point
  26294. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  26295. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  26296. // Don't normalize!, otherwise sharp corners become ugly
  26297. // but prevent crazy spikes
  26298. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  26299. if ( v_trans_lensq <= 2 ) {
  26300. return new Vector2( v_trans_x, v_trans_y );
  26301. } else {
  26302. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  26303. }
  26304. } else {
  26305. // handle special case of collinear edges
  26306. let direction_eq = false; // assumes: opposite
  26307. if ( v_prev_x > Number.EPSILON ) {
  26308. if ( v_next_x > Number.EPSILON ) {
  26309. direction_eq = true;
  26310. }
  26311. } else {
  26312. if ( v_prev_x < - Number.EPSILON ) {
  26313. if ( v_next_x < - Number.EPSILON ) {
  26314. direction_eq = true;
  26315. }
  26316. } else {
  26317. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  26318. direction_eq = true;
  26319. }
  26320. }
  26321. }
  26322. if ( direction_eq ) {
  26323. // log("Warning: lines are a straight sequence");
  26324. v_trans_x = - v_prev_y;
  26325. v_trans_y = v_prev_x;
  26326. shrink_by = Math.sqrt( v_prev_lensq );
  26327. } else {
  26328. // log("Warning: lines are a straight spike");
  26329. v_trans_x = v_prev_x;
  26330. v_trans_y = v_prev_y;
  26331. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  26332. }
  26333. }
  26334. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  26335. }
  26336. const contourMovements = [];
  26337. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26338. if ( j === il ) j = 0;
  26339. if ( k === il ) k = 0;
  26340. // (j)---(i)---(k)
  26341. // log('i,j,k', i, j , k)
  26342. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  26343. }
  26344. const holesMovements = [];
  26345. let oneHoleMovements, verticesMovements = contourMovements.concat();
  26346. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26347. const ahole = holes[ h ];
  26348. oneHoleMovements = [];
  26349. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26350. if ( j === il ) j = 0;
  26351. if ( k === il ) k = 0;
  26352. // (j)---(i)---(k)
  26353. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  26354. }
  26355. holesMovements.push( oneHoleMovements );
  26356. verticesMovements = verticesMovements.concat( oneHoleMovements );
  26357. }
  26358. let faces;
  26359. if ( bevelSegments === 0 ) {
  26360. faces = ShapeUtils.triangulateShape( contour, holes );
  26361. } else {
  26362. const contractedContourVertices = [];
  26363. const expandedHoleVertices = [];
  26364. // Loop bevelSegments, 1 for the front, 1 for the back
  26365. for ( let b = 0; b < bevelSegments; b ++ ) {
  26366. //for ( b = bevelSegments; b > 0; b -- ) {
  26367. const t = b / bevelSegments;
  26368. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26369. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26370. // contract shape
  26371. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26372. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26373. v( vert.x, vert.y, - z );
  26374. if ( t === 0 ) contractedContourVertices.push( vert );
  26375. }
  26376. // expand holes
  26377. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26378. const ahole = holes[ h ];
  26379. oneHoleMovements = holesMovements[ h ];
  26380. const oneHoleVertices = [];
  26381. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26382. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26383. v( vert.x, vert.y, - z );
  26384. if ( t === 0 ) oneHoleVertices.push( vert );
  26385. }
  26386. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  26387. }
  26388. }
  26389. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  26390. }
  26391. const flen = faces.length;
  26392. const bs = bevelSize + bevelOffset;
  26393. // Back facing vertices
  26394. for ( let i = 0; i < vlen; i ++ ) {
  26395. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26396. if ( ! extrudeByPath ) {
  26397. v( vert.x, vert.y, 0 );
  26398. } else {
  26399. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  26400. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  26401. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  26402. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  26403. v( position2.x, position2.y, position2.z );
  26404. }
  26405. }
  26406. // Add stepped vertices...
  26407. // Including front facing vertices
  26408. for ( let s = 1; s <= steps; s ++ ) {
  26409. for ( let i = 0; i < vlen; i ++ ) {
  26410. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26411. if ( ! extrudeByPath ) {
  26412. v( vert.x, vert.y, depth / steps * s );
  26413. } else {
  26414. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  26415. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  26416. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  26417. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  26418. v( position2.x, position2.y, position2.z );
  26419. }
  26420. }
  26421. }
  26422. // Add bevel segments planes
  26423. //for ( b = 1; b <= bevelSegments; b ++ ) {
  26424. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  26425. const t = b / bevelSegments;
  26426. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26427. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26428. // contract shape
  26429. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26430. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26431. v( vert.x, vert.y, depth + z );
  26432. }
  26433. // expand holes
  26434. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26435. const ahole = holes[ h ];
  26436. oneHoleMovements = holesMovements[ h ];
  26437. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26438. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26439. if ( ! extrudeByPath ) {
  26440. v( vert.x, vert.y, depth + z );
  26441. } else {
  26442. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  26443. }
  26444. }
  26445. }
  26446. }
  26447. /* Faces */
  26448. // Top and bottom faces
  26449. buildLidFaces();
  26450. // Sides faces
  26451. buildSideFaces();
  26452. ///// Internal functions
  26453. function buildLidFaces() {
  26454. const start = verticesArray.length / 3;
  26455. if ( bevelEnabled ) {
  26456. let layer = 0; // steps + 1
  26457. let offset = vlen * layer;
  26458. // Bottom faces
  26459. for ( let i = 0; i < flen; i ++ ) {
  26460. const face = faces[ i ];
  26461. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26462. }
  26463. layer = steps + bevelSegments * 2;
  26464. offset = vlen * layer;
  26465. // Top faces
  26466. for ( let i = 0; i < flen; i ++ ) {
  26467. const face = faces[ i ];
  26468. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26469. }
  26470. } else {
  26471. // Bottom faces
  26472. for ( let i = 0; i < flen; i ++ ) {
  26473. const face = faces[ i ];
  26474. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26475. }
  26476. // Top faces
  26477. for ( let i = 0; i < flen; i ++ ) {
  26478. const face = faces[ i ];
  26479. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26480. }
  26481. }
  26482. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26483. }
  26484. // Create faces for the z-sides of the shape
  26485. function buildSideFaces() {
  26486. const start = verticesArray.length / 3;
  26487. let layeroffset = 0;
  26488. sidewalls( contour, layeroffset );
  26489. layeroffset += contour.length;
  26490. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26491. const ahole = holes[ h ];
  26492. sidewalls( ahole, layeroffset );
  26493. //, true
  26494. layeroffset += ahole.length;
  26495. }
  26496. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26497. }
  26498. function sidewalls( contour, layeroffset ) {
  26499. let i = contour.length;
  26500. while ( -- i >= 0 ) {
  26501. const j = i;
  26502. let k = i - 1;
  26503. if ( k < 0 ) k = contour.length - 1;
  26504. //log('b', i,j, i-1, k,vertices.length);
  26505. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26506. const slen1 = vlen * s;
  26507. const slen2 = vlen * ( s + 1 );
  26508. const a = layeroffset + j + slen1,
  26509. b = layeroffset + k + slen1,
  26510. c = layeroffset + k + slen2,
  26511. d = layeroffset + j + slen2;
  26512. f4( a, b, c, d );
  26513. }
  26514. }
  26515. }
  26516. function v( x, y, z ) {
  26517. placeholder.push( x );
  26518. placeholder.push( y );
  26519. placeholder.push( z );
  26520. }
  26521. function f3( a, b, c ) {
  26522. addVertex( a );
  26523. addVertex( b );
  26524. addVertex( c );
  26525. const nextIndex = verticesArray.length / 3;
  26526. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26527. addUV( uvs[ 0 ] );
  26528. addUV( uvs[ 1 ] );
  26529. addUV( uvs[ 2 ] );
  26530. }
  26531. function f4( a, b, c, d ) {
  26532. addVertex( a );
  26533. addVertex( b );
  26534. addVertex( d );
  26535. addVertex( b );
  26536. addVertex( c );
  26537. addVertex( d );
  26538. const nextIndex = verticesArray.length / 3;
  26539. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26540. addUV( uvs[ 0 ] );
  26541. addUV( uvs[ 1 ] );
  26542. addUV( uvs[ 3 ] );
  26543. addUV( uvs[ 1 ] );
  26544. addUV( uvs[ 2 ] );
  26545. addUV( uvs[ 3 ] );
  26546. }
  26547. function addVertex( index ) {
  26548. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26549. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26550. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26551. }
  26552. function addUV( vector2 ) {
  26553. uvArray.push( vector2.x );
  26554. uvArray.push( vector2.y );
  26555. }
  26556. }
  26557. }
  26558. copy( source ) {
  26559. super.copy( source );
  26560. this.parameters = Object.assign( {}, source.parameters );
  26561. return this;
  26562. }
  26563. toJSON() {
  26564. const data = super.toJSON();
  26565. const shapes = this.parameters.shapes;
  26566. const options = this.parameters.options;
  26567. return toJSON$1( shapes, options, data );
  26568. }
  26569. /**
  26570. * Factory method for creating an instance of this class from the given
  26571. * JSON object.
  26572. *
  26573. * @param {Object} data - A JSON object representing the serialized geometry.
  26574. * @param {Array<Shape>} shapes - An array of shapes.
  26575. * @return {ExtrudeGeometry} A new instance.
  26576. */
  26577. static fromJSON( data, shapes ) {
  26578. const geometryShapes = [];
  26579. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26580. const shape = shapes[ data.shapes[ j ] ];
  26581. geometryShapes.push( shape );
  26582. }
  26583. const extrudePath = data.options.extrudePath;
  26584. if ( extrudePath !== undefined ) {
  26585. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26586. }
  26587. return new ExtrudeGeometry( geometryShapes, data.options );
  26588. }
  26589. }
  26590. const WorldUVGenerator = {
  26591. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26592. const a_x = vertices[ indexA * 3 ];
  26593. const a_y = vertices[ indexA * 3 + 1 ];
  26594. const b_x = vertices[ indexB * 3 ];
  26595. const b_y = vertices[ indexB * 3 + 1 ];
  26596. const c_x = vertices[ indexC * 3 ];
  26597. const c_y = vertices[ indexC * 3 + 1 ];
  26598. return [
  26599. new Vector2( a_x, a_y ),
  26600. new Vector2( b_x, b_y ),
  26601. new Vector2( c_x, c_y )
  26602. ];
  26603. },
  26604. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26605. const a_x = vertices[ indexA * 3 ];
  26606. const a_y = vertices[ indexA * 3 + 1 ];
  26607. const a_z = vertices[ indexA * 3 + 2 ];
  26608. const b_x = vertices[ indexB * 3 ];
  26609. const b_y = vertices[ indexB * 3 + 1 ];
  26610. const b_z = vertices[ indexB * 3 + 2 ];
  26611. const c_x = vertices[ indexC * 3 ];
  26612. const c_y = vertices[ indexC * 3 + 1 ];
  26613. const c_z = vertices[ indexC * 3 + 2 ];
  26614. const d_x = vertices[ indexD * 3 ];
  26615. const d_y = vertices[ indexD * 3 + 1 ];
  26616. const d_z = vertices[ indexD * 3 + 2 ];
  26617. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26618. return [
  26619. new Vector2( a_x, 1 - a_z ),
  26620. new Vector2( b_x, 1 - b_z ),
  26621. new Vector2( c_x, 1 - c_z ),
  26622. new Vector2( d_x, 1 - d_z )
  26623. ];
  26624. } else {
  26625. return [
  26626. new Vector2( a_y, 1 - a_z ),
  26627. new Vector2( b_y, 1 - b_z ),
  26628. new Vector2( c_y, 1 - c_z ),
  26629. new Vector2( d_y, 1 - d_z )
  26630. ];
  26631. }
  26632. }
  26633. };
  26634. function toJSON$1( shapes, options, data ) {
  26635. data.shapes = [];
  26636. if ( Array.isArray( shapes ) ) {
  26637. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26638. const shape = shapes[ i ];
  26639. data.shapes.push( shape.uuid );
  26640. }
  26641. } else {
  26642. data.shapes.push( shapes.uuid );
  26643. }
  26644. data.options = Object.assign( {}, options );
  26645. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26646. return data;
  26647. }
  26648. /**
  26649. * A geometry class for representing an icosahedron.
  26650. *
  26651. * ```js
  26652. * const geometry = new THREE.IcosahedronGeometry();
  26653. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26654. * const icosahedron = new THREE.Mesh( geometry, material );
  26655. * scene.add( icosahedron );
  26656. * ```
  26657. *
  26658. * @augments PolyhedronGeometry
  26659. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  26660. */
  26661. class IcosahedronGeometry extends PolyhedronGeometry {
  26662. /**
  26663. * Constructs a new icosahedron geometry.
  26664. *
  26665. * @param {number} [radius=1] - Radius of the icosahedron.
  26666. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26667. */
  26668. constructor( radius = 1, detail = 0 ) {
  26669. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26670. const vertices = [
  26671. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26672. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26673. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26674. ];
  26675. const indices = [
  26676. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26677. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26678. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26679. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26680. ];
  26681. super( vertices, indices, radius, detail );
  26682. this.type = 'IcosahedronGeometry';
  26683. /**
  26684. * Holds the constructor parameters that have been
  26685. * used to generate the geometry. Any modification
  26686. * after instantiation does not change the geometry.
  26687. *
  26688. * @type {Object}
  26689. */
  26690. this.parameters = {
  26691. radius: radius,
  26692. detail: detail
  26693. };
  26694. }
  26695. /**
  26696. * Factory method for creating an instance of this class from the given
  26697. * JSON object.
  26698. *
  26699. * @param {Object} data - A JSON object representing the serialized geometry.
  26700. * @return {IcosahedronGeometry} A new instance.
  26701. */
  26702. static fromJSON( data ) {
  26703. return new IcosahedronGeometry( data.radius, data.detail );
  26704. }
  26705. }
  26706. /**
  26707. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26708. *
  26709. * ```js
  26710. * const points = [];
  26711. * for ( let i = 0; i < 10; i ++ ) {
  26712. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26713. * }
  26714. * const geometry = new THREE.LatheGeometry( points );
  26715. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26716. * const lathe = new THREE.Mesh( geometry, material );
  26717. * scene.add( lathe );
  26718. * ```
  26719. *
  26720. * @augments BufferGeometry
  26721. * @demo scenes/geometry-browser.html#LatheGeometry
  26722. */
  26723. class LatheGeometry extends BufferGeometry {
  26724. /**
  26725. * Constructs a new lathe geometry.
  26726. *
  26727. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26728. * must be greater than zero.
  26729. * @param {number} [segments=12] - The number of circumference segments to generate.
  26730. * @param {number} [phiStart=0] - The starting angle in radians.
  26731. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26732. * closed lathe, less than 2PI is a portion.
  26733. */
  26734. 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 ) {
  26735. super();
  26736. this.type = 'LatheGeometry';
  26737. /**
  26738. * Holds the constructor parameters that have been
  26739. * used to generate the geometry. Any modification
  26740. * after instantiation does not change the geometry.
  26741. *
  26742. * @type {Object}
  26743. */
  26744. this.parameters = {
  26745. points: points,
  26746. segments: segments,
  26747. phiStart: phiStart,
  26748. phiLength: phiLength
  26749. };
  26750. segments = Math.floor( segments );
  26751. // clamp phiLength so it's in range of [ 0, 2PI ]
  26752. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26753. // buffers
  26754. const indices = [];
  26755. const vertices = [];
  26756. const uvs = [];
  26757. const initNormals = [];
  26758. const normals = [];
  26759. // helper variables
  26760. const inverseSegments = 1.0 / segments;
  26761. const vertex = new Vector3();
  26762. const uv = new Vector2();
  26763. const normal = new Vector3();
  26764. const curNormal = new Vector3();
  26765. const prevNormal = new Vector3();
  26766. let dx = 0;
  26767. let dy = 0;
  26768. // pre-compute normals for initial "meridian"
  26769. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26770. switch ( j ) {
  26771. case 0: // special handling for 1st vertex on path
  26772. dx = points[ j + 1 ].x - points[ j ].x;
  26773. dy = points[ j + 1 ].y - points[ j ].y;
  26774. normal.x = dy * 1.0;
  26775. normal.y = - dx;
  26776. normal.z = dy * 0.0;
  26777. prevNormal.copy( normal );
  26778. normal.normalize();
  26779. initNormals.push( normal.x, normal.y, normal.z );
  26780. break;
  26781. case ( points.length - 1 ): // special handling for last Vertex on path
  26782. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26783. break;
  26784. default: // default handling for all vertices in between
  26785. dx = points[ j + 1 ].x - points[ j ].x;
  26786. dy = points[ j + 1 ].y - points[ j ].y;
  26787. normal.x = dy * 1.0;
  26788. normal.y = - dx;
  26789. normal.z = dy * 0.0;
  26790. curNormal.copy( normal );
  26791. normal.x += prevNormal.x;
  26792. normal.y += prevNormal.y;
  26793. normal.z += prevNormal.z;
  26794. normal.normalize();
  26795. initNormals.push( normal.x, normal.y, normal.z );
  26796. prevNormal.copy( curNormal );
  26797. }
  26798. }
  26799. // generate vertices, uvs and normals
  26800. for ( let i = 0; i <= segments; i ++ ) {
  26801. const phi = phiStart + i * inverseSegments * phiLength;
  26802. const sin = Math.sin( phi );
  26803. const cos = Math.cos( phi );
  26804. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26805. // vertex
  26806. vertex.x = points[ j ].x * sin;
  26807. vertex.y = points[ j ].y;
  26808. vertex.z = points[ j ].x * cos;
  26809. vertices.push( vertex.x, vertex.y, vertex.z );
  26810. // uv
  26811. uv.x = i / segments;
  26812. uv.y = j / ( points.length - 1 );
  26813. uvs.push( uv.x, uv.y );
  26814. // normal
  26815. const x = initNormals[ 3 * j + 0 ] * sin;
  26816. const y = initNormals[ 3 * j + 1 ];
  26817. const z = initNormals[ 3 * j + 0 ] * cos;
  26818. normals.push( x, y, z );
  26819. }
  26820. }
  26821. // indices
  26822. for ( let i = 0; i < segments; i ++ ) {
  26823. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26824. const base = j + i * points.length;
  26825. const a = base;
  26826. const b = base + points.length;
  26827. const c = base + points.length + 1;
  26828. const d = base + 1;
  26829. // faces
  26830. indices.push( a, b, d );
  26831. indices.push( c, d, b );
  26832. }
  26833. }
  26834. // build geometry
  26835. this.setIndex( indices );
  26836. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26837. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26838. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26839. }
  26840. copy( source ) {
  26841. super.copy( source );
  26842. this.parameters = Object.assign( {}, source.parameters );
  26843. return this;
  26844. }
  26845. /**
  26846. * Factory method for creating an instance of this class from the given
  26847. * JSON object.
  26848. *
  26849. * @param {Object} data - A JSON object representing the serialized geometry.
  26850. * @return {LatheGeometry} A new instance.
  26851. */
  26852. static fromJSON( data ) {
  26853. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26854. }
  26855. }
  26856. /**
  26857. * A geometry class for representing an octahedron.
  26858. *
  26859. * ```js
  26860. * const geometry = new THREE.OctahedronGeometry();
  26861. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26862. * const octahedron = new THREE.Mesh( geometry, material );
  26863. * scene.add( octahedron );
  26864. * ```
  26865. *
  26866. * @augments PolyhedronGeometry
  26867. * @demo scenes/geometry-browser.html#OctahedronGeometry
  26868. */
  26869. class OctahedronGeometry extends PolyhedronGeometry {
  26870. /**
  26871. * Constructs a new octahedron geometry.
  26872. *
  26873. * @param {number} [radius=1] - Radius of the octahedron.
  26874. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26875. */
  26876. constructor( radius = 1, detail = 0 ) {
  26877. const vertices = [
  26878. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26879. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26880. ];
  26881. const indices = [
  26882. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26883. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26884. 1, 3, 4, 1, 4, 2
  26885. ];
  26886. super( vertices, indices, radius, detail );
  26887. this.type = 'OctahedronGeometry';
  26888. /**
  26889. * Holds the constructor parameters that have been
  26890. * used to generate the geometry. Any modification
  26891. * after instantiation does not change the geometry.
  26892. *
  26893. * @type {Object}
  26894. */
  26895. this.parameters = {
  26896. radius: radius,
  26897. detail: detail
  26898. };
  26899. }
  26900. /**
  26901. * Factory method for creating an instance of this class from the given
  26902. * JSON object.
  26903. *
  26904. * @param {Object} data - A JSON object representing the serialized geometry.
  26905. * @return {OctahedronGeometry} A new instance.
  26906. */
  26907. static fromJSON( data ) {
  26908. return new OctahedronGeometry( data.radius, data.detail );
  26909. }
  26910. }
  26911. /**
  26912. * A geometry class for representing a plane.
  26913. *
  26914. * ```js
  26915. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26916. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26917. * const plane = new THREE.Mesh( geometry, material );
  26918. * scene.add( plane );
  26919. * ```
  26920. *
  26921. * @augments BufferGeometry
  26922. * @demo scenes/geometry-browser.html#PlaneGeometry
  26923. */
  26924. class PlaneGeometry extends BufferGeometry {
  26925. /**
  26926. * Constructs a new plane geometry.
  26927. *
  26928. * @param {number} [width=1] - The width along the X axis.
  26929. * @param {number} [height=1] - The height along the Y axis
  26930. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26931. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26932. */
  26933. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26934. super();
  26935. this.type = 'PlaneGeometry';
  26936. /**
  26937. * Holds the constructor parameters that have been
  26938. * used to generate the geometry. Any modification
  26939. * after instantiation does not change the geometry.
  26940. *
  26941. * @type {Object}
  26942. */
  26943. this.parameters = {
  26944. width: width,
  26945. height: height,
  26946. widthSegments: widthSegments,
  26947. heightSegments: heightSegments
  26948. };
  26949. const width_half = width / 2;
  26950. const height_half = height / 2;
  26951. const gridX = Math.floor( widthSegments );
  26952. const gridY = Math.floor( heightSegments );
  26953. const gridX1 = gridX + 1;
  26954. const gridY1 = gridY + 1;
  26955. const segment_width = width / gridX;
  26956. const segment_height = height / gridY;
  26957. //
  26958. const indices = [];
  26959. const vertices = [];
  26960. const normals = [];
  26961. const uvs = [];
  26962. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26963. const y = iy * segment_height - height_half;
  26964. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26965. const x = ix * segment_width - width_half;
  26966. vertices.push( x, - y, 0 );
  26967. normals.push( 0, 0, 1 );
  26968. uvs.push( ix / gridX );
  26969. uvs.push( 1 - ( iy / gridY ) );
  26970. }
  26971. }
  26972. for ( let iy = 0; iy < gridY; iy ++ ) {
  26973. for ( let ix = 0; ix < gridX; ix ++ ) {
  26974. const a = ix + gridX1 * iy;
  26975. const b = ix + gridX1 * ( iy + 1 );
  26976. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26977. const d = ( ix + 1 ) + gridX1 * iy;
  26978. indices.push( a, b, d );
  26979. indices.push( b, c, d );
  26980. }
  26981. }
  26982. this.setIndex( indices );
  26983. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26984. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26985. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26986. }
  26987. copy( source ) {
  26988. super.copy( source );
  26989. this.parameters = Object.assign( {}, source.parameters );
  26990. return this;
  26991. }
  26992. /**
  26993. * Factory method for creating an instance of this class from the given
  26994. * JSON object.
  26995. *
  26996. * @param {Object} data - A JSON object representing the serialized geometry.
  26997. * @return {PlaneGeometry} A new instance.
  26998. */
  26999. static fromJSON( data ) {
  27000. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  27001. }
  27002. }
  27003. /**
  27004. * A class for generating a two-dimensional ring geometry.
  27005. *
  27006. * ```js
  27007. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  27008. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  27009. * const mesh = new THREE.Mesh( geometry, material );
  27010. * scene.add( mesh );
  27011. * ```
  27012. *
  27013. * @augments BufferGeometry
  27014. * @demo scenes/geometry-browser.html#RingGeometry
  27015. */
  27016. class RingGeometry extends BufferGeometry {
  27017. /**
  27018. * Constructs a new ring geometry.
  27019. *
  27020. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  27021. * @param {number} [outerRadius=1] - The outer radius of the ring.
  27022. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  27023. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  27024. * @param {number} [thetaStart=0] - Starting angle in radians.
  27025. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  27026. */
  27027. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  27028. super();
  27029. this.type = 'RingGeometry';
  27030. /**
  27031. * Holds the constructor parameters that have been
  27032. * used to generate the geometry. Any modification
  27033. * after instantiation does not change the geometry.
  27034. *
  27035. * @type {Object}
  27036. */
  27037. this.parameters = {
  27038. innerRadius: innerRadius,
  27039. outerRadius: outerRadius,
  27040. thetaSegments: thetaSegments,
  27041. phiSegments: phiSegments,
  27042. thetaStart: thetaStart,
  27043. thetaLength: thetaLength
  27044. };
  27045. thetaSegments = Math.max( 3, thetaSegments );
  27046. phiSegments = Math.max( 1, phiSegments );
  27047. // buffers
  27048. const indices = [];
  27049. const vertices = [];
  27050. const normals = [];
  27051. const uvs = [];
  27052. // some helper variables
  27053. let radius = innerRadius;
  27054. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  27055. const vertex = new Vector3();
  27056. const uv = new Vector2();
  27057. // generate vertices, normals and uvs
  27058. for ( let j = 0; j <= phiSegments; j ++ ) {
  27059. for ( let i = 0; i <= thetaSegments; i ++ ) {
  27060. // values are generate from the inside of the ring to the outside
  27061. const segment = thetaStart + i / thetaSegments * thetaLength;
  27062. // vertex
  27063. vertex.x = radius * Math.cos( segment );
  27064. vertex.y = radius * Math.sin( segment );
  27065. vertices.push( vertex.x, vertex.y, vertex.z );
  27066. // normal
  27067. normals.push( 0, 0, 1 );
  27068. // uv
  27069. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  27070. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  27071. uvs.push( uv.x, uv.y );
  27072. }
  27073. // increase the radius for next row of vertices
  27074. radius += radiusStep;
  27075. }
  27076. // indices
  27077. for ( let j = 0; j < phiSegments; j ++ ) {
  27078. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  27079. for ( let i = 0; i < thetaSegments; i ++ ) {
  27080. const segment = i + thetaSegmentLevel;
  27081. const a = segment;
  27082. const b = segment + thetaSegments + 1;
  27083. const c = segment + thetaSegments + 2;
  27084. const d = segment + 1;
  27085. // faces
  27086. indices.push( a, b, d );
  27087. indices.push( b, c, d );
  27088. }
  27089. }
  27090. // build geometry
  27091. this.setIndex( indices );
  27092. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27093. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27094. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27095. }
  27096. copy( source ) {
  27097. super.copy( source );
  27098. this.parameters = Object.assign( {}, source.parameters );
  27099. return this;
  27100. }
  27101. /**
  27102. * Factory method for creating an instance of this class from the given
  27103. * JSON object.
  27104. *
  27105. * @param {Object} data - A JSON object representing the serialized geometry.
  27106. * @return {RingGeometry} A new instance.
  27107. */
  27108. static fromJSON( data ) {
  27109. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  27110. }
  27111. }
  27112. /**
  27113. * Creates an one-sided polygonal geometry from one or more path shapes.
  27114. *
  27115. * ```js
  27116. * const arcShape = new THREE.Shape()
  27117. * .moveTo( 5, 1 )
  27118. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  27119. *
  27120. * const geometry = new THREE.ShapeGeometry( arcShape );
  27121. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  27122. * const mesh = new THREE.Mesh( geometry, material ) ;
  27123. * scene.add( mesh );
  27124. * ```
  27125. *
  27126. * @augments BufferGeometry
  27127. * @demo scenes/geometry-browser.html#ShapeGeometry
  27128. */
  27129. class ShapeGeometry extends BufferGeometry {
  27130. /**
  27131. * Constructs a new shape geometry.
  27132. *
  27133. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  27134. * @param {number} [curveSegments=12] - Number of segments per shape.
  27135. */
  27136. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  27137. super();
  27138. this.type = 'ShapeGeometry';
  27139. /**
  27140. * Holds the constructor parameters that have been
  27141. * used to generate the geometry. Any modification
  27142. * after instantiation does not change the geometry.
  27143. *
  27144. * @type {Object}
  27145. */
  27146. this.parameters = {
  27147. shapes: shapes,
  27148. curveSegments: curveSegments
  27149. };
  27150. // buffers
  27151. const indices = [];
  27152. const vertices = [];
  27153. const normals = [];
  27154. const uvs = [];
  27155. // helper variables
  27156. let groupStart = 0;
  27157. let groupCount = 0;
  27158. // allow single and array values for "shapes" parameter
  27159. if ( Array.isArray( shapes ) === false ) {
  27160. addShape( shapes );
  27161. } else {
  27162. for ( let i = 0; i < shapes.length; i ++ ) {
  27163. addShape( shapes[ i ] );
  27164. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  27165. groupStart += groupCount;
  27166. groupCount = 0;
  27167. }
  27168. }
  27169. // build geometry
  27170. this.setIndex( indices );
  27171. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27172. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27173. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27174. // helper functions
  27175. function addShape( shape ) {
  27176. const indexOffset = vertices.length / 3;
  27177. const points = shape.extractPoints( curveSegments );
  27178. let shapeVertices = points.shape;
  27179. const shapeHoles = points.holes;
  27180. // check direction of vertices
  27181. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  27182. shapeVertices = shapeVertices.reverse();
  27183. }
  27184. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27185. const shapeHole = shapeHoles[ i ];
  27186. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  27187. shapeHoles[ i ] = shapeHole.reverse();
  27188. }
  27189. }
  27190. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  27191. // join vertices of inner and outer paths to a single array
  27192. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27193. const shapeHole = shapeHoles[ i ];
  27194. shapeVertices = shapeVertices.concat( shapeHole );
  27195. }
  27196. // vertices, normals, uvs
  27197. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  27198. const vertex = shapeVertices[ i ];
  27199. vertices.push( vertex.x, vertex.y, 0 );
  27200. normals.push( 0, 0, 1 );
  27201. uvs.push( vertex.x, vertex.y ); // world uvs
  27202. }
  27203. // indices
  27204. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  27205. const face = faces[ i ];
  27206. const a = face[ 0 ] + indexOffset;
  27207. const b = face[ 1 ] + indexOffset;
  27208. const c = face[ 2 ] + indexOffset;
  27209. indices.push( a, b, c );
  27210. groupCount += 3;
  27211. }
  27212. }
  27213. }
  27214. copy( source ) {
  27215. super.copy( source );
  27216. this.parameters = Object.assign( {}, source.parameters );
  27217. return this;
  27218. }
  27219. toJSON() {
  27220. const data = super.toJSON();
  27221. const shapes = this.parameters.shapes;
  27222. return toJSON( shapes, data );
  27223. }
  27224. /**
  27225. * Factory method for creating an instance of this class from the given
  27226. * JSON object.
  27227. *
  27228. * @param {Object} data - A JSON object representing the serialized geometry.
  27229. * @param {Array<Shape>} shapes - An array of shapes.
  27230. * @return {ShapeGeometry} A new instance.
  27231. */
  27232. static fromJSON( data, shapes ) {
  27233. const geometryShapes = [];
  27234. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27235. const shape = shapes[ data.shapes[ j ] ];
  27236. geometryShapes.push( shape );
  27237. }
  27238. return new ShapeGeometry( geometryShapes, data.curveSegments );
  27239. }
  27240. }
  27241. function toJSON( shapes, data ) {
  27242. data.shapes = [];
  27243. if ( Array.isArray( shapes ) ) {
  27244. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  27245. const shape = shapes[ i ];
  27246. data.shapes.push( shape.uuid );
  27247. }
  27248. } else {
  27249. data.shapes.push( shapes.uuid );
  27250. }
  27251. return data;
  27252. }
  27253. /**
  27254. * A class for generating a sphere geometry.
  27255. *
  27256. * ```js
  27257. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  27258. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27259. * const sphere = new THREE.Mesh( geometry, material );
  27260. * scene.add( sphere );
  27261. * ```
  27262. *
  27263. * @augments BufferGeometry
  27264. * @demo scenes/geometry-browser.html#SphereGeometry
  27265. */
  27266. class SphereGeometry extends BufferGeometry {
  27267. /**
  27268. * Constructs a new sphere geometry.
  27269. *
  27270. * @param {number} [radius=1] - The sphere radius.
  27271. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  27272. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  27273. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  27274. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  27275. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  27276. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  27277. */
  27278. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  27279. super();
  27280. this.type = 'SphereGeometry';
  27281. /**
  27282. * Holds the constructor parameters that have been
  27283. * used to generate the geometry. Any modification
  27284. * after instantiation does not change the geometry.
  27285. *
  27286. * @type {Object}
  27287. */
  27288. this.parameters = {
  27289. radius: radius,
  27290. widthSegments: widthSegments,
  27291. heightSegments: heightSegments,
  27292. phiStart: phiStart,
  27293. phiLength: phiLength,
  27294. thetaStart: thetaStart,
  27295. thetaLength: thetaLength
  27296. };
  27297. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  27298. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  27299. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  27300. let index = 0;
  27301. const grid = [];
  27302. const vertex = new Vector3();
  27303. const normal = new Vector3();
  27304. // buffers
  27305. const indices = [];
  27306. const vertices = [];
  27307. const normals = [];
  27308. const uvs = [];
  27309. // generate vertices, normals and uvs
  27310. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  27311. const verticesRow = [];
  27312. const v = iy / heightSegments;
  27313. // special case for the poles
  27314. let uOffset = 0;
  27315. if ( iy === 0 && thetaStart === 0 ) {
  27316. uOffset = 0.5 / widthSegments;
  27317. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  27318. uOffset = -0.5 / widthSegments;
  27319. }
  27320. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  27321. const u = ix / widthSegments;
  27322. // vertex
  27323. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27324. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  27325. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27326. vertices.push( vertex.x, vertex.y, vertex.z );
  27327. // normal
  27328. normal.copy( vertex ).normalize();
  27329. normals.push( normal.x, normal.y, normal.z );
  27330. // uv
  27331. uvs.push( u + uOffset, 1 - v );
  27332. verticesRow.push( index ++ );
  27333. }
  27334. grid.push( verticesRow );
  27335. }
  27336. // indices
  27337. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  27338. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  27339. const a = grid[ iy ][ ix + 1 ];
  27340. const b = grid[ iy ][ ix ];
  27341. const c = grid[ iy + 1 ][ ix ];
  27342. const d = grid[ iy + 1 ][ ix + 1 ];
  27343. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  27344. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  27345. }
  27346. }
  27347. // build geometry
  27348. this.setIndex( indices );
  27349. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27350. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27351. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27352. }
  27353. copy( source ) {
  27354. super.copy( source );
  27355. this.parameters = Object.assign( {}, source.parameters );
  27356. return this;
  27357. }
  27358. /**
  27359. * Factory method for creating an instance of this class from the given
  27360. * JSON object.
  27361. *
  27362. * @param {Object} data - A JSON object representing the serialized geometry.
  27363. * @return {SphereGeometry} A new instance.
  27364. */
  27365. static fromJSON( data ) {
  27366. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  27367. }
  27368. }
  27369. /**
  27370. * A geometry class for representing an tetrahedron.
  27371. *
  27372. * ```js
  27373. * const geometry = new THREE.TetrahedronGeometry();
  27374. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27375. * const tetrahedron = new THREE.Mesh( geometry, material );
  27376. * scene.add( tetrahedron );
  27377. * ```
  27378. *
  27379. * @augments PolyhedronGeometry
  27380. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  27381. */
  27382. class TetrahedronGeometry extends PolyhedronGeometry {
  27383. /**
  27384. * Constructs a new tetrahedron geometry.
  27385. *
  27386. * @param {number} [radius=1] - Radius of the tetrahedron.
  27387. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  27388. */
  27389. constructor( radius = 1, detail = 0 ) {
  27390. const vertices = [
  27391. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  27392. ];
  27393. const indices = [
  27394. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  27395. ];
  27396. super( vertices, indices, radius, detail );
  27397. this.type = 'TetrahedronGeometry';
  27398. /**
  27399. * Holds the constructor parameters that have been
  27400. * used to generate the geometry. Any modification
  27401. * after instantiation does not change the geometry.
  27402. *
  27403. * @type {Object}
  27404. */
  27405. this.parameters = {
  27406. radius: radius,
  27407. detail: detail
  27408. };
  27409. }
  27410. /**
  27411. * Factory method for creating an instance of this class from the given
  27412. * JSON object.
  27413. *
  27414. * @param {Object} data - A JSON object representing the serialized geometry.
  27415. * @return {TetrahedronGeometry} A new instance.
  27416. */
  27417. static fromJSON( data ) {
  27418. return new TetrahedronGeometry( data.radius, data.detail );
  27419. }
  27420. }
  27421. /**
  27422. * A geometry class for representing an torus.
  27423. *
  27424. * ```js
  27425. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  27426. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27427. * const torus = new THREE.Mesh( geometry, material );
  27428. * scene.add( torus );
  27429. * ```
  27430. *
  27431. * @augments BufferGeometry
  27432. * @demo scenes/geometry-browser.html#TorusGeometry
  27433. */
  27434. class TorusGeometry extends BufferGeometry {
  27435. /**
  27436. * Constructs a new torus geometry.
  27437. *
  27438. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  27439. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  27440. * @param {number} [radialSegments=12] - The number of radial segments.
  27441. * @param {number} [tubularSegments=48] - The number of tubular segments.
  27442. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  27443. * @param {number} [thetaStart=0] - Start of the tubular sweep in radians.
  27444. * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians.
  27445. */
  27446. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  27447. super();
  27448. this.type = 'TorusGeometry';
  27449. /**
  27450. * Holds the constructor parameters that have been
  27451. * used to generate the geometry. Any modification
  27452. * after instantiation does not change the geometry.
  27453. *
  27454. * @type {Object}
  27455. */
  27456. this.parameters = {
  27457. radius: radius,
  27458. tube: tube,
  27459. radialSegments: radialSegments,
  27460. tubularSegments: tubularSegments,
  27461. arc: arc,
  27462. thetaStart: thetaStart,
  27463. thetaLength: thetaLength,
  27464. };
  27465. radialSegments = Math.floor( radialSegments );
  27466. tubularSegments = Math.floor( tubularSegments );
  27467. // buffers
  27468. const indices = [];
  27469. const vertices = [];
  27470. const normals = [];
  27471. const uvs = [];
  27472. // helper variables
  27473. const center = new Vector3();
  27474. const vertex = new Vector3();
  27475. const normal = new Vector3();
  27476. // generate vertices, normals and uvs
  27477. for ( let j = 0; j <= radialSegments; j ++ ) {
  27478. const v = thetaStart + ( j / radialSegments ) * thetaLength;
  27479. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27480. const u = i / tubularSegments * arc;
  27481. // vertex
  27482. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27483. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27484. vertex.z = tube * Math.sin( v );
  27485. vertices.push( vertex.x, vertex.y, vertex.z );
  27486. // normal
  27487. center.x = radius * Math.cos( u );
  27488. center.y = radius * Math.sin( u );
  27489. normal.subVectors( vertex, center ).normalize();
  27490. normals.push( normal.x, normal.y, normal.z );
  27491. // uv
  27492. uvs.push( i / tubularSegments );
  27493. uvs.push( j / radialSegments );
  27494. }
  27495. }
  27496. // generate indices
  27497. for ( let j = 1; j <= radialSegments; j ++ ) {
  27498. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27499. // indices
  27500. const a = ( tubularSegments + 1 ) * j + i - 1;
  27501. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27502. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27503. const d = ( tubularSegments + 1 ) * j + i;
  27504. // faces
  27505. indices.push( a, b, d );
  27506. indices.push( b, c, d );
  27507. }
  27508. }
  27509. // build geometry
  27510. this.setIndex( indices );
  27511. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27512. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27513. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27514. }
  27515. copy( source ) {
  27516. super.copy( source );
  27517. this.parameters = Object.assign( {}, source.parameters );
  27518. return this;
  27519. }
  27520. /**
  27521. * Factory method for creating an instance of this class from the given
  27522. * JSON object.
  27523. *
  27524. * @param {Object} data - A JSON object representing the serialized geometry.
  27525. * @return {TorusGeometry} A new instance.
  27526. */
  27527. static fromJSON( data ) {
  27528. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27529. }
  27530. }
  27531. /**
  27532. * Creates a torus knot, the particular shape of which is defined by a pair
  27533. * of coprime integers, p and q. If p and q are not coprime, the result will
  27534. * be a torus link.
  27535. *
  27536. * ```js
  27537. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27538. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27539. * const torusKnot = new THREE.Mesh( geometry, material );
  27540. * scene.add( torusKnot );
  27541. * ```
  27542. *
  27543. * @augments BufferGeometry
  27544. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  27545. */
  27546. class TorusKnotGeometry extends BufferGeometry {
  27547. /**
  27548. * Constructs a new torus knot geometry.
  27549. *
  27550. * @param {number} [radius=1] - Radius of the torus knot.
  27551. * @param {number} [tube=0.4] - Radius of the tube.
  27552. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27553. * @param {number} [radialSegments=8] - The number of radial segments.
  27554. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27555. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27556. */
  27557. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27558. super();
  27559. this.type = 'TorusKnotGeometry';
  27560. /**
  27561. * Holds the constructor parameters that have been
  27562. * used to generate the geometry. Any modification
  27563. * after instantiation does not change the geometry.
  27564. *
  27565. * @type {Object}
  27566. */
  27567. this.parameters = {
  27568. radius: radius,
  27569. tube: tube,
  27570. tubularSegments: tubularSegments,
  27571. radialSegments: radialSegments,
  27572. p: p,
  27573. q: q
  27574. };
  27575. tubularSegments = Math.floor( tubularSegments );
  27576. radialSegments = Math.floor( radialSegments );
  27577. // buffers
  27578. const indices = [];
  27579. const vertices = [];
  27580. const normals = [];
  27581. const uvs = [];
  27582. // helper variables
  27583. const vertex = new Vector3();
  27584. const normal = new Vector3();
  27585. const P1 = new Vector3();
  27586. const P2 = new Vector3();
  27587. const B = new Vector3();
  27588. const T = new Vector3();
  27589. const N = new Vector3();
  27590. // generate vertices, normals and uvs
  27591. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27592. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27593. const u = i / tubularSegments * p * Math.PI * 2;
  27594. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27595. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27596. calculatePositionOnCurve( u, p, q, radius, P1 );
  27597. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27598. // calculate orthonormal basis
  27599. T.subVectors( P2, P1 );
  27600. N.addVectors( P2, P1 );
  27601. B.crossVectors( T, N );
  27602. N.crossVectors( B, T );
  27603. // normalize B, N. T can be ignored, we don't use it
  27604. B.normalize();
  27605. N.normalize();
  27606. for ( let j = 0; j <= radialSegments; ++ j ) {
  27607. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27608. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27609. const v = j / radialSegments * Math.PI * 2;
  27610. const cx = - tube * Math.cos( v );
  27611. const cy = tube * Math.sin( v );
  27612. // now calculate the final vertex position.
  27613. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27614. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27615. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27616. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27617. vertices.push( vertex.x, vertex.y, vertex.z );
  27618. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27619. normal.subVectors( vertex, P1 ).normalize();
  27620. normals.push( normal.x, normal.y, normal.z );
  27621. // uv
  27622. uvs.push( i / tubularSegments );
  27623. uvs.push( j / radialSegments );
  27624. }
  27625. }
  27626. // generate indices
  27627. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27628. for ( let i = 1; i <= radialSegments; i ++ ) {
  27629. // indices
  27630. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27631. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27632. const c = ( radialSegments + 1 ) * j + i;
  27633. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27634. // faces
  27635. indices.push( a, b, d );
  27636. indices.push( b, c, d );
  27637. }
  27638. }
  27639. // build geometry
  27640. this.setIndex( indices );
  27641. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27642. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27643. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27644. // this function calculates the current position on the torus curve
  27645. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27646. const cu = Math.cos( u );
  27647. const su = Math.sin( u );
  27648. const quOverP = q / p * u;
  27649. const cs = Math.cos( quOverP );
  27650. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27651. position.y = radius * ( 2 + cs ) * su * 0.5;
  27652. position.z = radius * Math.sin( quOverP ) * 0.5;
  27653. }
  27654. }
  27655. copy( source ) {
  27656. super.copy( source );
  27657. this.parameters = Object.assign( {}, source.parameters );
  27658. return this;
  27659. }
  27660. /**
  27661. * Factory method for creating an instance of this class from the given
  27662. * JSON object.
  27663. *
  27664. * @param {Object} data - A JSON object representing the serialized geometry.
  27665. * @return {TorusKnotGeometry} A new instance.
  27666. */
  27667. static fromJSON( data ) {
  27668. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27669. }
  27670. }
  27671. /**
  27672. * Creates a tube that extrudes along a 3D curve.
  27673. *
  27674. * ```js
  27675. * class CustomSinCurve extends THREE.Curve {
  27676. *
  27677. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27678. *
  27679. * const tx = t * 3 - 1.5;
  27680. * const ty = Math.sin( 2 * Math.PI * t );
  27681. * const tz = 0;
  27682. *
  27683. * return optionalTarget.set( tx, ty, tz );
  27684. * }
  27685. *
  27686. * }
  27687. *
  27688. * const path = new CustomSinCurve( 10 );
  27689. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27690. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27691. * const mesh = new THREE.Mesh( geometry, material );
  27692. * scene.add( mesh );
  27693. * ```
  27694. *
  27695. * @augments BufferGeometry
  27696. * @demo scenes/geometry-browser.html#TubeGeometry
  27697. */
  27698. class TubeGeometry extends BufferGeometry {
  27699. /**
  27700. * Constructs a new tube geometry.
  27701. *
  27702. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27703. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27704. * @param {number} [radius=1] -The radius of the tube.
  27705. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27706. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27707. */
  27708. 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 ) {
  27709. super();
  27710. this.type = 'TubeGeometry';
  27711. /**
  27712. * Holds the constructor parameters that have been
  27713. * used to generate the geometry. Any modification
  27714. * after instantiation does not change the geometry.
  27715. *
  27716. * @type {Object}
  27717. */
  27718. this.parameters = {
  27719. path: path,
  27720. tubularSegments: tubularSegments,
  27721. radius: radius,
  27722. radialSegments: radialSegments,
  27723. closed: closed
  27724. };
  27725. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27726. // expose internals
  27727. this.tangents = frames.tangents;
  27728. this.normals = frames.normals;
  27729. this.binormals = frames.binormals;
  27730. // helper variables
  27731. const vertex = new Vector3();
  27732. const normal = new Vector3();
  27733. const uv = new Vector2();
  27734. let P = new Vector3();
  27735. // buffer
  27736. const vertices = [];
  27737. const normals = [];
  27738. const uvs = [];
  27739. const indices = [];
  27740. // create buffer data
  27741. generateBufferData();
  27742. // build geometry
  27743. this.setIndex( indices );
  27744. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27745. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27746. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27747. // functions
  27748. function generateBufferData() {
  27749. for ( let i = 0; i < tubularSegments; i ++ ) {
  27750. generateSegment( i );
  27751. }
  27752. // if the geometry is not closed, generate the last row of vertices and normals
  27753. // at the regular position on the given path
  27754. //
  27755. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27756. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27757. // uvs are generated in a separate function.
  27758. // this makes it easy compute correct values for closed geometries
  27759. generateUVs();
  27760. // finally create faces
  27761. generateIndices();
  27762. }
  27763. function generateSegment( i ) {
  27764. // we use getPointAt to sample evenly distributed points from the given path
  27765. P = path.getPointAt( i / tubularSegments, P );
  27766. // retrieve corresponding normal and binormal
  27767. const N = frames.normals[ i ];
  27768. const B = frames.binormals[ i ];
  27769. // generate normals and vertices for the current segment
  27770. for ( let j = 0; j <= radialSegments; j ++ ) {
  27771. const v = j / radialSegments * Math.PI * 2;
  27772. const sin = Math.sin( v );
  27773. const cos = - Math.cos( v );
  27774. // normal
  27775. normal.x = ( cos * N.x + sin * B.x );
  27776. normal.y = ( cos * N.y + sin * B.y );
  27777. normal.z = ( cos * N.z + sin * B.z );
  27778. normal.normalize();
  27779. normals.push( normal.x, normal.y, normal.z );
  27780. // vertex
  27781. vertex.x = P.x + radius * normal.x;
  27782. vertex.y = P.y + radius * normal.y;
  27783. vertex.z = P.z + radius * normal.z;
  27784. vertices.push( vertex.x, vertex.y, vertex.z );
  27785. }
  27786. }
  27787. function generateIndices() {
  27788. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27789. for ( let i = 1; i <= radialSegments; i ++ ) {
  27790. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27791. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27792. const c = ( radialSegments + 1 ) * j + i;
  27793. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27794. // faces
  27795. indices.push( a, b, d );
  27796. indices.push( b, c, d );
  27797. }
  27798. }
  27799. }
  27800. function generateUVs() {
  27801. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27802. for ( let j = 0; j <= radialSegments; j ++ ) {
  27803. uv.x = i / tubularSegments;
  27804. uv.y = j / radialSegments;
  27805. uvs.push( uv.x, uv.y );
  27806. }
  27807. }
  27808. }
  27809. }
  27810. copy( source ) {
  27811. super.copy( source );
  27812. this.parameters = Object.assign( {}, source.parameters );
  27813. return this;
  27814. }
  27815. toJSON() {
  27816. const data = super.toJSON();
  27817. data.path = this.parameters.path.toJSON();
  27818. return data;
  27819. }
  27820. /**
  27821. * Factory method for creating an instance of this class from the given
  27822. * JSON object.
  27823. *
  27824. * @param {Object} data - A JSON object representing the serialized geometry.
  27825. * @return {TubeGeometry} A new instance.
  27826. */
  27827. static fromJSON( data ) {
  27828. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27829. // User defined curves or instances of CurvePath will not be deserialized.
  27830. return new TubeGeometry(
  27831. new Curves[ data.path.type ]().fromJSON( data.path ),
  27832. data.tubularSegments,
  27833. data.radius,
  27834. data.radialSegments,
  27835. data.closed
  27836. );
  27837. }
  27838. }
  27839. /**
  27840. * Can be used as a helper object to visualize a geometry as a wireframe.
  27841. *
  27842. * ```js
  27843. * const geometry = new THREE.SphereGeometry();
  27844. *
  27845. * const wireframe = new THREE.WireframeGeometry( geometry );
  27846. *
  27847. * const line = new THREE.LineSegments( wireframe );
  27848. * line.material.depthWrite = false;
  27849. * line.material.opacity = 0.25;
  27850. * line.material.transparent = true;
  27851. *
  27852. * scene.add( line );
  27853. * ```
  27854. *
  27855. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27856. *
  27857. * @augments BufferGeometry
  27858. */
  27859. class WireframeGeometry extends BufferGeometry {
  27860. /**
  27861. * Constructs a new wireframe geometry.
  27862. *
  27863. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27864. */
  27865. constructor( geometry = null ) {
  27866. super();
  27867. this.type = 'WireframeGeometry';
  27868. /**
  27869. * Holds the constructor parameters that have been
  27870. * used to generate the geometry. Any modification
  27871. * after instantiation does not change the geometry.
  27872. *
  27873. * @type {Object}
  27874. */
  27875. this.parameters = {
  27876. geometry: geometry
  27877. };
  27878. if ( geometry !== null ) {
  27879. // buffer
  27880. const vertices = [];
  27881. const edges = new Set();
  27882. // helper variables
  27883. const start = new Vector3();
  27884. const end = new Vector3();
  27885. if ( geometry.index !== null ) {
  27886. // indexed BufferGeometry
  27887. const position = geometry.attributes.position;
  27888. const indices = geometry.index;
  27889. let groups = geometry.groups;
  27890. if ( groups.length === 0 ) {
  27891. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27892. }
  27893. // create a data structure that contains all edges without duplicates
  27894. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27895. const group = groups[ o ];
  27896. const groupStart = group.start;
  27897. const groupCount = group.count;
  27898. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27899. for ( let j = 0; j < 3; j ++ ) {
  27900. const index1 = indices.getX( i + j );
  27901. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27902. start.fromBufferAttribute( position, index1 );
  27903. end.fromBufferAttribute( position, index2 );
  27904. if ( isUniqueEdge( start, end, edges ) === true ) {
  27905. vertices.push( start.x, start.y, start.z );
  27906. vertices.push( end.x, end.y, end.z );
  27907. }
  27908. }
  27909. }
  27910. }
  27911. } else {
  27912. // non-indexed BufferGeometry
  27913. const position = geometry.attributes.position;
  27914. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27915. for ( let j = 0; j < 3; j ++ ) {
  27916. // three edges per triangle, an edge is represented as (index1, index2)
  27917. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27918. const index1 = 3 * i + j;
  27919. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27920. start.fromBufferAttribute( position, index1 );
  27921. end.fromBufferAttribute( position, index2 );
  27922. if ( isUniqueEdge( start, end, edges ) === true ) {
  27923. vertices.push( start.x, start.y, start.z );
  27924. vertices.push( end.x, end.y, end.z );
  27925. }
  27926. }
  27927. }
  27928. }
  27929. // build geometry
  27930. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27931. }
  27932. }
  27933. copy( source ) {
  27934. super.copy( source );
  27935. this.parameters = Object.assign( {}, source.parameters );
  27936. return this;
  27937. }
  27938. }
  27939. function isUniqueEdge( start, end, edges ) {
  27940. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27941. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27942. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27943. return false;
  27944. } else {
  27945. edges.add( hash1 );
  27946. edges.add( hash2 );
  27947. return true;
  27948. }
  27949. }
  27950. var Geometries = /*#__PURE__*/Object.freeze({
  27951. __proto__: null,
  27952. BoxGeometry: BoxGeometry,
  27953. CapsuleGeometry: CapsuleGeometry,
  27954. CircleGeometry: CircleGeometry,
  27955. ConeGeometry: ConeGeometry,
  27956. CylinderGeometry: CylinderGeometry,
  27957. DodecahedronGeometry: DodecahedronGeometry,
  27958. EdgesGeometry: EdgesGeometry,
  27959. ExtrudeGeometry: ExtrudeGeometry,
  27960. IcosahedronGeometry: IcosahedronGeometry,
  27961. LatheGeometry: LatheGeometry,
  27962. OctahedronGeometry: OctahedronGeometry,
  27963. PlaneGeometry: PlaneGeometry,
  27964. PolyhedronGeometry: PolyhedronGeometry,
  27965. RingGeometry: RingGeometry,
  27966. ShapeGeometry: ShapeGeometry,
  27967. SphereGeometry: SphereGeometry,
  27968. TetrahedronGeometry: TetrahedronGeometry,
  27969. TorusGeometry: TorusGeometry,
  27970. TorusKnotGeometry: TorusKnotGeometry,
  27971. TubeGeometry: TubeGeometry,
  27972. WireframeGeometry: WireframeGeometry
  27973. });
  27974. /**
  27975. * This material can receive shadows, but otherwise is completely transparent.
  27976. *
  27977. * ```js
  27978. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27979. * geometry.rotateX( - Math.PI / 2 );
  27980. *
  27981. * const material = new THREE.ShadowMaterial();
  27982. * material.opacity = 0.2;
  27983. *
  27984. * const plane = new THREE.Mesh( geometry, material );
  27985. * plane.position.y = -200;
  27986. * plane.receiveShadow = true;
  27987. * scene.add( plane );
  27988. * ```
  27989. *
  27990. * @augments Material
  27991. */
  27992. class ShadowMaterial extends Material {
  27993. /**
  27994. * Constructs a new shadow material.
  27995. *
  27996. * @param {Object} [parameters] - An object with one or more properties
  27997. * defining the material's appearance. Any property of the material
  27998. * (including any property from inherited materials) can be passed
  27999. * in here. Color values can be passed any type of value accepted
  28000. * by {@link Color#set}.
  28001. */
  28002. constructor( parameters ) {
  28003. super();
  28004. /**
  28005. * This flag can be used for type testing.
  28006. *
  28007. * @type {boolean}
  28008. * @readonly
  28009. * @default true
  28010. */
  28011. this.isShadowMaterial = true;
  28012. this.type = 'ShadowMaterial';
  28013. /**
  28014. * Color of the material.
  28015. *
  28016. * @type {Color}
  28017. * @default (0,0,0)
  28018. */
  28019. this.color = new Color( 0x000000 );
  28020. /**
  28021. * Overwritten since shadow materials are transparent
  28022. * by default.
  28023. *
  28024. * @type {boolean}
  28025. * @default true
  28026. */
  28027. this.transparent = true;
  28028. /**
  28029. * Whether the material is affected by fog or not.
  28030. *
  28031. * @type {boolean}
  28032. * @default true
  28033. */
  28034. this.fog = true;
  28035. this.setValues( parameters );
  28036. }
  28037. copy( source ) {
  28038. super.copy( source );
  28039. this.color.copy( source.color );
  28040. this.fog = source.fog;
  28041. return this;
  28042. }
  28043. }
  28044. /**
  28045. * This class works just like {@link ShaderMaterial}, except that definitions
  28046. * of built-in uniforms and attributes are not automatically prepended to the
  28047. * GLSL shader code.
  28048. *
  28049. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  28050. *
  28051. * @augments ShaderMaterial
  28052. */
  28053. class RawShaderMaterial extends ShaderMaterial {
  28054. /**
  28055. * Constructs a new raw shader material.
  28056. *
  28057. * @param {Object} [parameters] - An object with one or more properties
  28058. * defining the material's appearance. Any property of the material
  28059. * (including any property from inherited materials) can be passed
  28060. * in here. Color values can be passed any type of value accepted
  28061. * by {@link Color#set}.
  28062. */
  28063. constructor( parameters ) {
  28064. super( parameters );
  28065. /**
  28066. * This flag can be used for type testing.
  28067. *
  28068. * @type {boolean}
  28069. * @readonly
  28070. * @default true
  28071. */
  28072. this.isRawShaderMaterial = true;
  28073. this.type = 'RawShaderMaterial';
  28074. }
  28075. }
  28076. /**
  28077. * A standard physically based material, using Metallic-Roughness workflow.
  28078. *
  28079. * Physically based rendering (PBR) has recently become the standard in many
  28080. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  28081. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  28082. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  28083. *
  28084. * This approach differs from older approaches in that instead of using
  28085. * approximations for the way in which light interacts with a surface, a
  28086. * physically correct model is used. The idea is that, instead of tweaking
  28087. * materials to look good under specific lighting, a material can be created
  28088. * that will react 'correctly' under all lighting scenarios.
  28089. *
  28090. * In practice this gives a more accurate and realistic looking result than
  28091. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  28092. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  28093. * shading.
  28094. *
  28095. * Note that for best results you should always specify an environment map when using this material.
  28096. *
  28097. * For a non-technical introduction to the concept of PBR and how to set up a
  28098. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  28099. *
  28100. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  28101. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  28102. *
  28103. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  28104. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  28105. * (pdf), by Brent Burley.
  28106. *
  28107. * @augments Material
  28108. * @demo scenes/material-browser.html#MeshStandardMaterial
  28109. */
  28110. class MeshStandardMaterial extends Material {
  28111. /**
  28112. * Constructs a new mesh standard material.
  28113. *
  28114. * @param {Object} [parameters] - An object with one or more properties
  28115. * defining the material's appearance. Any property of the material
  28116. * (including any property from inherited materials) can be passed
  28117. * in here. Color values can be passed any type of value accepted
  28118. * by {@link Color#set}.
  28119. */
  28120. constructor( parameters ) {
  28121. super();
  28122. /**
  28123. * This flag can be used for type testing.
  28124. *
  28125. * @type {boolean}
  28126. * @readonly
  28127. * @default true
  28128. */
  28129. this.isMeshStandardMaterial = true;
  28130. this.type = 'MeshStandardMaterial';
  28131. this.defines = { 'STANDARD': '' };
  28132. /**
  28133. * Color of the material.
  28134. *
  28135. * @type {Color}
  28136. * @default (1,1,1)
  28137. */
  28138. this.color = new Color( 0xffffff ); // diffuse
  28139. /**
  28140. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  28141. * means fully diffuse. If `roughnessMap` is also provided,
  28142. * both values are multiplied.
  28143. *
  28144. * @type {number}
  28145. * @default 1
  28146. */
  28147. this.roughness = 1.0;
  28148. /**
  28149. * How much the material is like a metal. Non-metallic materials such as wood
  28150. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  28151. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  28152. * If `metalnessMap` is also provided, both values are multiplied.
  28153. *
  28154. * @type {number}
  28155. * @default 0
  28156. */
  28157. this.metalness = 0.0;
  28158. /**
  28159. * The color map. May optionally include an alpha channel, typically combined
  28160. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28161. * color is modulated by the diffuse `color`.
  28162. *
  28163. * @type {?Texture}
  28164. * @default null
  28165. */
  28166. this.map = null;
  28167. /**
  28168. * The light map. Requires a second set of UVs.
  28169. *
  28170. * @type {?Texture}
  28171. * @default null
  28172. */
  28173. this.lightMap = null;
  28174. /**
  28175. * Intensity of the baked light.
  28176. *
  28177. * @type {number}
  28178. * @default 1
  28179. */
  28180. this.lightMapIntensity = 1.0;
  28181. /**
  28182. * The red channel of this texture is used as the ambient occlusion map.
  28183. * Requires a second set of UVs.
  28184. *
  28185. * @type {?Texture}
  28186. * @default null
  28187. */
  28188. this.aoMap = null;
  28189. /**
  28190. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28191. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28192. * red channel is also `1`, ambient light is fully occluded on a surface.
  28193. *
  28194. * @type {number}
  28195. * @default 1
  28196. */
  28197. this.aoMapIntensity = 1.0;
  28198. /**
  28199. * Emissive (light) color of the material, essentially a solid color
  28200. * unaffected by other lighting.
  28201. *
  28202. * @type {Color}
  28203. * @default (0,0,0)
  28204. */
  28205. this.emissive = new Color( 0x000000 );
  28206. /**
  28207. * Intensity of the emissive light. Modulates the emissive color.
  28208. *
  28209. * @type {number}
  28210. * @default 1
  28211. */
  28212. this.emissiveIntensity = 1.0;
  28213. /**
  28214. * Set emissive (glow) map. The emissive map color is modulated by the
  28215. * emissive color and the emissive intensity. If you have an emissive map,
  28216. * be sure to set the emissive color to something other than black.
  28217. *
  28218. * @type {?Texture}
  28219. * @default null
  28220. */
  28221. this.emissiveMap = null;
  28222. /**
  28223. * The texture to create a bump map. The black and white values map to the
  28224. * perceived depth in relation to the lights. Bump doesn't actually affect
  28225. * the geometry of the object, only the lighting. If a normal map is defined
  28226. * this will be ignored.
  28227. *
  28228. * @type {?Texture}
  28229. * @default null
  28230. */
  28231. this.bumpMap = null;
  28232. /**
  28233. * How much the bump map affects the material. Typical range is `[0,1]`.
  28234. *
  28235. * @type {number}
  28236. * @default 1
  28237. */
  28238. this.bumpScale = 1;
  28239. /**
  28240. * The texture to create a normal map. The RGB values affect the surface
  28241. * normal for each pixel fragment and change the way the color is lit. Normal
  28242. * maps do not change the actual shape of the surface, only the lighting. In
  28243. * case the material has a normal map authored using the left handed
  28244. * convention, the `y` component of `normalScale` should be negated to compensate
  28245. * for the different handedness.
  28246. *
  28247. * @type {?Texture}
  28248. * @default null
  28249. */
  28250. this.normalMap = null;
  28251. /**
  28252. * The type of normal map.
  28253. *
  28254. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28255. * @default TangentSpaceNormalMap
  28256. */
  28257. this.normalMapType = TangentSpaceNormalMap;
  28258. /**
  28259. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28260. *
  28261. * @type {Vector2}
  28262. * @default (1,1)
  28263. */
  28264. this.normalScale = new Vector2( 1, 1 );
  28265. /**
  28266. * The displacement map affects the position of the mesh's vertices. Unlike
  28267. * other maps which only affect the light and shade of the material the
  28268. * displaced vertices can cast shadows, block other objects, and otherwise
  28269. * act as real geometry. The displacement texture is an image where the value
  28270. * of each pixel (white being the highest) is mapped against, and
  28271. * repositions, the vertices of the mesh.
  28272. *
  28273. * @type {?Texture}
  28274. * @default null
  28275. */
  28276. this.displacementMap = null;
  28277. /**
  28278. * How much the displacement map affects the mesh (where black is no
  28279. * displacement, and white is maximum displacement). Without a displacement
  28280. * map set, this value is not applied.
  28281. *
  28282. * @type {number}
  28283. * @default 0
  28284. */
  28285. this.displacementScale = 1;
  28286. /**
  28287. * The offset of the displacement map's values on the mesh's vertices.
  28288. * The bias is added to the scaled sample of the displacement map.
  28289. * Without a displacement map set, this value is not applied.
  28290. *
  28291. * @type {number}
  28292. * @default 0
  28293. */
  28294. this.displacementBias = 0;
  28295. /**
  28296. * The green channel of this texture is used to alter the roughness of the
  28297. * material.
  28298. *
  28299. * @type {?Texture}
  28300. * @default null
  28301. */
  28302. this.roughnessMap = null;
  28303. /**
  28304. * The blue channel of this texture is used to alter the metalness of the
  28305. * material.
  28306. *
  28307. * @type {?Texture}
  28308. * @default null
  28309. */
  28310. this.metalnessMap = null;
  28311. /**
  28312. * The alpha map is a grayscale texture that controls the opacity across the
  28313. * surface (black: fully transparent; white: fully opaque).
  28314. *
  28315. * Only the color of the texture is used, ignoring the alpha channel if one
  28316. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28317. * when sampling this texture due to the extra bit of precision provided for
  28318. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28319. * luminance/alpha textures will also still work as expected.
  28320. *
  28321. * @type {?Texture}
  28322. * @default null
  28323. */
  28324. this.alphaMap = null;
  28325. /**
  28326. * The environment map. To ensure a physically correct rendering, environment maps
  28327. * are internally pre-processed with {@link PMREMGenerator}.
  28328. *
  28329. * @type {?Texture}
  28330. * @default null
  28331. */
  28332. this.envMap = null;
  28333. /**
  28334. * The rotation of the environment map in radians.
  28335. *
  28336. * @type {Euler}
  28337. * @default (0,0,0)
  28338. */
  28339. this.envMapRotation = new Euler();
  28340. /**
  28341. * Scales the effect of the environment map by multiplying its color.
  28342. *
  28343. * @type {number}
  28344. * @default 1
  28345. */
  28346. this.envMapIntensity = 1.0;
  28347. /**
  28348. * Renders the geometry as a wireframe.
  28349. *
  28350. * @type {boolean}
  28351. * @default false
  28352. */
  28353. this.wireframe = false;
  28354. /**
  28355. * Controls the thickness of the wireframe.
  28356. *
  28357. * Can only be used with {@link SVGRenderer}.
  28358. *
  28359. * @type {number}
  28360. * @default 1
  28361. */
  28362. this.wireframeLinewidth = 1;
  28363. /**
  28364. * Defines appearance of wireframe ends.
  28365. *
  28366. * Can only be used with {@link SVGRenderer}.
  28367. *
  28368. * @type {('round'|'bevel'|'miter')}
  28369. * @default 'round'
  28370. */
  28371. this.wireframeLinecap = 'round';
  28372. /**
  28373. * Defines appearance of wireframe joints.
  28374. *
  28375. * Can only be used with {@link SVGRenderer}.
  28376. *
  28377. * @type {('round'|'bevel'|'miter')}
  28378. * @default 'round'
  28379. */
  28380. this.wireframeLinejoin = 'round';
  28381. /**
  28382. * Whether the material is rendered with flat shading or not.
  28383. *
  28384. * @type {boolean}
  28385. * @default false
  28386. */
  28387. this.flatShading = false;
  28388. /**
  28389. * Whether the material is affected by fog or not.
  28390. *
  28391. * @type {boolean}
  28392. * @default true
  28393. */
  28394. this.fog = true;
  28395. this.setValues( parameters );
  28396. }
  28397. copy( source ) {
  28398. super.copy( source );
  28399. this.defines = { 'STANDARD': '' };
  28400. this.color.copy( source.color );
  28401. this.roughness = source.roughness;
  28402. this.metalness = source.metalness;
  28403. this.map = source.map;
  28404. this.lightMap = source.lightMap;
  28405. this.lightMapIntensity = source.lightMapIntensity;
  28406. this.aoMap = source.aoMap;
  28407. this.aoMapIntensity = source.aoMapIntensity;
  28408. this.emissive.copy( source.emissive );
  28409. this.emissiveMap = source.emissiveMap;
  28410. this.emissiveIntensity = source.emissiveIntensity;
  28411. this.bumpMap = source.bumpMap;
  28412. this.bumpScale = source.bumpScale;
  28413. this.normalMap = source.normalMap;
  28414. this.normalMapType = source.normalMapType;
  28415. this.normalScale.copy( source.normalScale );
  28416. this.displacementMap = source.displacementMap;
  28417. this.displacementScale = source.displacementScale;
  28418. this.displacementBias = source.displacementBias;
  28419. this.roughnessMap = source.roughnessMap;
  28420. this.metalnessMap = source.metalnessMap;
  28421. this.alphaMap = source.alphaMap;
  28422. this.envMap = source.envMap;
  28423. this.envMapRotation.copy( source.envMapRotation );
  28424. this.envMapIntensity = source.envMapIntensity;
  28425. this.wireframe = source.wireframe;
  28426. this.wireframeLinewidth = source.wireframeLinewidth;
  28427. this.wireframeLinecap = source.wireframeLinecap;
  28428. this.wireframeLinejoin = source.wireframeLinejoin;
  28429. this.flatShading = source.flatShading;
  28430. this.fog = source.fog;
  28431. return this;
  28432. }
  28433. }
  28434. /**
  28435. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28436. * physically-based rendering properties:
  28437. *
  28438. * - Anisotropy: Ability to represent the anisotropic property of materials
  28439. * as observable with brushed metals.
  28440. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28441. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28442. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28443. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28444. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28445. * wings of many insects.
  28446. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28447. * transparent materials are less reflective. Physically-based transmission provides a more
  28448. * realistic option for thin, transparent surfaces like glass.
  28449. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28450. * - Sheen: Can be used for representing cloth and fabric materials.
  28451. *
  28452. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28453. * higher performance cost, per pixel, than other three.js materials. Most
  28454. * effects are disabled by default, and add cost as they are enabled. For
  28455. * best results, always specify an environment map when using this material.
  28456. *
  28457. * @augments MeshStandardMaterial
  28458. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  28459. */
  28460. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28461. /**
  28462. * Constructs a new mesh physical material.
  28463. *
  28464. * @param {Object} [parameters] - An object with one or more properties
  28465. * defining the material's appearance. Any property of the material
  28466. * (including any property from inherited materials) can be passed
  28467. * in here. Color values can be passed any type of value accepted
  28468. * by {@link Color#set}.
  28469. */
  28470. constructor( parameters ) {
  28471. super();
  28472. /**
  28473. * This flag can be used for type testing.
  28474. *
  28475. * @type {boolean}
  28476. * @readonly
  28477. * @default true
  28478. */
  28479. this.isMeshPhysicalMaterial = true;
  28480. this.defines = {
  28481. 'STANDARD': '',
  28482. 'PHYSICAL': ''
  28483. };
  28484. this.type = 'MeshPhysicalMaterial';
  28485. /**
  28486. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28487. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28488. * property provides additional rotation to the vectors in the texture.
  28489. *
  28490. * @type {number}
  28491. * @default 1
  28492. */
  28493. this.anisotropyRotation = 0;
  28494. /**
  28495. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28496. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28497. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28498. *
  28499. * @type {?Texture}
  28500. * @default null
  28501. */
  28502. this.anisotropyMap = null;
  28503. /**
  28504. * The red channel of this texture is multiplied against `clearcoat`,
  28505. * for per-pixel control over a coating's intensity.
  28506. *
  28507. * @type {?Texture}
  28508. * @default null
  28509. */
  28510. this.clearcoatMap = null;
  28511. /**
  28512. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28513. *
  28514. * @type {number}
  28515. * @default 0
  28516. */
  28517. this.clearcoatRoughness = 0.0;
  28518. /**
  28519. * The green channel of this texture is multiplied against
  28520. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28521. *
  28522. * @type {?Texture}
  28523. * @default null
  28524. */
  28525. this.clearcoatRoughnessMap = null;
  28526. /**
  28527. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28528. * `(0,0)` to `(1,1)`.
  28529. *
  28530. * @type {Vector2}
  28531. * @default (1,1)
  28532. */
  28533. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28534. /**
  28535. * Can be used to enable independent normals for the clear coat layer.
  28536. *
  28537. * @type {?Texture}
  28538. * @default null
  28539. */
  28540. this.clearcoatNormalMap = null;
  28541. /**
  28542. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28543. *
  28544. * @type {number}
  28545. * @default 1.5
  28546. */
  28547. this.ior = 1.5;
  28548. /**
  28549. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28550. * corresponds to an index-of-refraction of `1.5`.
  28551. *
  28552. * This models the reflectivity of non-metallic materials. It has no effect
  28553. * when `metalness` is `1.0`
  28554. *
  28555. * @name MeshPhysicalMaterial#reflectivity
  28556. * @type {number}
  28557. * @default 0.5
  28558. */
  28559. Object.defineProperty( this, 'reflectivity', {
  28560. get: function () {
  28561. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28562. },
  28563. set: function ( reflectivity ) {
  28564. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28565. }
  28566. } );
  28567. /**
  28568. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28569. * control over iridescence.
  28570. *
  28571. * @type {?Texture}
  28572. * @default null
  28573. */
  28574. this.iridescenceMap = null;
  28575. /**
  28576. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28577. * Between `1.0` to `2.333`.
  28578. *
  28579. * @type {number}
  28580. * @default 1.3
  28581. */
  28582. this.iridescenceIOR = 1.3;
  28583. /**
  28584. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28585. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28586. *
  28587. * @type {Array<number,number>}
  28588. * @default [100,400]
  28589. */
  28590. this.iridescenceThicknessRange = [ 100, 400 ];
  28591. /**
  28592. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28593. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28594. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28595. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28596. * - Values in-between will linearly interpolate between the elements of the array.
  28597. *
  28598. * @type {?Texture}
  28599. * @default null
  28600. */
  28601. this.iridescenceThicknessMap = null;
  28602. /**
  28603. * The sheen tint.
  28604. *
  28605. * @type {Color}
  28606. * @default (0,0,0)
  28607. */
  28608. this.sheenColor = new Color( 0x000000 );
  28609. /**
  28610. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28611. * over sheen tint.
  28612. *
  28613. * @type {?Texture}
  28614. * @default null
  28615. */
  28616. this.sheenColorMap = null;
  28617. /**
  28618. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28619. *
  28620. * @type {number}
  28621. * @default 1
  28622. */
  28623. this.sheenRoughness = 1.0;
  28624. /**
  28625. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28626. * over sheen roughness.
  28627. *
  28628. * @type {?Texture}
  28629. * @default null
  28630. */
  28631. this.sheenRoughnessMap = null;
  28632. /**
  28633. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28634. * optical transparency.
  28635. *
  28636. * @type {?Texture}
  28637. * @default null
  28638. */
  28639. this.transmissionMap = null;
  28640. /**
  28641. * The thickness of the volume beneath the surface. The value is given in the
  28642. * coordinate space of the mesh. If the value is `0` the material is
  28643. * thin-walled. Otherwise the material is a volume boundary.
  28644. *
  28645. * @type {number}
  28646. * @default 0
  28647. */
  28648. this.thickness = 0;
  28649. /**
  28650. * A texture that defines the thickness, stored in the green channel. This will
  28651. * be multiplied by `thickness`.
  28652. *
  28653. * @type {?Texture}
  28654. * @default null
  28655. */
  28656. this.thicknessMap = null;
  28657. /**
  28658. * Density of the medium given as the average distance that light travels in
  28659. * the medium before interacting with a particle. The value is given in world
  28660. * space units, and must be greater than zero.
  28661. *
  28662. * @type {number}
  28663. * @default Infinity
  28664. */
  28665. this.attenuationDistance = Infinity;
  28666. /**
  28667. * The color that white light turns into due to absorption when reaching the
  28668. * attenuation distance.
  28669. *
  28670. * @type {Color}
  28671. * @default (1,1,1)
  28672. */
  28673. this.attenuationColor = new Color( 1, 1, 1 );
  28674. /**
  28675. * A float that scales the amount of specular reflection for non-metals only.
  28676. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28677. *
  28678. * @type {number}
  28679. * @default 1
  28680. */
  28681. this.specularIntensity = 1.0;
  28682. /**
  28683. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28684. * for per-pixel control over specular intensity.
  28685. *
  28686. * @type {?Texture}
  28687. * @default null
  28688. */
  28689. this.specularIntensityMap = null;
  28690. /**
  28691. * Tints the specular reflection at normal incidence for non-metals only.
  28692. *
  28693. * @type {Color}
  28694. * @default (1,1,1)
  28695. */
  28696. this.specularColor = new Color( 1, 1, 1 );
  28697. /**
  28698. * The RGB channels of this texture are multiplied against `specularColor`,
  28699. * for per-pixel control over specular color.
  28700. *
  28701. * @type {?Texture}
  28702. * @default null
  28703. */
  28704. this.specularColorMap = null;
  28705. this._anisotropy = 0;
  28706. this._clearcoat = 0;
  28707. this._dispersion = 0;
  28708. this._iridescence = 0;
  28709. this._sheen = 0.0;
  28710. this._transmission = 0;
  28711. this.setValues( parameters );
  28712. }
  28713. /**
  28714. * The anisotropy strength, from `0.0` to `1.0`.
  28715. *
  28716. * @type {number}
  28717. * @default 0
  28718. */
  28719. get anisotropy() {
  28720. return this._anisotropy;
  28721. }
  28722. set anisotropy( value ) {
  28723. if ( this._anisotropy > 0 !== value > 0 ) {
  28724. this.version ++;
  28725. }
  28726. this._anisotropy = value;
  28727. }
  28728. /**
  28729. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28730. * clear coat related properties to enable multilayer materials that have a
  28731. * thin translucent layer over the base layer.
  28732. *
  28733. * @type {number}
  28734. * @default 0
  28735. */
  28736. get clearcoat() {
  28737. return this._clearcoat;
  28738. }
  28739. set clearcoat( value ) {
  28740. if ( this._clearcoat > 0 !== value > 0 ) {
  28741. this.version ++;
  28742. }
  28743. this._clearcoat = value;
  28744. }
  28745. /**
  28746. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28747. * the surface and the viewer, from `0.0` to `1.0`.
  28748. *
  28749. * @type {number}
  28750. * @default 0
  28751. */
  28752. get iridescence() {
  28753. return this._iridescence;
  28754. }
  28755. set iridescence( value ) {
  28756. if ( this._iridescence > 0 !== value > 0 ) {
  28757. this.version ++;
  28758. }
  28759. this._iridescence = value;
  28760. }
  28761. /**
  28762. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28763. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28764. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28765. *
  28766. * @type {number}
  28767. * @default 0
  28768. */
  28769. get dispersion() {
  28770. return this._dispersion;
  28771. }
  28772. set dispersion( value ) {
  28773. if ( this._dispersion > 0 !== value > 0 ) {
  28774. this.version ++;
  28775. }
  28776. this._dispersion = value;
  28777. }
  28778. /**
  28779. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28780. *
  28781. * @type {number}
  28782. * @default 0
  28783. */
  28784. get sheen() {
  28785. return this._sheen;
  28786. }
  28787. set sheen( value ) {
  28788. if ( this._sheen > 0 !== value > 0 ) {
  28789. this.version ++;
  28790. }
  28791. this._sheen = value;
  28792. }
  28793. /**
  28794. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28795. *
  28796. * Thin, transparent or semitransparent, plastic or glass materials remain
  28797. * largely reflective even if they are fully transmissive. The transmission
  28798. * property can be used to model these materials.
  28799. *
  28800. * When transmission is non-zero, `opacity` should be set to `1`.
  28801. *
  28802. * @type {number}
  28803. * @default 0
  28804. */
  28805. get transmission() {
  28806. return this._transmission;
  28807. }
  28808. set transmission( value ) {
  28809. if ( this._transmission > 0 !== value > 0 ) {
  28810. this.version ++;
  28811. }
  28812. this._transmission = value;
  28813. }
  28814. copy( source ) {
  28815. super.copy( source );
  28816. this.defines = {
  28817. 'STANDARD': '',
  28818. 'PHYSICAL': ''
  28819. };
  28820. this.anisotropy = source.anisotropy;
  28821. this.anisotropyRotation = source.anisotropyRotation;
  28822. this.anisotropyMap = source.anisotropyMap;
  28823. this.clearcoat = source.clearcoat;
  28824. this.clearcoatMap = source.clearcoatMap;
  28825. this.clearcoatRoughness = source.clearcoatRoughness;
  28826. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28827. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28828. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28829. this.dispersion = source.dispersion;
  28830. this.ior = source.ior;
  28831. this.iridescence = source.iridescence;
  28832. this.iridescenceMap = source.iridescenceMap;
  28833. this.iridescenceIOR = source.iridescenceIOR;
  28834. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28835. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28836. this.sheen = source.sheen;
  28837. this.sheenColor.copy( source.sheenColor );
  28838. this.sheenColorMap = source.sheenColorMap;
  28839. this.sheenRoughness = source.sheenRoughness;
  28840. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28841. this.transmission = source.transmission;
  28842. this.transmissionMap = source.transmissionMap;
  28843. this.thickness = source.thickness;
  28844. this.thicknessMap = source.thicknessMap;
  28845. this.attenuationDistance = source.attenuationDistance;
  28846. this.attenuationColor.copy( source.attenuationColor );
  28847. this.specularIntensity = source.specularIntensity;
  28848. this.specularIntensityMap = source.specularIntensityMap;
  28849. this.specularColor.copy( source.specularColor );
  28850. this.specularColorMap = source.specularColorMap;
  28851. return this;
  28852. }
  28853. }
  28854. /**
  28855. * A material for shiny surfaces with specular highlights.
  28856. *
  28857. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28858. * model for calculating reflectance. Unlike the Lambertian model used in the
  28859. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28860. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28861. *
  28862. * Performance will generally be greater when using this material over the
  28863. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28864. * some graphical accuracy.
  28865. *
  28866. * @augments Material
  28867. * @demo scenes/material-browser.html#MeshPhongMaterial
  28868. */
  28869. class MeshPhongMaterial extends Material {
  28870. /**
  28871. * Constructs a new mesh phong material.
  28872. *
  28873. * @param {Object} [parameters] - An object with one or more properties
  28874. * defining the material's appearance. Any property of the material
  28875. * (including any property from inherited materials) can be passed
  28876. * in here. Color values can be passed any type of value accepted
  28877. * by {@link Color#set}.
  28878. */
  28879. constructor( parameters ) {
  28880. super();
  28881. /**
  28882. * This flag can be used for type testing.
  28883. *
  28884. * @type {boolean}
  28885. * @readonly
  28886. * @default true
  28887. */
  28888. this.isMeshPhongMaterial = true;
  28889. this.type = 'MeshPhongMaterial';
  28890. /**
  28891. * Color of the material.
  28892. *
  28893. * @type {Color}
  28894. * @default (1,1,1)
  28895. */
  28896. this.color = new Color( 0xffffff ); // diffuse
  28897. /**
  28898. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28899. *
  28900. * This defines how shiny the material is and the color of its shine.
  28901. *
  28902. * @type {Color}
  28903. */
  28904. this.specular = new Color( 0x111111 );
  28905. /**
  28906. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28907. *
  28908. * @type {number}
  28909. * @default 30
  28910. */
  28911. this.shininess = 30;
  28912. /**
  28913. * The color map. May optionally include an alpha channel, typically combined
  28914. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28915. * color is modulated by the diffuse `color`.
  28916. *
  28917. * @type {?Texture}
  28918. * @default null
  28919. */
  28920. this.map = null;
  28921. /**
  28922. * The light map. Requires a second set of UVs.
  28923. *
  28924. * @type {?Texture}
  28925. * @default null
  28926. */
  28927. this.lightMap = null;
  28928. /**
  28929. * Intensity of the baked light.
  28930. *
  28931. * @type {number}
  28932. * @default 1
  28933. */
  28934. this.lightMapIntensity = 1.0;
  28935. /**
  28936. * The red channel of this texture is used as the ambient occlusion map.
  28937. * Requires a second set of UVs.
  28938. *
  28939. * @type {?Texture}
  28940. * @default null
  28941. */
  28942. this.aoMap = null;
  28943. /**
  28944. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28945. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28946. * red channel is also `1`, ambient light is fully occluded on a surface.
  28947. *
  28948. * @type {number}
  28949. * @default 1
  28950. */
  28951. this.aoMapIntensity = 1.0;
  28952. /**
  28953. * Emissive (light) color of the material, essentially a solid color
  28954. * unaffected by other lighting.
  28955. *
  28956. * @type {Color}
  28957. * @default (0,0,0)
  28958. */
  28959. this.emissive = new Color( 0x000000 );
  28960. /**
  28961. * Intensity of the emissive light. Modulates the emissive color.
  28962. *
  28963. * @type {number}
  28964. * @default 1
  28965. */
  28966. this.emissiveIntensity = 1.0;
  28967. /**
  28968. * Set emissive (glow) map. The emissive map color is modulated by the
  28969. * emissive color and the emissive intensity. If you have an emissive map,
  28970. * be sure to set the emissive color to something other than black.
  28971. *
  28972. * @type {?Texture}
  28973. * @default null
  28974. */
  28975. this.emissiveMap = null;
  28976. /**
  28977. * The texture to create a bump map. The black and white values map to the
  28978. * perceived depth in relation to the lights. Bump doesn't actually affect
  28979. * the geometry of the object, only the lighting. If a normal map is defined
  28980. * this will be ignored.
  28981. *
  28982. * @type {?Texture}
  28983. * @default null
  28984. */
  28985. this.bumpMap = null;
  28986. /**
  28987. * How much the bump map affects the material. Typical range is `[0,1]`.
  28988. *
  28989. * @type {number}
  28990. * @default 1
  28991. */
  28992. this.bumpScale = 1;
  28993. /**
  28994. * The texture to create a normal map. The RGB values affect the surface
  28995. * normal for each pixel fragment and change the way the color is lit. Normal
  28996. * maps do not change the actual shape of the surface, only the lighting. In
  28997. * case the material has a normal map authored using the left handed
  28998. * convention, the `y` component of `normalScale` should be negated to compensate
  28999. * for the different handedness.
  29000. *
  29001. * @type {?Texture}
  29002. * @default null
  29003. */
  29004. this.normalMap = null;
  29005. /**
  29006. * The type of normal map.
  29007. *
  29008. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29009. * @default TangentSpaceNormalMap
  29010. */
  29011. this.normalMapType = TangentSpaceNormalMap;
  29012. /**
  29013. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29014. *
  29015. * @type {Vector2}
  29016. * @default (1,1)
  29017. */
  29018. this.normalScale = new Vector2( 1, 1 );
  29019. /**
  29020. * The displacement map affects the position of the mesh's vertices. Unlike
  29021. * other maps which only affect the light and shade of the material the
  29022. * displaced vertices can cast shadows, block other objects, and otherwise
  29023. * act as real geometry. The displacement texture is an image where the value
  29024. * of each pixel (white being the highest) is mapped against, and
  29025. * repositions, the vertices of the mesh.
  29026. *
  29027. * @type {?Texture}
  29028. * @default null
  29029. */
  29030. this.displacementMap = null;
  29031. /**
  29032. * How much the displacement map affects the mesh (where black is no
  29033. * displacement, and white is maximum displacement). Without a displacement
  29034. * map set, this value is not applied.
  29035. *
  29036. * @type {number}
  29037. * @default 0
  29038. */
  29039. this.displacementScale = 1;
  29040. /**
  29041. * The offset of the displacement map's values on the mesh's vertices.
  29042. * The bias is added to the scaled sample of the displacement map.
  29043. * Without a displacement map set, this value is not applied.
  29044. *
  29045. * @type {number}
  29046. * @default 0
  29047. */
  29048. this.displacementBias = 0;
  29049. /**
  29050. * The specular map value affects both how much the specular surface
  29051. * highlight contributes and how much of the environment map affects the
  29052. * surface.
  29053. *
  29054. * @type {?Texture}
  29055. * @default null
  29056. */
  29057. this.specularMap = null;
  29058. /**
  29059. * The alpha map is a grayscale texture that controls the opacity across the
  29060. * surface (black: fully transparent; white: fully opaque).
  29061. *
  29062. * Only the color of the texture is used, ignoring the alpha channel if one
  29063. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29064. * when sampling this texture due to the extra bit of precision provided for
  29065. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29066. * luminance/alpha textures will also still work as expected.
  29067. *
  29068. * @type {?Texture}
  29069. * @default null
  29070. */
  29071. this.alphaMap = null;
  29072. /**
  29073. * The environment map.
  29074. *
  29075. * @type {?Texture}
  29076. * @default null
  29077. */
  29078. this.envMap = null;
  29079. /**
  29080. * The rotation of the environment map in radians.
  29081. *
  29082. * @type {Euler}
  29083. * @default (0,0,0)
  29084. */
  29085. this.envMapRotation = new Euler();
  29086. /**
  29087. * How to combine the result of the surface's color with the environment map, if any.
  29088. *
  29089. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29090. * blend between the two colors.
  29091. *
  29092. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29093. * @default MultiplyOperation
  29094. */
  29095. this.combine = MultiplyOperation;
  29096. /**
  29097. * How much the environment map affects the surface.
  29098. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29099. *
  29100. * @type {number}
  29101. * @default 1
  29102. */
  29103. this.reflectivity = 1;
  29104. /**
  29105. * Scales the effect of the environment map by multiplying its color.
  29106. *
  29107. * @type {number}
  29108. * @default 1
  29109. */
  29110. this.envMapIntensity = 1.0;
  29111. /**
  29112. * The index of refraction (IOR) of air (approximately 1) divided by the
  29113. * index of refraction of the material. It is used with environment mapping
  29114. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29115. * The refraction ratio should not exceed `1`.
  29116. *
  29117. * @type {number}
  29118. * @default 0.98
  29119. */
  29120. this.refractionRatio = 0.98;
  29121. /**
  29122. * Renders the geometry as a wireframe.
  29123. *
  29124. * @type {boolean}
  29125. * @default false
  29126. */
  29127. this.wireframe = false;
  29128. /**
  29129. * Controls the thickness of the wireframe.
  29130. *
  29131. * Can only be used with {@link SVGRenderer}.
  29132. *
  29133. * @type {number}
  29134. * @default 1
  29135. */
  29136. this.wireframeLinewidth = 1;
  29137. /**
  29138. * Defines appearance of wireframe ends.
  29139. *
  29140. * Can only be used with {@link SVGRenderer}.
  29141. *
  29142. * @type {('round'|'bevel'|'miter')}
  29143. * @default 'round'
  29144. */
  29145. this.wireframeLinecap = 'round';
  29146. /**
  29147. * Defines appearance of wireframe joints.
  29148. *
  29149. * Can only be used with {@link SVGRenderer}.
  29150. *
  29151. * @type {('round'|'bevel'|'miter')}
  29152. * @default 'round'
  29153. */
  29154. this.wireframeLinejoin = 'round';
  29155. /**
  29156. * Whether the material is rendered with flat shading or not.
  29157. *
  29158. * @type {boolean}
  29159. * @default false
  29160. */
  29161. this.flatShading = false;
  29162. /**
  29163. * Whether the material is affected by fog or not.
  29164. *
  29165. * @type {boolean}
  29166. * @default true
  29167. */
  29168. this.fog = true;
  29169. this.setValues( parameters );
  29170. }
  29171. copy( source ) {
  29172. super.copy( source );
  29173. this.color.copy( source.color );
  29174. this.specular.copy( source.specular );
  29175. this.shininess = source.shininess;
  29176. this.map = source.map;
  29177. this.lightMap = source.lightMap;
  29178. this.lightMapIntensity = source.lightMapIntensity;
  29179. this.aoMap = source.aoMap;
  29180. this.aoMapIntensity = source.aoMapIntensity;
  29181. this.emissive.copy( source.emissive );
  29182. this.emissiveMap = source.emissiveMap;
  29183. this.emissiveIntensity = source.emissiveIntensity;
  29184. this.bumpMap = source.bumpMap;
  29185. this.bumpScale = source.bumpScale;
  29186. this.normalMap = source.normalMap;
  29187. this.normalMapType = source.normalMapType;
  29188. this.normalScale.copy( source.normalScale );
  29189. this.displacementMap = source.displacementMap;
  29190. this.displacementScale = source.displacementScale;
  29191. this.displacementBias = source.displacementBias;
  29192. this.specularMap = source.specularMap;
  29193. this.alphaMap = source.alphaMap;
  29194. this.envMap = source.envMap;
  29195. this.envMapRotation.copy( source.envMapRotation );
  29196. this.combine = source.combine;
  29197. this.reflectivity = source.reflectivity;
  29198. this.envMapIntensity = source.envMapIntensity;
  29199. this.refractionRatio = source.refractionRatio;
  29200. this.wireframe = source.wireframe;
  29201. this.wireframeLinewidth = source.wireframeLinewidth;
  29202. this.wireframeLinecap = source.wireframeLinecap;
  29203. this.wireframeLinejoin = source.wireframeLinejoin;
  29204. this.flatShading = source.flatShading;
  29205. this.fog = source.fog;
  29206. return this;
  29207. }
  29208. }
  29209. /**
  29210. * A material implementing toon shading.
  29211. *
  29212. * @augments Material
  29213. * @demo scenes/material-browser.html#MeshToonMaterial
  29214. */
  29215. class MeshToonMaterial extends Material {
  29216. /**
  29217. * Constructs a new mesh toon material.
  29218. *
  29219. * @param {Object} [parameters] - An object with one or more properties
  29220. * defining the material's appearance. Any property of the material
  29221. * (including any property from inherited materials) can be passed
  29222. * in here. Color values can be passed any type of value accepted
  29223. * by {@link Color#set}.
  29224. */
  29225. constructor( parameters ) {
  29226. super();
  29227. /**
  29228. * This flag can be used for type testing.
  29229. *
  29230. * @type {boolean}
  29231. * @readonly
  29232. * @default true
  29233. */
  29234. this.isMeshToonMaterial = true;
  29235. this.defines = { 'TOON': '' };
  29236. this.type = 'MeshToonMaterial';
  29237. /**
  29238. * Color of the material.
  29239. *
  29240. * @type {Color}
  29241. * @default (1,1,1)
  29242. */
  29243. this.color = new Color( 0xffffff );
  29244. /**
  29245. * The color map. May optionally include an alpha channel, typically combined
  29246. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29247. * color is modulated by the diffuse `color`.
  29248. *
  29249. * @type {?Texture}
  29250. * @default null
  29251. */
  29252. this.map = null;
  29253. /**
  29254. * Gradient map for toon shading. It's required to set
  29255. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  29256. * when using this type of texture.
  29257. *
  29258. * @type {?Texture}
  29259. * @default null
  29260. */
  29261. this.gradientMap = null;
  29262. /**
  29263. * The light map. Requires a second set of UVs.
  29264. *
  29265. * @type {?Texture}
  29266. * @default null
  29267. */
  29268. this.lightMap = null;
  29269. /**
  29270. * Intensity of the baked light.
  29271. *
  29272. * @type {number}
  29273. * @default 1
  29274. */
  29275. this.lightMapIntensity = 1.0;
  29276. /**
  29277. * The red channel of this texture is used as the ambient occlusion map.
  29278. * Requires a second set of UVs.
  29279. *
  29280. * @type {?Texture}
  29281. * @default null
  29282. */
  29283. this.aoMap = null;
  29284. /**
  29285. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29286. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29287. * red channel is also `1`, ambient light is fully occluded on a surface.
  29288. *
  29289. * @type {number}
  29290. * @default 1
  29291. */
  29292. this.aoMapIntensity = 1.0;
  29293. /**
  29294. * Emissive (light) color of the material, essentially a solid color
  29295. * unaffected by other lighting.
  29296. *
  29297. * @type {Color}
  29298. * @default (0,0,0)
  29299. */
  29300. this.emissive = new Color( 0x000000 );
  29301. /**
  29302. * Intensity of the emissive light. Modulates the emissive color.
  29303. *
  29304. * @type {number}
  29305. * @default 1
  29306. */
  29307. this.emissiveIntensity = 1.0;
  29308. /**
  29309. * Set emissive (glow) map. The emissive map color is modulated by the
  29310. * emissive color and the emissive intensity. If you have an emissive map,
  29311. * be sure to set the emissive color to something other than black.
  29312. *
  29313. * @type {?Texture}
  29314. * @default null
  29315. */
  29316. this.emissiveMap = null;
  29317. /**
  29318. * The texture to create a bump map. The black and white values map to the
  29319. * perceived depth in relation to the lights. Bump doesn't actually affect
  29320. * the geometry of the object, only the lighting. If a normal map is defined
  29321. * this will be ignored.
  29322. *
  29323. * @type {?Texture}
  29324. * @default null
  29325. */
  29326. this.bumpMap = null;
  29327. /**
  29328. * How much the bump map affects the material. Typical range is `[0,1]`.
  29329. *
  29330. * @type {number}
  29331. * @default 1
  29332. */
  29333. this.bumpScale = 1;
  29334. /**
  29335. * The texture to create a normal map. The RGB values affect the surface
  29336. * normal for each pixel fragment and change the way the color is lit. Normal
  29337. * maps do not change the actual shape of the surface, only the lighting. In
  29338. * case the material has a normal map authored using the left handed
  29339. * convention, the `y` component of `normalScale` should be negated to compensate
  29340. * for the different handedness.
  29341. *
  29342. * @type {?Texture}
  29343. * @default null
  29344. */
  29345. this.normalMap = null;
  29346. /**
  29347. * The type of normal map.
  29348. *
  29349. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29350. * @default TangentSpaceNormalMap
  29351. */
  29352. this.normalMapType = TangentSpaceNormalMap;
  29353. /**
  29354. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29355. *
  29356. * @type {Vector2}
  29357. * @default (1,1)
  29358. */
  29359. this.normalScale = new Vector2( 1, 1 );
  29360. /**
  29361. * The displacement map affects the position of the mesh's vertices. Unlike
  29362. * other maps which only affect the light and shade of the material the
  29363. * displaced vertices can cast shadows, block other objects, and otherwise
  29364. * act as real geometry. The displacement texture is an image where the value
  29365. * of each pixel (white being the highest) is mapped against, and
  29366. * repositions, the vertices of the mesh.
  29367. *
  29368. * @type {?Texture}
  29369. * @default null
  29370. */
  29371. this.displacementMap = null;
  29372. /**
  29373. * How much the displacement map affects the mesh (where black is no
  29374. * displacement, and white is maximum displacement). Without a displacement
  29375. * map set, this value is not applied.
  29376. *
  29377. * @type {number}
  29378. * @default 0
  29379. */
  29380. this.displacementScale = 1;
  29381. /**
  29382. * The offset of the displacement map's values on the mesh's vertices.
  29383. * The bias is added to the scaled sample of the displacement map.
  29384. * Without a displacement map set, this value is not applied.
  29385. *
  29386. * @type {number}
  29387. * @default 0
  29388. */
  29389. this.displacementBias = 0;
  29390. /**
  29391. * The alpha map is a grayscale texture that controls the opacity across the
  29392. * surface (black: fully transparent; white: fully opaque).
  29393. *
  29394. * Only the color of the texture is used, ignoring the alpha channel if one
  29395. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29396. * when sampling this texture due to the extra bit of precision provided for
  29397. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29398. * luminance/alpha textures will also still work as expected.
  29399. *
  29400. * @type {?Texture}
  29401. * @default null
  29402. */
  29403. this.alphaMap = null;
  29404. /**
  29405. * Renders the geometry as a wireframe.
  29406. *
  29407. * @type {boolean}
  29408. * @default false
  29409. */
  29410. this.wireframe = false;
  29411. /**
  29412. * Controls the thickness of the wireframe.
  29413. *
  29414. * Can only be used with {@link SVGRenderer}.
  29415. *
  29416. * @type {number}
  29417. * @default 1
  29418. */
  29419. this.wireframeLinewidth = 1;
  29420. /**
  29421. * Defines appearance of wireframe ends.
  29422. *
  29423. * Can only be used with {@link SVGRenderer}.
  29424. *
  29425. * @type {('round'|'bevel'|'miter')}
  29426. * @default 'round'
  29427. */
  29428. this.wireframeLinecap = 'round';
  29429. /**
  29430. * Defines appearance of wireframe joints.
  29431. *
  29432. * Can only be used with {@link SVGRenderer}.
  29433. *
  29434. * @type {('round'|'bevel'|'miter')}
  29435. * @default 'round'
  29436. */
  29437. this.wireframeLinejoin = 'round';
  29438. /**
  29439. * Whether the material is affected by fog or not.
  29440. *
  29441. * @type {boolean}
  29442. * @default true
  29443. */
  29444. this.fog = true;
  29445. this.setValues( parameters );
  29446. }
  29447. copy( source ) {
  29448. super.copy( source );
  29449. this.color.copy( source.color );
  29450. this.map = source.map;
  29451. this.gradientMap = source.gradientMap;
  29452. this.lightMap = source.lightMap;
  29453. this.lightMapIntensity = source.lightMapIntensity;
  29454. this.aoMap = source.aoMap;
  29455. this.aoMapIntensity = source.aoMapIntensity;
  29456. this.emissive.copy( source.emissive );
  29457. this.emissiveMap = source.emissiveMap;
  29458. this.emissiveIntensity = source.emissiveIntensity;
  29459. this.bumpMap = source.bumpMap;
  29460. this.bumpScale = source.bumpScale;
  29461. this.normalMap = source.normalMap;
  29462. this.normalMapType = source.normalMapType;
  29463. this.normalScale.copy( source.normalScale );
  29464. this.displacementMap = source.displacementMap;
  29465. this.displacementScale = source.displacementScale;
  29466. this.displacementBias = source.displacementBias;
  29467. this.alphaMap = source.alphaMap;
  29468. this.wireframe = source.wireframe;
  29469. this.wireframeLinewidth = source.wireframeLinewidth;
  29470. this.wireframeLinecap = source.wireframeLinecap;
  29471. this.wireframeLinejoin = source.wireframeLinejoin;
  29472. this.fog = source.fog;
  29473. return this;
  29474. }
  29475. }
  29476. /**
  29477. * A material that maps the normal vectors to RGB colors.
  29478. *
  29479. * @augments Material
  29480. * @demo scenes/material-browser.html#MeshNormalMaterial
  29481. */
  29482. class MeshNormalMaterial extends Material {
  29483. /**
  29484. * Constructs a new mesh normal material.
  29485. *
  29486. * @param {Object} [parameters] - An object with one or more properties
  29487. * defining the material's appearance. Any property of the material
  29488. * (including any property from inherited materials) can be passed
  29489. * in here. Color values can be passed any type of value accepted
  29490. * by {@link Color#set}.
  29491. */
  29492. constructor( parameters ) {
  29493. super();
  29494. /**
  29495. * This flag can be used for type testing.
  29496. *
  29497. * @type {boolean}
  29498. * @readonly
  29499. * @default true
  29500. */
  29501. this.isMeshNormalMaterial = true;
  29502. this.type = 'MeshNormalMaterial';
  29503. /**
  29504. * The texture to create a bump map. The black and white values map to the
  29505. * perceived depth in relation to the lights. Bump doesn't actually affect
  29506. * the geometry of the object, only the lighting. If a normal map is defined
  29507. * this will be ignored.
  29508. *
  29509. * @type {?Texture}
  29510. * @default null
  29511. */
  29512. this.bumpMap = null;
  29513. /**
  29514. * How much the bump map affects the material. Typical range is `[0,1]`.
  29515. *
  29516. * @type {number}
  29517. * @default 1
  29518. */
  29519. this.bumpScale = 1;
  29520. /**
  29521. * The texture to create a normal map. The RGB values affect the surface
  29522. * normal for each pixel fragment and change the way the color is lit. Normal
  29523. * maps do not change the actual shape of the surface, only the lighting. In
  29524. * case the material has a normal map authored using the left handed
  29525. * convention, the `y` component of `normalScale` should be negated to compensate
  29526. * for the different handedness.
  29527. *
  29528. * @type {?Texture}
  29529. * @default null
  29530. */
  29531. this.normalMap = null;
  29532. /**
  29533. * The type of normal map.
  29534. *
  29535. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29536. * @default TangentSpaceNormalMap
  29537. */
  29538. this.normalMapType = TangentSpaceNormalMap;
  29539. /**
  29540. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29541. *
  29542. * @type {Vector2}
  29543. * @default (1,1)
  29544. */
  29545. this.normalScale = new Vector2( 1, 1 );
  29546. /**
  29547. * The displacement map affects the position of the mesh's vertices. Unlike
  29548. * other maps which only affect the light and shade of the material the
  29549. * displaced vertices can cast shadows, block other objects, and otherwise
  29550. * act as real geometry. The displacement texture is an image where the value
  29551. * of each pixel (white being the highest) is mapped against, and
  29552. * repositions, the vertices of the mesh.
  29553. *
  29554. * @type {?Texture}
  29555. * @default null
  29556. */
  29557. this.displacementMap = null;
  29558. /**
  29559. * How much the displacement map affects the mesh (where black is no
  29560. * displacement, and white is maximum displacement). Without a displacement
  29561. * map set, this value is not applied.
  29562. *
  29563. * @type {number}
  29564. * @default 0
  29565. */
  29566. this.displacementScale = 1;
  29567. /**
  29568. * The offset of the displacement map's values on the mesh's vertices.
  29569. * The bias is added to the scaled sample of the displacement map.
  29570. * Without a displacement map set, this value is not applied.
  29571. *
  29572. * @type {number}
  29573. * @default 0
  29574. */
  29575. this.displacementBias = 0;
  29576. /**
  29577. * Renders the geometry as a wireframe.
  29578. *
  29579. * @type {boolean}
  29580. * @default false
  29581. */
  29582. this.wireframe = false;
  29583. /**
  29584. * Controls the thickness of the wireframe.
  29585. *
  29586. * WebGL and WebGPU ignore this property and always render
  29587. * 1 pixel wide lines.
  29588. *
  29589. * @type {number}
  29590. * @default 1
  29591. */
  29592. this.wireframeLinewidth = 1;
  29593. /**
  29594. * Whether the material is rendered with flat shading or not.
  29595. *
  29596. * @type {boolean}
  29597. * @default false
  29598. */
  29599. this.flatShading = false;
  29600. this.setValues( parameters );
  29601. }
  29602. copy( source ) {
  29603. super.copy( source );
  29604. this.bumpMap = source.bumpMap;
  29605. this.bumpScale = source.bumpScale;
  29606. this.normalMap = source.normalMap;
  29607. this.normalMapType = source.normalMapType;
  29608. this.normalScale.copy( source.normalScale );
  29609. this.displacementMap = source.displacementMap;
  29610. this.displacementScale = source.displacementScale;
  29611. this.displacementBias = source.displacementBias;
  29612. this.wireframe = source.wireframe;
  29613. this.wireframeLinewidth = source.wireframeLinewidth;
  29614. this.flatShading = source.flatShading;
  29615. return this;
  29616. }
  29617. }
  29618. /**
  29619. * A material for non-shiny surfaces, without specular highlights.
  29620. *
  29621. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29622. * model for calculating reflectance. This can simulate some surfaces (such
  29623. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29624. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29625. * shading.
  29626. *
  29627. * Due to the simplicity of the reflectance and illumination models,
  29628. * performance will be greater when using this material over the
  29629. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29630. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29631. *
  29632. * @augments Material
  29633. * @demo scenes/material-browser.html#MeshLambertMaterial
  29634. */
  29635. class MeshLambertMaterial extends Material {
  29636. /**
  29637. * Constructs a new mesh lambert material.
  29638. *
  29639. * @param {Object} [parameters] - An object with one or more properties
  29640. * defining the material's appearance. Any property of the material
  29641. * (including any property from inherited materials) can be passed
  29642. * in here. Color values can be passed any type of value accepted
  29643. * by {@link Color#set}.
  29644. */
  29645. constructor( parameters ) {
  29646. super();
  29647. /**
  29648. * This flag can be used for type testing.
  29649. *
  29650. * @type {boolean}
  29651. * @readonly
  29652. * @default true
  29653. */
  29654. this.isMeshLambertMaterial = true;
  29655. this.type = 'MeshLambertMaterial';
  29656. /**
  29657. * Color of the material.
  29658. *
  29659. * @type {Color}
  29660. * @default (1,1,1)
  29661. */
  29662. this.color = new Color( 0xffffff ); // diffuse
  29663. /**
  29664. * The color map. May optionally include an alpha channel, typically combined
  29665. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29666. * color is modulated by the diffuse `color`.
  29667. *
  29668. * @type {?Texture}
  29669. * @default null
  29670. */
  29671. this.map = null;
  29672. /**
  29673. * The light map. Requires a second set of UVs.
  29674. *
  29675. * @type {?Texture}
  29676. * @default null
  29677. */
  29678. this.lightMap = null;
  29679. /**
  29680. * Intensity of the baked light.
  29681. *
  29682. * @type {number}
  29683. * @default 1
  29684. */
  29685. this.lightMapIntensity = 1.0;
  29686. /**
  29687. * The red channel of this texture is used as the ambient occlusion map.
  29688. * Requires a second set of UVs.
  29689. *
  29690. * @type {?Texture}
  29691. * @default null
  29692. */
  29693. this.aoMap = null;
  29694. /**
  29695. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29696. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29697. * red channel is also `1`, ambient light is fully occluded on a surface.
  29698. *
  29699. * @type {number}
  29700. * @default 1
  29701. */
  29702. this.aoMapIntensity = 1.0;
  29703. /**
  29704. * Emissive (light) color of the material, essentially a solid color
  29705. * unaffected by other lighting.
  29706. *
  29707. * @type {Color}
  29708. * @default (0,0,0)
  29709. */
  29710. this.emissive = new Color( 0x000000 );
  29711. /**
  29712. * Intensity of the emissive light. Modulates the emissive color.
  29713. *
  29714. * @type {number}
  29715. * @default 1
  29716. */
  29717. this.emissiveIntensity = 1.0;
  29718. /**
  29719. * Set emissive (glow) map. The emissive map color is modulated by the
  29720. * emissive color and the emissive intensity. If you have an emissive map,
  29721. * be sure to set the emissive color to something other than black.
  29722. *
  29723. * @type {?Texture}
  29724. * @default null
  29725. */
  29726. this.emissiveMap = null;
  29727. /**
  29728. * The texture to create a bump map. The black and white values map to the
  29729. * perceived depth in relation to the lights. Bump doesn't actually affect
  29730. * the geometry of the object, only the lighting. If a normal map is defined
  29731. * this will be ignored.
  29732. *
  29733. * @type {?Texture}
  29734. * @default null
  29735. */
  29736. this.bumpMap = null;
  29737. /**
  29738. * How much the bump map affects the material. Typical range is `[0,1]`.
  29739. *
  29740. * @type {number}
  29741. * @default 1
  29742. */
  29743. this.bumpScale = 1;
  29744. /**
  29745. * The texture to create a normal map. The RGB values affect the surface
  29746. * normal for each pixel fragment and change the way the color is lit. Normal
  29747. * maps do not change the actual shape of the surface, only the lighting. In
  29748. * case the material has a normal map authored using the left handed
  29749. * convention, the `y` component of `normalScale` should be negated to compensate
  29750. * for the different handedness.
  29751. *
  29752. * @type {?Texture}
  29753. * @default null
  29754. */
  29755. this.normalMap = null;
  29756. /**
  29757. * The type of normal map.
  29758. *
  29759. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29760. * @default TangentSpaceNormalMap
  29761. */
  29762. this.normalMapType = TangentSpaceNormalMap;
  29763. /**
  29764. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29765. *
  29766. * @type {Vector2}
  29767. * @default (1,1)
  29768. */
  29769. this.normalScale = new Vector2( 1, 1 );
  29770. /**
  29771. * The displacement map affects the position of the mesh's vertices. Unlike
  29772. * other maps which only affect the light and shade of the material the
  29773. * displaced vertices can cast shadows, block other objects, and otherwise
  29774. * act as real geometry. The displacement texture is an image where the value
  29775. * of each pixel (white being the highest) is mapped against, and
  29776. * repositions, the vertices of the mesh.
  29777. *
  29778. * @type {?Texture}
  29779. * @default null
  29780. */
  29781. this.displacementMap = null;
  29782. /**
  29783. * How much the displacement map affects the mesh (where black is no
  29784. * displacement, and white is maximum displacement). Without a displacement
  29785. * map set, this value is not applied.
  29786. *
  29787. * @type {number}
  29788. * @default 0
  29789. */
  29790. this.displacementScale = 1;
  29791. /**
  29792. * The offset of the displacement map's values on the mesh's vertices.
  29793. * The bias is added to the scaled sample of the displacement map.
  29794. * Without a displacement map set, this value is not applied.
  29795. *
  29796. * @type {number}
  29797. * @default 0
  29798. */
  29799. this.displacementBias = 0;
  29800. /**
  29801. * Specular map used by the material.
  29802. *
  29803. * @type {?Texture}
  29804. * @default null
  29805. */
  29806. this.specularMap = null;
  29807. /**
  29808. * The alpha map is a grayscale texture that controls the opacity across the
  29809. * surface (black: fully transparent; white: fully opaque).
  29810. *
  29811. * Only the color of the texture is used, ignoring the alpha channel if one
  29812. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29813. * when sampling this texture due to the extra bit of precision provided for
  29814. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29815. * luminance/alpha textures will also still work as expected.
  29816. *
  29817. * @type {?Texture}
  29818. * @default null
  29819. */
  29820. this.alphaMap = null;
  29821. /**
  29822. * The environment map.
  29823. *
  29824. * @type {?Texture}
  29825. * @default null
  29826. */
  29827. this.envMap = null;
  29828. /**
  29829. * The rotation of the environment map in radians.
  29830. *
  29831. * @type {Euler}
  29832. * @default (0,0,0)
  29833. */
  29834. this.envMapRotation = new Euler();
  29835. /**
  29836. * How to combine the result of the surface's color with the environment map, if any.
  29837. *
  29838. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29839. * blend between the two colors.
  29840. *
  29841. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29842. * @default MultiplyOperation
  29843. */
  29844. this.combine = MultiplyOperation;
  29845. /**
  29846. * How much the environment map affects the surface.
  29847. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29848. *
  29849. * @type {number}
  29850. * @default 1
  29851. */
  29852. this.reflectivity = 1;
  29853. /**
  29854. * Scales the effect of the environment map by multiplying its color.
  29855. *
  29856. * @type {number}
  29857. * @default 1
  29858. */
  29859. this.envMapIntensity = 1.0;
  29860. /**
  29861. * The index of refraction (IOR) of air (approximately 1) divided by the
  29862. * index of refraction of the material. It is used with environment mapping
  29863. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29864. * The refraction ratio should not exceed `1`.
  29865. *
  29866. * @type {number}
  29867. * @default 0.98
  29868. */
  29869. this.refractionRatio = 0.98;
  29870. /**
  29871. * Renders the geometry as a wireframe.
  29872. *
  29873. * @type {boolean}
  29874. * @default false
  29875. */
  29876. this.wireframe = false;
  29877. /**
  29878. * Controls the thickness of the wireframe.
  29879. *
  29880. * Can only be used with {@link SVGRenderer}.
  29881. *
  29882. * @type {number}
  29883. * @default 1
  29884. */
  29885. this.wireframeLinewidth = 1;
  29886. /**
  29887. * Defines appearance of wireframe ends.
  29888. *
  29889. * Can only be used with {@link SVGRenderer}.
  29890. *
  29891. * @type {('round'|'bevel'|'miter')}
  29892. * @default 'round'
  29893. */
  29894. this.wireframeLinecap = 'round';
  29895. /**
  29896. * Defines appearance of wireframe joints.
  29897. *
  29898. * Can only be used with {@link SVGRenderer}.
  29899. *
  29900. * @type {('round'|'bevel'|'miter')}
  29901. * @default 'round'
  29902. */
  29903. this.wireframeLinejoin = 'round';
  29904. /**
  29905. * Whether the material is rendered with flat shading or not.
  29906. *
  29907. * @type {boolean}
  29908. * @default false
  29909. */
  29910. this.flatShading = false;
  29911. /**
  29912. * Whether the material is affected by fog or not.
  29913. *
  29914. * @type {boolean}
  29915. * @default true
  29916. */
  29917. this.fog = true;
  29918. this.setValues( parameters );
  29919. }
  29920. copy( source ) {
  29921. super.copy( source );
  29922. this.color.copy( source.color );
  29923. this.map = source.map;
  29924. this.lightMap = source.lightMap;
  29925. this.lightMapIntensity = source.lightMapIntensity;
  29926. this.aoMap = source.aoMap;
  29927. this.aoMapIntensity = source.aoMapIntensity;
  29928. this.emissive.copy( source.emissive );
  29929. this.emissiveMap = source.emissiveMap;
  29930. this.emissiveIntensity = source.emissiveIntensity;
  29931. this.bumpMap = source.bumpMap;
  29932. this.bumpScale = source.bumpScale;
  29933. this.normalMap = source.normalMap;
  29934. this.normalMapType = source.normalMapType;
  29935. this.normalScale.copy( source.normalScale );
  29936. this.displacementMap = source.displacementMap;
  29937. this.displacementScale = source.displacementScale;
  29938. this.displacementBias = source.displacementBias;
  29939. this.specularMap = source.specularMap;
  29940. this.alphaMap = source.alphaMap;
  29941. this.envMap = source.envMap;
  29942. this.envMapRotation.copy( source.envMapRotation );
  29943. this.combine = source.combine;
  29944. this.reflectivity = source.reflectivity;
  29945. this.envMapIntensity = source.envMapIntensity;
  29946. this.refractionRatio = source.refractionRatio;
  29947. this.wireframe = source.wireframe;
  29948. this.wireframeLinewidth = source.wireframeLinewidth;
  29949. this.wireframeLinecap = source.wireframeLinecap;
  29950. this.wireframeLinejoin = source.wireframeLinejoin;
  29951. this.flatShading = source.flatShading;
  29952. this.fog = source.fog;
  29953. return this;
  29954. }
  29955. }
  29956. /**
  29957. * A material for drawing geometry by depth. Depth is based off of the camera
  29958. * near and far plane. White is nearest, black is farthest.
  29959. *
  29960. * @augments Material
  29961. * @demo scenes/material-browser.html#MeshDepthMaterial
  29962. */
  29963. class MeshDepthMaterial extends Material {
  29964. /**
  29965. * Constructs a new mesh depth material.
  29966. *
  29967. * @param {Object} [parameters] - An object with one or more properties
  29968. * defining the material's appearance. Any property of the material
  29969. * (including any property from inherited materials) can be passed
  29970. * in here. Color values can be passed any type of value accepted
  29971. * by {@link Color#set}.
  29972. */
  29973. constructor( parameters ) {
  29974. super();
  29975. /**
  29976. * This flag can be used for type testing.
  29977. *
  29978. * @type {boolean}
  29979. * @readonly
  29980. * @default true
  29981. */
  29982. this.isMeshDepthMaterial = true;
  29983. this.type = 'MeshDepthMaterial';
  29984. /**
  29985. * Type for depth packing.
  29986. *
  29987. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29988. * @default BasicDepthPacking
  29989. */
  29990. this.depthPacking = BasicDepthPacking;
  29991. /**
  29992. * The color map. May optionally include an alpha channel, typically combined
  29993. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29994. *
  29995. * @type {?Texture}
  29996. * @default null
  29997. */
  29998. this.map = null;
  29999. /**
  30000. * The alpha map is a grayscale texture that controls the opacity across the
  30001. * surface (black: fully transparent; white: fully opaque).
  30002. *
  30003. * Only the color of the texture is used, ignoring the alpha channel if one
  30004. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30005. * when sampling this texture due to the extra bit of precision provided for
  30006. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30007. * luminance/alpha textures will also still work as expected.
  30008. *
  30009. * @type {?Texture}
  30010. * @default null
  30011. */
  30012. this.alphaMap = null;
  30013. /**
  30014. * The displacement map affects the position of the mesh's vertices. Unlike
  30015. * other maps which only affect the light and shade of the material the
  30016. * displaced vertices can cast shadows, block other objects, and otherwise
  30017. * act as real geometry. The displacement texture is an image where the value
  30018. * of each pixel (white being the highest) is mapped against, and
  30019. * repositions, the vertices of the mesh.
  30020. *
  30021. * @type {?Texture}
  30022. * @default null
  30023. */
  30024. this.displacementMap = null;
  30025. /**
  30026. * How much the displacement map affects the mesh (where black is no
  30027. * displacement, and white is maximum displacement). Without a displacement
  30028. * map set, this value is not applied.
  30029. *
  30030. * @type {number}
  30031. * @default 0
  30032. */
  30033. this.displacementScale = 1;
  30034. /**
  30035. * The offset of the displacement map's values on the mesh's vertices.
  30036. * The bias is added to the scaled sample of the displacement map.
  30037. * Without a displacement map set, this value is not applied.
  30038. *
  30039. * @type {number}
  30040. * @default 0
  30041. */
  30042. this.displacementBias = 0;
  30043. /**
  30044. * Renders the geometry as a wireframe.
  30045. *
  30046. * @type {boolean}
  30047. * @default false
  30048. */
  30049. this.wireframe = false;
  30050. /**
  30051. * Controls the thickness of the wireframe.
  30052. *
  30053. * WebGL and WebGPU ignore this property and always render
  30054. * 1 pixel wide lines.
  30055. *
  30056. * @type {number}
  30057. * @default 1
  30058. */
  30059. this.wireframeLinewidth = 1;
  30060. this.setValues( parameters );
  30061. }
  30062. copy( source ) {
  30063. super.copy( source );
  30064. this.depthPacking = source.depthPacking;
  30065. this.map = source.map;
  30066. this.alphaMap = source.alphaMap;
  30067. this.displacementMap = source.displacementMap;
  30068. this.displacementScale = source.displacementScale;
  30069. this.displacementBias = source.displacementBias;
  30070. this.wireframe = source.wireframe;
  30071. this.wireframeLinewidth = source.wireframeLinewidth;
  30072. return this;
  30073. }
  30074. }
  30075. /**
  30076. * A material used internally for implementing shadow mapping with
  30077. * point lights.
  30078. *
  30079. * Can also be used to customize the shadow casting of an object by assigning
  30080. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  30081. * The following examples demonstrates this approach in order to ensure
  30082. * transparent parts of objects do not cast shadows.
  30083. *
  30084. * @augments Material
  30085. */
  30086. class MeshDistanceMaterial extends Material {
  30087. /**
  30088. * Constructs a new mesh distance material.
  30089. *
  30090. * @param {Object} [parameters] - An object with one or more properties
  30091. * defining the material's appearance. Any property of the material
  30092. * (including any property from inherited materials) can be passed
  30093. * in here. Color values can be passed any type of value accepted
  30094. * by {@link Color#set}.
  30095. */
  30096. constructor( parameters ) {
  30097. super();
  30098. /**
  30099. * This flag can be used for type testing.
  30100. *
  30101. * @type {boolean}
  30102. * @readonly
  30103. * @default true
  30104. */
  30105. this.isMeshDistanceMaterial = true;
  30106. this.type = 'MeshDistanceMaterial';
  30107. /**
  30108. * The color map. May optionally include an alpha channel, typically combined
  30109. * with {@link Material#transparent} or {@link Material#alphaTest}.
  30110. *
  30111. * @type {?Texture}
  30112. * @default null
  30113. */
  30114. this.map = null;
  30115. /**
  30116. * The alpha map is a grayscale texture that controls the opacity across the
  30117. * surface (black: fully transparent; white: fully opaque).
  30118. *
  30119. * Only the color of the texture is used, ignoring the alpha channel if one
  30120. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30121. * when sampling this texture due to the extra bit of precision provided for
  30122. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30123. * luminance/alpha textures will also still work as expected.
  30124. *
  30125. * @type {?Texture}
  30126. * @default null
  30127. */
  30128. this.alphaMap = null;
  30129. /**
  30130. * The displacement map affects the position of the mesh's vertices. Unlike
  30131. * other maps which only affect the light and shade of the material the
  30132. * displaced vertices can cast shadows, block other objects, and otherwise
  30133. * act as real geometry. The displacement texture is an image where the value
  30134. * of each pixel (white being the highest) is mapped against, and
  30135. * repositions, the vertices of the mesh.
  30136. *
  30137. * @type {?Texture}
  30138. * @default null
  30139. */
  30140. this.displacementMap = null;
  30141. /**
  30142. * How much the displacement map affects the mesh (where black is no
  30143. * displacement, and white is maximum displacement). Without a displacement
  30144. * map set, this value is not applied.
  30145. *
  30146. * @type {number}
  30147. * @default 0
  30148. */
  30149. this.displacementScale = 1;
  30150. /**
  30151. * The offset of the displacement map's values on the mesh's vertices.
  30152. * The bias is added to the scaled sample of the displacement map.
  30153. * Without a displacement map set, this value is not applied.
  30154. *
  30155. * @type {number}
  30156. * @default 0
  30157. */
  30158. this.displacementBias = 0;
  30159. this.setValues( parameters );
  30160. }
  30161. copy( source ) {
  30162. super.copy( source );
  30163. this.map = source.map;
  30164. this.alphaMap = source.alphaMap;
  30165. this.displacementMap = source.displacementMap;
  30166. this.displacementScale = source.displacementScale;
  30167. this.displacementBias = source.displacementBias;
  30168. return this;
  30169. }
  30170. }
  30171. /**
  30172. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  30173. * material color and shading.
  30174. *
  30175. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  30176. * baked lighting. It will cast a shadow onto an object that receives shadows
  30177. * (and shadow clipping works), but it will not self-shadow or receive
  30178. * shadows.
  30179. *
  30180. * @augments Material
  30181. * @demo scenes/material-browser.html#MeshMatcapMaterial
  30182. */
  30183. class MeshMatcapMaterial extends Material {
  30184. /**
  30185. * Constructs a new mesh matcap material.
  30186. *
  30187. * @param {Object} [parameters] - An object with one or more properties
  30188. * defining the material's appearance. Any property of the material
  30189. * (including any property from inherited materials) can be passed
  30190. * in here. Color values can be passed any type of value accepted
  30191. * by {@link Color#set}.
  30192. */
  30193. constructor( parameters ) {
  30194. super();
  30195. /**
  30196. * This flag can be used for type testing.
  30197. *
  30198. * @type {boolean}
  30199. * @readonly
  30200. * @default true
  30201. */
  30202. this.isMeshMatcapMaterial = true;
  30203. this.defines = { 'MATCAP': '' };
  30204. this.type = 'MeshMatcapMaterial';
  30205. /**
  30206. * Color of the material.
  30207. *
  30208. * @type {Color}
  30209. * @default (1,1,1)
  30210. */
  30211. this.color = new Color( 0xffffff ); // diffuse
  30212. /**
  30213. * The matcap map.
  30214. *
  30215. * @type {?Texture}
  30216. * @default null
  30217. */
  30218. this.matcap = null;
  30219. /**
  30220. * The color map. May optionally include an alpha channel, typically combined
  30221. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  30222. * color is modulated by the diffuse `color`.
  30223. *
  30224. * @type {?Texture}
  30225. * @default null
  30226. */
  30227. this.map = null;
  30228. /**
  30229. * The texture to create a bump map. The black and white values map to the
  30230. * perceived depth in relation to the lights. Bump doesn't actually affect
  30231. * the geometry of the object, only the lighting. If a normal map is defined
  30232. * this will be ignored.
  30233. *
  30234. * @type {?Texture}
  30235. * @default null
  30236. */
  30237. this.bumpMap = null;
  30238. /**
  30239. * How much the bump map affects the material. Typical range is `[0,1]`.
  30240. *
  30241. * @type {number}
  30242. * @default 1
  30243. */
  30244. this.bumpScale = 1;
  30245. /**
  30246. * The texture to create a normal map. The RGB values affect the surface
  30247. * normal for each pixel fragment and change the way the color is lit. Normal
  30248. * maps do not change the actual shape of the surface, only the lighting. In
  30249. * case the material has a normal map authored using the left handed
  30250. * convention, the `y` component of `normalScale` should be negated to compensate
  30251. * for the different handedness.
  30252. *
  30253. * @type {?Texture}
  30254. * @default null
  30255. */
  30256. this.normalMap = null;
  30257. /**
  30258. * The type of normal map.
  30259. *
  30260. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  30261. * @default TangentSpaceNormalMap
  30262. */
  30263. this.normalMapType = TangentSpaceNormalMap;
  30264. /**
  30265. * How much the normal map affects the material. Typical value range is `[0,1]`.
  30266. *
  30267. * @type {Vector2}
  30268. * @default (1,1)
  30269. */
  30270. this.normalScale = new Vector2( 1, 1 );
  30271. /**
  30272. * The displacement map affects the position of the mesh's vertices. Unlike
  30273. * other maps which only affect the light and shade of the material the
  30274. * displaced vertices can cast shadows, block other objects, and otherwise
  30275. * act as real geometry. The displacement texture is an image where the value
  30276. * of each pixel (white being the highest) is mapped against, and
  30277. * repositions, the vertices of the mesh.
  30278. *
  30279. * @type {?Texture}
  30280. * @default null
  30281. */
  30282. this.displacementMap = null;
  30283. /**
  30284. * How much the displacement map affects the mesh (where black is no
  30285. * displacement, and white is maximum displacement). Without a displacement
  30286. * map set, this value is not applied.
  30287. *
  30288. * @type {number}
  30289. * @default 0
  30290. */
  30291. this.displacementScale = 1;
  30292. /**
  30293. * The offset of the displacement map's values on the mesh's vertices.
  30294. * The bias is added to the scaled sample of the displacement map.
  30295. * Without a displacement map set, this value is not applied.
  30296. *
  30297. * @type {number}
  30298. * @default 0
  30299. */
  30300. this.displacementBias = 0;
  30301. /**
  30302. * The alpha map is a grayscale texture that controls the opacity across the
  30303. * surface (black: fully transparent; white: fully opaque).
  30304. *
  30305. * Only the color of the texture is used, ignoring the alpha channel if one
  30306. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30307. * when sampling this texture due to the extra bit of precision provided for
  30308. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30309. * luminance/alpha textures will also still work as expected.
  30310. *
  30311. * @type {?Texture}
  30312. * @default null
  30313. */
  30314. this.alphaMap = null;
  30315. /**
  30316. * Renders the geometry as a wireframe.
  30317. *
  30318. * @type {boolean}
  30319. * @default false
  30320. */
  30321. this.wireframe = false;
  30322. /**
  30323. * Controls the thickness of the wireframe.
  30324. *
  30325. * Can only be used with {@link SVGRenderer}.
  30326. *
  30327. * @type {number}
  30328. * @default 1
  30329. */
  30330. this.wireframeLinewidth = 1;
  30331. /**
  30332. * Whether the material is rendered with flat shading or not.
  30333. *
  30334. * @type {boolean}
  30335. * @default false
  30336. */
  30337. this.flatShading = false;
  30338. /**
  30339. * Whether the material is affected by fog or not.
  30340. *
  30341. * @type {boolean}
  30342. * @default true
  30343. */
  30344. this.fog = true;
  30345. this.setValues( parameters );
  30346. }
  30347. copy( source ) {
  30348. super.copy( source );
  30349. this.defines = { 'MATCAP': '' };
  30350. this.color.copy( source.color );
  30351. this.matcap = source.matcap;
  30352. this.map = source.map;
  30353. this.bumpMap = source.bumpMap;
  30354. this.bumpScale = source.bumpScale;
  30355. this.normalMap = source.normalMap;
  30356. this.normalMapType = source.normalMapType;
  30357. this.normalScale.copy( source.normalScale );
  30358. this.displacementMap = source.displacementMap;
  30359. this.displacementScale = source.displacementScale;
  30360. this.displacementBias = source.displacementBias;
  30361. this.alphaMap = source.alphaMap;
  30362. this.wireframe = source.wireframe;
  30363. this.wireframeLinewidth = source.wireframeLinewidth;
  30364. this.flatShading = source.flatShading;
  30365. this.fog = source.fog;
  30366. return this;
  30367. }
  30368. }
  30369. /**
  30370. * A material for rendering line primitives.
  30371. *
  30372. * Materials define the appearance of renderable 3D objects.
  30373. *
  30374. * ```js
  30375. * const material = new THREE.LineDashedMaterial( {
  30376. * color: 0xffffff,
  30377. * scale: 1,
  30378. * dashSize: 3,
  30379. * gapSize: 1,
  30380. * } );
  30381. * ```
  30382. *
  30383. * @augments LineBasicMaterial
  30384. */
  30385. class LineDashedMaterial extends LineBasicMaterial {
  30386. /**
  30387. * Constructs a new line dashed material.
  30388. *
  30389. * @param {Object} [parameters] - An object with one or more properties
  30390. * defining the material's appearance. Any property of the material
  30391. * (including any property from inherited materials) can be passed
  30392. * in here. Color values can be passed any type of value accepted
  30393. * by {@link Color#set}.
  30394. */
  30395. constructor( parameters ) {
  30396. super();
  30397. /**
  30398. * This flag can be used for type testing.
  30399. *
  30400. * @type {boolean}
  30401. * @readonly
  30402. * @default true
  30403. */
  30404. this.isLineDashedMaterial = true;
  30405. this.type = 'LineDashedMaterial';
  30406. /**
  30407. * The scale of the dashed part of a line.
  30408. *
  30409. * @type {number}
  30410. * @default 1
  30411. */
  30412. this.scale = 1;
  30413. /**
  30414. * The size of the dash. This is both the gap with the stroke.
  30415. *
  30416. * @type {number}
  30417. * @default 3
  30418. */
  30419. this.dashSize = 3;
  30420. /**
  30421. * The size of the gap.
  30422. *
  30423. * @type {number}
  30424. * @default 1
  30425. */
  30426. this.gapSize = 1;
  30427. this.setValues( parameters );
  30428. }
  30429. copy( source ) {
  30430. super.copy( source );
  30431. this.scale = source.scale;
  30432. this.dashSize = source.dashSize;
  30433. this.gapSize = source.gapSize;
  30434. return this;
  30435. }
  30436. }
  30437. /**
  30438. * Converts an array to a specific type.
  30439. *
  30440. * @param {TypedArray|Array} array - The array to convert.
  30441. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30442. * @return {TypedArray} The converted array.
  30443. */
  30444. function convertArray( array, type ) {
  30445. if ( ! array || array.constructor === type ) return array;
  30446. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30447. return new type( array ); // create typed array
  30448. }
  30449. return Array.prototype.slice.call( array ); // create Array
  30450. }
  30451. /**
  30452. * Returns an array by which times and values can be sorted.
  30453. *
  30454. * @param {Array<number>} times - The keyframe time values.
  30455. * @return {Array<number>} The array.
  30456. */
  30457. function getKeyframeOrder( times ) {
  30458. function compareTime( i, j ) {
  30459. return times[ i ] - times[ j ];
  30460. }
  30461. const n = times.length;
  30462. const result = new Array( n );
  30463. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30464. result.sort( compareTime );
  30465. return result;
  30466. }
  30467. /**
  30468. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30469. *
  30470. * @param {Array<number>} values - The values to sort.
  30471. * @param {number} stride - The stride.
  30472. * @param {Array<number>} order - The sort order.
  30473. * @return {Array<number>} The sorted values.
  30474. */
  30475. function sortedArray( values, stride, order ) {
  30476. const nValues = values.length;
  30477. const result = new values.constructor( nValues );
  30478. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30479. const srcOffset = order[ i ] * stride;
  30480. for ( let j = 0; j !== stride; ++ j ) {
  30481. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30482. }
  30483. }
  30484. return result;
  30485. }
  30486. /**
  30487. * Used for parsing AOS keyframe formats.
  30488. *
  30489. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30490. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30491. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30492. * @param {string} valuePropertyName - The name of the property to use.
  30493. */
  30494. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30495. let i = 1, key = jsonKeys[ 0 ];
  30496. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30497. key = jsonKeys[ i ++ ];
  30498. }
  30499. if ( key === undefined ) return; // no data
  30500. let value = key[ valuePropertyName ];
  30501. if ( value === undefined ) return; // no data
  30502. if ( Array.isArray( value ) ) {
  30503. do {
  30504. value = key[ valuePropertyName ];
  30505. if ( value !== undefined ) {
  30506. times.push( key.time );
  30507. values.push( ...value ); // push all elements
  30508. }
  30509. key = jsonKeys[ i ++ ];
  30510. } while ( key !== undefined );
  30511. } else if ( value.toArray !== undefined ) {
  30512. // ...assume THREE.Math-ish
  30513. do {
  30514. value = key[ valuePropertyName ];
  30515. if ( value !== undefined ) {
  30516. times.push( key.time );
  30517. value.toArray( values, values.length );
  30518. }
  30519. key = jsonKeys[ i ++ ];
  30520. } while ( key !== undefined );
  30521. } else {
  30522. // otherwise push as-is
  30523. do {
  30524. value = key[ valuePropertyName ];
  30525. if ( value !== undefined ) {
  30526. times.push( key.time );
  30527. values.push( value );
  30528. }
  30529. key = jsonKeys[ i ++ ];
  30530. } while ( key !== undefined );
  30531. }
  30532. }
  30533. /**
  30534. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30535. *
  30536. * @param {AnimationClip} sourceClip - The values to sort.
  30537. * @param {string} name - The name of the clip.
  30538. * @param {number} startFrame - The start frame.
  30539. * @param {number} endFrame - The end frame.
  30540. * @param {number} [fps=30] - The FPS.
  30541. * @return {AnimationClip} The new sub clip.
  30542. */
  30543. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30544. const clip = sourceClip.clone();
  30545. clip.name = name;
  30546. const tracks = [];
  30547. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30548. const track = clip.tracks[ i ];
  30549. const valueSize = track.getValueSize();
  30550. const times = [];
  30551. const values = [];
  30552. for ( let j = 0; j < track.times.length; ++ j ) {
  30553. const frame = track.times[ j ] * fps;
  30554. if ( frame < startFrame || frame >= endFrame ) continue;
  30555. times.push( track.times[ j ] );
  30556. for ( let k = 0; k < valueSize; ++ k ) {
  30557. values.push( track.values[ j * valueSize + k ] );
  30558. }
  30559. }
  30560. if ( times.length === 0 ) continue;
  30561. track.times = convertArray( times, track.times.constructor );
  30562. track.values = convertArray( values, track.values.constructor );
  30563. tracks.push( track );
  30564. }
  30565. clip.tracks = tracks;
  30566. // find minimum .times value across all tracks in the trimmed clip
  30567. let minStartTime = Infinity;
  30568. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30569. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30570. minStartTime = clip.tracks[ i ].times[ 0 ];
  30571. }
  30572. }
  30573. // shift all tracks such that clip begins at t=0
  30574. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30575. clip.tracks[ i ].shift( -1 * minStartTime );
  30576. }
  30577. clip.resetDuration();
  30578. return clip;
  30579. }
  30580. /**
  30581. * Converts the keyframes of the given animation clip to an additive format.
  30582. *
  30583. * @param {AnimationClip} targetClip - The clip to make additive.
  30584. * @param {number} [referenceFrame=0] - The reference frame.
  30585. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30586. * @param {number} [fps=30] - The FPS.
  30587. * @return {AnimationClip} The updated clip which is now additive.
  30588. */
  30589. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30590. if ( fps <= 0 ) fps = 30;
  30591. const numTracks = referenceClip.tracks.length;
  30592. const referenceTime = referenceFrame / fps;
  30593. // Make each track's values relative to the values at the reference frame
  30594. for ( let i = 0; i < numTracks; ++ i ) {
  30595. const referenceTrack = referenceClip.tracks[ i ];
  30596. const referenceTrackType = referenceTrack.ValueTypeName;
  30597. // Skip this track if it's non-numeric
  30598. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30599. // Find the track in the target clip whose name and type matches the reference track
  30600. const targetTrack = targetClip.tracks.find( function ( track ) {
  30601. return track.name === referenceTrack.name
  30602. && track.ValueTypeName === referenceTrackType;
  30603. } );
  30604. if ( targetTrack === undefined ) continue;
  30605. let referenceOffset = 0;
  30606. const referenceValueSize = referenceTrack.getValueSize();
  30607. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30608. referenceOffset = referenceValueSize / 3;
  30609. }
  30610. let targetOffset = 0;
  30611. const targetValueSize = targetTrack.getValueSize();
  30612. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30613. targetOffset = targetValueSize / 3;
  30614. }
  30615. const lastIndex = referenceTrack.times.length - 1;
  30616. let referenceValue;
  30617. // Find the value to subtract out of the track
  30618. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30619. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30620. const startIndex = referenceOffset;
  30621. const endIndex = referenceValueSize - referenceOffset;
  30622. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30623. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30624. // Reference frame is after the last keyframe, so just use the last keyframe
  30625. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30626. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30627. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30628. } else {
  30629. // Interpolate to the reference value
  30630. const interpolant = referenceTrack.createInterpolant();
  30631. const startIndex = referenceOffset;
  30632. const endIndex = referenceValueSize - referenceOffset;
  30633. interpolant.evaluate( referenceTime );
  30634. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30635. }
  30636. // Conjugate the quaternion
  30637. if ( referenceTrackType === 'quaternion' ) {
  30638. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30639. referenceQuat.toArray( referenceValue );
  30640. }
  30641. // Subtract the reference value from all of the track values
  30642. const numTimes = targetTrack.times.length;
  30643. for ( let j = 0; j < numTimes; ++ j ) {
  30644. const valueStart = j * targetValueSize + targetOffset;
  30645. if ( referenceTrackType === 'quaternion' ) {
  30646. // Multiply the conjugate for quaternion track types
  30647. Quaternion.multiplyQuaternionsFlat(
  30648. targetTrack.values,
  30649. valueStart,
  30650. referenceValue,
  30651. 0,
  30652. targetTrack.values,
  30653. valueStart
  30654. );
  30655. } else {
  30656. const valueEnd = targetValueSize - targetOffset * 2;
  30657. // Subtract each value for all other numeric track types
  30658. for ( let k = 0; k < valueEnd; ++ k ) {
  30659. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30660. }
  30661. }
  30662. }
  30663. }
  30664. targetClip.blendMode = AdditiveAnimationBlendMode;
  30665. return targetClip;
  30666. }
  30667. /**
  30668. * A class with various methods to assist with animations.
  30669. *
  30670. * @hideconstructor
  30671. */
  30672. class AnimationUtils {
  30673. /**
  30674. * Converts an array to a specific type
  30675. *
  30676. * @static
  30677. * @param {TypedArray|Array} array - The array to convert.
  30678. * @param {TypedArray.constructor} type - The constructor of a type array.
  30679. * @return {TypedArray} The converted array
  30680. */
  30681. static convertArray( array, type ) {
  30682. return convertArray( array, type );
  30683. }
  30684. /**
  30685. * Returns `true` if the given object is a typed array.
  30686. *
  30687. * @static
  30688. * @param {any} object - The object to check.
  30689. * @return {boolean} Whether the given object is a typed array.
  30690. */
  30691. static isTypedArray( object ) {
  30692. return isTypedArray( object );
  30693. }
  30694. /**
  30695. * Returns an array by which times and values can be sorted.
  30696. *
  30697. * @static
  30698. * @param {Array<number>} times - The keyframe time values.
  30699. * @return {Array<number>} The array.
  30700. */
  30701. static getKeyframeOrder( times ) {
  30702. return getKeyframeOrder( times );
  30703. }
  30704. /**
  30705. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30706. *
  30707. * @static
  30708. * @param {Array<number>} values - The values to sort.
  30709. * @param {number} stride - The stride.
  30710. * @param {Array<number>} order - The sort order.
  30711. * @return {Array<number>} The sorted values.
  30712. */
  30713. static sortedArray( values, stride, order ) {
  30714. return sortedArray( values, stride, order );
  30715. }
  30716. /**
  30717. * Used for parsing AOS keyframe formats.
  30718. *
  30719. * @static
  30720. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30721. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30722. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30723. * @param {string} valuePropertyName - The name of the property to use.
  30724. */
  30725. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30726. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30727. }
  30728. /**
  30729. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30730. *
  30731. * @static
  30732. * @param {AnimationClip} sourceClip - The values to sort.
  30733. * @param {string} name - The name of the clip.
  30734. * @param {number} startFrame - The start frame.
  30735. * @param {number} endFrame - The end frame.
  30736. * @param {number} [fps=30] - The FPS.
  30737. * @return {AnimationClip} The new sub clip.
  30738. */
  30739. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30740. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30741. }
  30742. /**
  30743. * Converts the keyframes of the given animation clip to an additive format.
  30744. *
  30745. * @static
  30746. * @param {AnimationClip} targetClip - The clip to make additive.
  30747. * @param {number} [referenceFrame=0] - The reference frame.
  30748. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30749. * @param {number} [fps=30] - The FPS.
  30750. * @return {AnimationClip} The updated clip which is now additive.
  30751. */
  30752. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30753. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30754. }
  30755. }
  30756. /**
  30757. * Abstract base class of interpolants over parametric samples.
  30758. *
  30759. * The parameter domain is one dimensional, typically the time or a path
  30760. * along a curve defined by the data.
  30761. *
  30762. * The sample values can have any dimensionality and derived classes may
  30763. * apply special interpretations to the data.
  30764. *
  30765. * This class provides the interval seek in a Template Method, deferring
  30766. * the actual interpolation to derived classes.
  30767. *
  30768. * Time complexity is O(1) for linear access crossing at most two points
  30769. * and O(log N) for random access, where N is the number of positions.
  30770. *
  30771. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30772. *
  30773. * @abstract
  30774. */
  30775. class Interpolant {
  30776. /**
  30777. * Constructs a new interpolant.
  30778. *
  30779. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30780. * @param {TypedArray} sampleValues - The sample values.
  30781. * @param {number} sampleSize - The sample size
  30782. * @param {TypedArray} [resultBuffer] - The result buffer.
  30783. */
  30784. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30785. /**
  30786. * The parameter positions.
  30787. *
  30788. * @type {TypedArray}
  30789. */
  30790. this.parameterPositions = parameterPositions;
  30791. /**
  30792. * A cache index.
  30793. *
  30794. * @private
  30795. * @type {number}
  30796. * @default 0
  30797. */
  30798. this._cachedIndex = 0;
  30799. /**
  30800. * The result buffer.
  30801. *
  30802. * @type {TypedArray}
  30803. */
  30804. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30805. /**
  30806. * The sample values.
  30807. *
  30808. * @type {TypedArray}
  30809. */
  30810. this.sampleValues = sampleValues;
  30811. /**
  30812. * The value size.
  30813. *
  30814. * @type {TypedArray}
  30815. */
  30816. this.valueSize = sampleSize;
  30817. /**
  30818. * The interpolation settings.
  30819. *
  30820. * @type {?Object}
  30821. * @default null
  30822. */
  30823. this.settings = null;
  30824. /**
  30825. * The default settings object.
  30826. *
  30827. * @type {Object}
  30828. */
  30829. this.DefaultSettings_ = {};
  30830. }
  30831. /**
  30832. * Evaluate the interpolant at position `t`.
  30833. *
  30834. * @param {number} t - The interpolation factor.
  30835. * @return {TypedArray} The result buffer.
  30836. */
  30837. evaluate( t ) {
  30838. const pp = this.parameterPositions;
  30839. let i1 = this._cachedIndex,
  30840. t1 = pp[ i1 ],
  30841. t0 = pp[ i1 - 1 ];
  30842. validate_interval: {
  30843. seek: {
  30844. let right;
  30845. linear_scan: {
  30846. //- See http://jsperf.com/comparison-to-undefined/3
  30847. //- slower code:
  30848. //-
  30849. //- if ( t >= t1 || t1 === undefined ) {
  30850. forward_scan: if ( ! ( t < t1 ) ) {
  30851. for ( let giveUpAt = i1 + 2; ; ) {
  30852. if ( t1 === undefined ) {
  30853. if ( t < t0 ) break forward_scan;
  30854. // after end
  30855. i1 = pp.length;
  30856. this._cachedIndex = i1;
  30857. return this.copySampleValue_( i1 - 1 );
  30858. }
  30859. if ( i1 === giveUpAt ) break; // this loop
  30860. t0 = t1;
  30861. t1 = pp[ ++ i1 ];
  30862. if ( t < t1 ) {
  30863. // we have arrived at the sought interval
  30864. break seek;
  30865. }
  30866. }
  30867. // prepare binary search on the right side of the index
  30868. right = pp.length;
  30869. break linear_scan;
  30870. }
  30871. //- slower code:
  30872. //- if ( t < t0 || t0 === undefined ) {
  30873. if ( ! ( t >= t0 ) ) {
  30874. // looping?
  30875. const t1global = pp[ 1 ];
  30876. if ( t < t1global ) {
  30877. i1 = 2; // + 1, using the scan for the details
  30878. t0 = t1global;
  30879. }
  30880. // linear reverse scan
  30881. for ( let giveUpAt = i1 - 2; ; ) {
  30882. if ( t0 === undefined ) {
  30883. // before start
  30884. this._cachedIndex = 0;
  30885. return this.copySampleValue_( 0 );
  30886. }
  30887. if ( i1 === giveUpAt ) break; // this loop
  30888. t1 = t0;
  30889. t0 = pp[ -- i1 - 1 ];
  30890. if ( t >= t0 ) {
  30891. // we have arrived at the sought interval
  30892. break seek;
  30893. }
  30894. }
  30895. // prepare binary search on the left side of the index
  30896. right = i1;
  30897. i1 = 0;
  30898. break linear_scan;
  30899. }
  30900. // the interval is valid
  30901. break validate_interval;
  30902. } // linear scan
  30903. // binary search
  30904. while ( i1 < right ) {
  30905. const mid = ( i1 + right ) >>> 1;
  30906. if ( t < pp[ mid ] ) {
  30907. right = mid;
  30908. } else {
  30909. i1 = mid + 1;
  30910. }
  30911. }
  30912. t1 = pp[ i1 ];
  30913. t0 = pp[ i1 - 1 ];
  30914. // check boundary cases, again
  30915. if ( t0 === undefined ) {
  30916. this._cachedIndex = 0;
  30917. return this.copySampleValue_( 0 );
  30918. }
  30919. if ( t1 === undefined ) {
  30920. i1 = pp.length;
  30921. this._cachedIndex = i1;
  30922. return this.copySampleValue_( i1 - 1 );
  30923. }
  30924. } // seek
  30925. this._cachedIndex = i1;
  30926. this.intervalChanged_( i1, t0, t1 );
  30927. } // validate_interval
  30928. return this.interpolate_( i1, t0, t, t1 );
  30929. }
  30930. /**
  30931. * Returns the interpolation settings.
  30932. *
  30933. * @return {Object} The interpolation settings.
  30934. */
  30935. getSettings_() {
  30936. return this.settings || this.DefaultSettings_;
  30937. }
  30938. /**
  30939. * Copies a sample value to the result buffer.
  30940. *
  30941. * @param {number} index - An index into the sample value buffer.
  30942. * @return {TypedArray} The result buffer.
  30943. */
  30944. copySampleValue_( index ) {
  30945. // copies a sample value to the result buffer
  30946. const result = this.resultBuffer,
  30947. values = this.sampleValues,
  30948. stride = this.valueSize,
  30949. offset = index * stride;
  30950. for ( let i = 0; i !== stride; ++ i ) {
  30951. result[ i ] = values[ offset + i ];
  30952. }
  30953. return result;
  30954. }
  30955. /**
  30956. * Copies a sample value to the result buffer.
  30957. *
  30958. * @abstract
  30959. * @param {number} i1 - An index into the sample value buffer.
  30960. * @param {number} t0 - The previous interpolation factor.
  30961. * @param {number} t - The current interpolation factor.
  30962. * @param {number} t1 - The next interpolation factor.
  30963. * @return {TypedArray} The result buffer.
  30964. */
  30965. interpolate_( /* i1, t0, t, t1 */ ) {
  30966. throw new Error( 'call to abstract method' );
  30967. // implementations shall return this.resultBuffer
  30968. }
  30969. /**
  30970. * Optional method that is executed when the interval has changed.
  30971. *
  30972. * @param {number} i1 - An index into the sample value buffer.
  30973. * @param {number} t0 - The previous interpolation factor.
  30974. * @param {number} t - The current interpolation factor.
  30975. */
  30976. intervalChanged_( /* i1, t0, t1 */ ) {
  30977. // empty
  30978. }
  30979. }
  30980. /**
  30981. * Fast and simple cubic spline interpolant.
  30982. *
  30983. * It was derived from a Hermitian construction setting the first derivative
  30984. * at each sample position to the linear slope between neighboring positions
  30985. * over their parameter interval.
  30986. *
  30987. * @augments Interpolant
  30988. */
  30989. class CubicInterpolant extends Interpolant {
  30990. /**
  30991. * Constructs a new cubic interpolant.
  30992. *
  30993. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30994. * @param {TypedArray} sampleValues - The sample values.
  30995. * @param {number} sampleSize - The sample size
  30996. * @param {TypedArray} [resultBuffer] - The result buffer.
  30997. */
  30998. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30999. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31000. this._weightPrev = -0;
  31001. this._offsetPrev = -0;
  31002. this._weightNext = -0;
  31003. this._offsetNext = -0;
  31004. this.DefaultSettings_ = {
  31005. endingStart: ZeroCurvatureEnding,
  31006. endingEnd: ZeroCurvatureEnding
  31007. };
  31008. }
  31009. intervalChanged_( i1, t0, t1 ) {
  31010. const pp = this.parameterPositions;
  31011. let iPrev = i1 - 2,
  31012. iNext = i1 + 1,
  31013. tPrev = pp[ iPrev ],
  31014. tNext = pp[ iNext ];
  31015. if ( tPrev === undefined ) {
  31016. switch ( this.getSettings_().endingStart ) {
  31017. case ZeroSlopeEnding:
  31018. // f'(t0) = 0
  31019. iPrev = i1;
  31020. tPrev = 2 * t0 - t1;
  31021. break;
  31022. case WrapAroundEnding:
  31023. // use the other end of the curve
  31024. iPrev = pp.length - 2;
  31025. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  31026. break;
  31027. default: // ZeroCurvatureEnding
  31028. // f''(t0) = 0 a.k.a. Natural Spline
  31029. iPrev = i1;
  31030. tPrev = t1;
  31031. }
  31032. }
  31033. if ( tNext === undefined ) {
  31034. switch ( this.getSettings_().endingEnd ) {
  31035. case ZeroSlopeEnding:
  31036. // f'(tN) = 0
  31037. iNext = i1;
  31038. tNext = 2 * t1 - t0;
  31039. break;
  31040. case WrapAroundEnding:
  31041. // use the other end of the curve
  31042. iNext = 1;
  31043. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  31044. break;
  31045. default: // ZeroCurvatureEnding
  31046. // f''(tN) = 0, a.k.a. Natural Spline
  31047. iNext = i1 - 1;
  31048. tNext = t0;
  31049. }
  31050. }
  31051. const halfDt = ( t1 - t0 ) * 0.5,
  31052. stride = this.valueSize;
  31053. this._weightPrev = halfDt / ( t0 - tPrev );
  31054. this._weightNext = halfDt / ( tNext - t1 );
  31055. this._offsetPrev = iPrev * stride;
  31056. this._offsetNext = iNext * stride;
  31057. }
  31058. interpolate_( i1, t0, t, t1 ) {
  31059. const result = this.resultBuffer,
  31060. values = this.sampleValues,
  31061. stride = this.valueSize,
  31062. o1 = i1 * stride, o0 = o1 - stride,
  31063. oP = this._offsetPrev, oN = this._offsetNext,
  31064. wP = this._weightPrev, wN = this._weightNext,
  31065. p = ( t - t0 ) / ( t1 - t0 ),
  31066. pp = p * p,
  31067. ppp = pp * p;
  31068. // evaluate polynomials
  31069. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  31070. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  31071. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  31072. const sN = wN * ppp - wN * pp;
  31073. // combine data linearly
  31074. for ( let i = 0; i !== stride; ++ i ) {
  31075. result[ i ] =
  31076. sP * values[ oP + i ] +
  31077. s0 * values[ o0 + i ] +
  31078. s1 * values[ o1 + i ] +
  31079. sN * values[ oN + i ];
  31080. }
  31081. return result;
  31082. }
  31083. }
  31084. /**
  31085. * A basic linear interpolant.
  31086. *
  31087. * @augments Interpolant
  31088. */
  31089. class LinearInterpolant extends Interpolant {
  31090. /**
  31091. * Constructs a new linear interpolant.
  31092. *
  31093. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31094. * @param {TypedArray} sampleValues - The sample values.
  31095. * @param {number} sampleSize - The sample size
  31096. * @param {TypedArray} [resultBuffer] - The result buffer.
  31097. */
  31098. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31099. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31100. }
  31101. interpolate_( i1, t0, t, t1 ) {
  31102. const result = this.resultBuffer,
  31103. values = this.sampleValues,
  31104. stride = this.valueSize,
  31105. offset1 = i1 * stride,
  31106. offset0 = offset1 - stride,
  31107. weight1 = ( t - t0 ) / ( t1 - t0 ),
  31108. weight0 = 1 - weight1;
  31109. for ( let i = 0; i !== stride; ++ i ) {
  31110. result[ i ] =
  31111. values[ offset0 + i ] * weight0 +
  31112. values[ offset1 + i ] * weight1;
  31113. }
  31114. return result;
  31115. }
  31116. }
  31117. /**
  31118. * Interpolant that evaluates to the sample value at the position preceding
  31119. * the parameter.
  31120. *
  31121. * @augments Interpolant
  31122. */
  31123. class DiscreteInterpolant extends Interpolant {
  31124. /**
  31125. * Constructs a new discrete interpolant.
  31126. *
  31127. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31128. * @param {TypedArray} sampleValues - The sample values.
  31129. * @param {number} sampleSize - The sample size
  31130. * @param {TypedArray} [resultBuffer] - The result buffer.
  31131. */
  31132. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31133. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31134. }
  31135. interpolate_( i1 /*, t0, t, t1 */ ) {
  31136. return this.copySampleValue_( i1 - 1 );
  31137. }
  31138. }
  31139. /**
  31140. * Represents a timed sequence of keyframes, which are composed of lists of
  31141. * times and related values, and which are used to animate a specific property
  31142. * of an object.
  31143. */
  31144. class KeyframeTrack {
  31145. /**
  31146. * Constructs a new keyframe track.
  31147. *
  31148. * @param {string} name - The keyframe track's name.
  31149. * @param {Array<number>} times - A list of keyframe times.
  31150. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  31151. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31152. */
  31153. constructor( name, times, values, interpolation ) {
  31154. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  31155. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  31156. /**
  31157. * The track's name can refer to morph targets or bones or
  31158. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  31159. * for the forms of strings that can be parsed for property binding.
  31160. *
  31161. * @type {string}
  31162. */
  31163. this.name = name;
  31164. /**
  31165. * The keyframe times.
  31166. *
  31167. * @type {Float32Array}
  31168. */
  31169. this.times = convertArray( times, this.TimeBufferType );
  31170. /**
  31171. * The keyframe values.
  31172. *
  31173. * @type {Float32Array}
  31174. */
  31175. this.values = convertArray( values, this.ValueBufferType );
  31176. this.setInterpolation( interpolation || this.DefaultInterpolation );
  31177. }
  31178. /**
  31179. * Converts the keyframe track to JSON.
  31180. *
  31181. * @static
  31182. * @param {KeyframeTrack} track - The keyframe track to serialize.
  31183. * @return {Object} The serialized keyframe track as JSON.
  31184. */
  31185. static toJSON( track ) {
  31186. const trackType = track.constructor;
  31187. let json;
  31188. // derived classes can define a static toJSON method
  31189. if ( trackType.toJSON !== this.toJSON ) {
  31190. json = trackType.toJSON( track );
  31191. } else {
  31192. // by default, we assume the data can be serialized as-is
  31193. json = {
  31194. 'name': track.name,
  31195. 'times': convertArray( track.times, Array ),
  31196. 'values': convertArray( track.values, Array )
  31197. };
  31198. const interpolation = track.getInterpolation();
  31199. if ( interpolation !== track.DefaultInterpolation ) {
  31200. json.interpolation = interpolation;
  31201. }
  31202. }
  31203. json.type = track.ValueTypeName; // mandatory
  31204. return json;
  31205. }
  31206. /**
  31207. * Factory method for creating a new discrete interpolant.
  31208. *
  31209. * @static
  31210. * @param {TypedArray} [result] - The result buffer.
  31211. * @return {DiscreteInterpolant} The new interpolant.
  31212. */
  31213. InterpolantFactoryMethodDiscrete( result ) {
  31214. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  31215. }
  31216. /**
  31217. * Factory method for creating a new linear interpolant.
  31218. *
  31219. * @static
  31220. * @param {TypedArray} [result] - The result buffer.
  31221. * @return {LinearInterpolant} The new interpolant.
  31222. */
  31223. InterpolantFactoryMethodLinear( result ) {
  31224. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31225. }
  31226. /**
  31227. * Factory method for creating a new smooth interpolant.
  31228. *
  31229. * @static
  31230. * @param {TypedArray} [result] - The result buffer.
  31231. * @return {CubicInterpolant} The new interpolant.
  31232. */
  31233. InterpolantFactoryMethodSmooth( result ) {
  31234. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  31235. }
  31236. /**
  31237. * Defines the interpolation factor method for this keyframe track.
  31238. *
  31239. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  31240. * @return {KeyframeTrack} A reference to this keyframe track.
  31241. */
  31242. setInterpolation( interpolation ) {
  31243. let factoryMethod;
  31244. switch ( interpolation ) {
  31245. case InterpolateDiscrete:
  31246. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  31247. break;
  31248. case InterpolateLinear:
  31249. factoryMethod = this.InterpolantFactoryMethodLinear;
  31250. break;
  31251. case InterpolateSmooth:
  31252. factoryMethod = this.InterpolantFactoryMethodSmooth;
  31253. break;
  31254. }
  31255. if ( factoryMethod === undefined ) {
  31256. const message = 'unsupported interpolation for ' +
  31257. this.ValueTypeName + ' keyframe track named ' + this.name;
  31258. if ( this.createInterpolant === undefined ) {
  31259. // fall back to default, unless the default itself is messed up
  31260. if ( interpolation !== this.DefaultInterpolation ) {
  31261. this.setInterpolation( this.DefaultInterpolation );
  31262. } else {
  31263. throw new Error( message ); // fatal, in this case
  31264. }
  31265. }
  31266. warn( 'KeyframeTrack:', message );
  31267. return this;
  31268. }
  31269. this.createInterpolant = factoryMethod;
  31270. return this;
  31271. }
  31272. /**
  31273. * Returns the current interpolation type.
  31274. *
  31275. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  31276. */
  31277. getInterpolation() {
  31278. switch ( this.createInterpolant ) {
  31279. case this.InterpolantFactoryMethodDiscrete:
  31280. return InterpolateDiscrete;
  31281. case this.InterpolantFactoryMethodLinear:
  31282. return InterpolateLinear;
  31283. case this.InterpolantFactoryMethodSmooth:
  31284. return InterpolateSmooth;
  31285. }
  31286. }
  31287. /**
  31288. * Returns the value size.
  31289. *
  31290. * @return {number} The value size.
  31291. */
  31292. getValueSize() {
  31293. return this.values.length / this.times.length;
  31294. }
  31295. /**
  31296. * Moves all keyframes either forward or backward in time.
  31297. *
  31298. * @param {number} timeOffset - The offset to move the time values.
  31299. * @return {KeyframeTrack} A reference to this keyframe track.
  31300. */
  31301. shift( timeOffset ) {
  31302. if ( timeOffset !== 0.0 ) {
  31303. const times = this.times;
  31304. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31305. times[ i ] += timeOffset;
  31306. }
  31307. }
  31308. return this;
  31309. }
  31310. /**
  31311. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  31312. *
  31313. * @param {number} timeScale - The time scale.
  31314. * @return {KeyframeTrack} A reference to this keyframe track.
  31315. */
  31316. scale( timeScale ) {
  31317. if ( timeScale !== 1.0 ) {
  31318. const times = this.times;
  31319. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31320. times[ i ] *= timeScale;
  31321. }
  31322. }
  31323. return this;
  31324. }
  31325. /**
  31326. * Removes keyframes before and after animation without changing any values within the defined time range.
  31327. *
  31328. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  31329. * keys this will change their values
  31330. *
  31331. * @param {number} startTime - The start time.
  31332. * @param {number} endTime - The end time.
  31333. * @return {KeyframeTrack} A reference to this keyframe track.
  31334. */
  31335. trim( startTime, endTime ) {
  31336. const times = this.times,
  31337. nKeys = times.length;
  31338. let from = 0,
  31339. to = nKeys - 1;
  31340. while ( from !== nKeys && times[ from ] < startTime ) {
  31341. ++ from;
  31342. }
  31343. while ( to !== -1 && times[ to ] > endTime ) {
  31344. -- to;
  31345. }
  31346. ++ to; // inclusive -> exclusive bound
  31347. if ( from !== 0 || to !== nKeys ) {
  31348. // empty tracks are forbidden, so keep at least one keyframe
  31349. if ( from >= to ) {
  31350. to = Math.max( to, 1 );
  31351. from = to - 1;
  31352. }
  31353. const stride = this.getValueSize();
  31354. this.times = times.slice( from, to );
  31355. this.values = this.values.slice( from * stride, to * stride );
  31356. }
  31357. return this;
  31358. }
  31359. /**
  31360. * Performs minimal validation on the keyframe track. Returns `true` if the values
  31361. * are valid.
  31362. *
  31363. * @return {boolean} Whether the keyframes are valid or not.
  31364. */
  31365. validate() {
  31366. let valid = true;
  31367. const valueSize = this.getValueSize();
  31368. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  31369. error( 'KeyframeTrack: Invalid value size in track.', this );
  31370. valid = false;
  31371. }
  31372. const times = this.times,
  31373. values = this.values,
  31374. nKeys = times.length;
  31375. if ( nKeys === 0 ) {
  31376. error( 'KeyframeTrack: Track is empty.', this );
  31377. valid = false;
  31378. }
  31379. let prevTime = null;
  31380. for ( let i = 0; i !== nKeys; i ++ ) {
  31381. const currTime = times[ i ];
  31382. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31383. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31384. valid = false;
  31385. break;
  31386. }
  31387. if ( prevTime !== null && prevTime > currTime ) {
  31388. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31389. valid = false;
  31390. break;
  31391. }
  31392. prevTime = currTime;
  31393. }
  31394. if ( values !== undefined ) {
  31395. if ( isTypedArray( values ) ) {
  31396. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31397. const value = values[ i ];
  31398. if ( isNaN( value ) ) {
  31399. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31400. valid = false;
  31401. break;
  31402. }
  31403. }
  31404. }
  31405. }
  31406. return valid;
  31407. }
  31408. /**
  31409. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31410. * common in morph target sequences).
  31411. *
  31412. * @return {KeyframeTrack} A reference to this keyframe track.
  31413. */
  31414. optimize() {
  31415. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31416. // times or values may be shared with other tracks, so overwriting is unsafe
  31417. const times = this.times.slice(),
  31418. values = this.values.slice(),
  31419. stride = this.getValueSize(),
  31420. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31421. lastIndex = times.length - 1;
  31422. let writeIndex = 1;
  31423. for ( let i = 1; i < lastIndex; ++ i ) {
  31424. let keep = false;
  31425. const time = times[ i ];
  31426. const timeNext = times[ i + 1 ];
  31427. // remove adjacent keyframes scheduled at the same time
  31428. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31429. if ( ! smoothInterpolation ) {
  31430. // remove unnecessary keyframes same as their neighbors
  31431. const offset = i * stride,
  31432. offsetP = offset - stride,
  31433. offsetN = offset + stride;
  31434. for ( let j = 0; j !== stride; ++ j ) {
  31435. const value = values[ offset + j ];
  31436. if ( value !== values[ offsetP + j ] ||
  31437. value !== values[ offsetN + j ] ) {
  31438. keep = true;
  31439. break;
  31440. }
  31441. }
  31442. } else {
  31443. keep = true;
  31444. }
  31445. }
  31446. // in-place compaction
  31447. if ( keep ) {
  31448. if ( i !== writeIndex ) {
  31449. times[ writeIndex ] = times[ i ];
  31450. const readOffset = i * stride,
  31451. writeOffset = writeIndex * stride;
  31452. for ( let j = 0; j !== stride; ++ j ) {
  31453. values[ writeOffset + j ] = values[ readOffset + j ];
  31454. }
  31455. }
  31456. ++ writeIndex;
  31457. }
  31458. }
  31459. // flush last keyframe (compaction looks ahead)
  31460. if ( lastIndex > 0 ) {
  31461. times[ writeIndex ] = times[ lastIndex ];
  31462. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31463. values[ writeOffset + j ] = values[ readOffset + j ];
  31464. }
  31465. ++ writeIndex;
  31466. }
  31467. if ( writeIndex !== times.length ) {
  31468. this.times = times.slice( 0, writeIndex );
  31469. this.values = values.slice( 0, writeIndex * stride );
  31470. } else {
  31471. this.times = times;
  31472. this.values = values;
  31473. }
  31474. return this;
  31475. }
  31476. /**
  31477. * Returns a new keyframe track with copied values from this instance.
  31478. *
  31479. * @return {KeyframeTrack} A clone of this instance.
  31480. */
  31481. clone() {
  31482. const times = this.times.slice();
  31483. const values = this.values.slice();
  31484. const TypedKeyframeTrack = this.constructor;
  31485. const track = new TypedKeyframeTrack( this.name, times, values );
  31486. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31487. track.createInterpolant = this.createInterpolant;
  31488. return track;
  31489. }
  31490. }
  31491. /**
  31492. * The value type name.
  31493. *
  31494. * @type {string}
  31495. * @default ''
  31496. */
  31497. KeyframeTrack.prototype.ValueTypeName = '';
  31498. /**
  31499. * The time buffer type of this keyframe track.
  31500. *
  31501. * @type {TypedArray|Array}
  31502. * @default Float32Array.constructor
  31503. */
  31504. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31505. /**
  31506. * The value buffer type of this keyframe track.
  31507. *
  31508. * @type {TypedArray|Array}
  31509. * @default Float32Array.constructor
  31510. */
  31511. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31512. /**
  31513. * The default interpolation type of this keyframe track.
  31514. *
  31515. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31516. * @default InterpolateLinear
  31517. */
  31518. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31519. /**
  31520. * A track for boolean keyframe values.
  31521. *
  31522. * @augments KeyframeTrack
  31523. */
  31524. class BooleanKeyframeTrack extends KeyframeTrack {
  31525. /**
  31526. * Constructs a new boolean keyframe track.
  31527. *
  31528. * This keyframe track type has no `interpolation` parameter because the
  31529. * interpolation is always discrete.
  31530. *
  31531. * @param {string} name - The keyframe track's name.
  31532. * @param {Array<number>} times - A list of keyframe times.
  31533. * @param {Array<boolean>} values - A list of keyframe values.
  31534. */
  31535. constructor( name, times, values ) {
  31536. super( name, times, values );
  31537. }
  31538. }
  31539. /**
  31540. * The value type name.
  31541. *
  31542. * @type {string}
  31543. * @default 'bool'
  31544. */
  31545. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31546. /**
  31547. * The value buffer type of this keyframe track.
  31548. *
  31549. * @type {TypedArray|Array}
  31550. * @default Array.constructor
  31551. */
  31552. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31553. /**
  31554. * The default interpolation type of this keyframe track.
  31555. *
  31556. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31557. * @default InterpolateDiscrete
  31558. */
  31559. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31560. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31561. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31562. /**
  31563. * A track for color keyframe values.
  31564. *
  31565. * @augments KeyframeTrack
  31566. */
  31567. class ColorKeyframeTrack extends KeyframeTrack {
  31568. /**
  31569. * Constructs a new color keyframe track.
  31570. *
  31571. * @param {string} name - The keyframe track's name.
  31572. * @param {Array<number>} times - A list of keyframe times.
  31573. * @param {Array<number>} values - A list of keyframe values.
  31574. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31575. */
  31576. constructor( name, times, values, interpolation ) {
  31577. super( name, times, values, interpolation );
  31578. }
  31579. }
  31580. /**
  31581. * The value type name.
  31582. *
  31583. * @type {string}
  31584. * @default 'color'
  31585. */
  31586. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31587. /**
  31588. * A track for numeric keyframe values.
  31589. *
  31590. * @augments KeyframeTrack
  31591. */
  31592. class NumberKeyframeTrack extends KeyframeTrack {
  31593. /**
  31594. * Constructs a new number keyframe track.
  31595. *
  31596. * @param {string} name - The keyframe track's name.
  31597. * @param {Array<number>} times - A list of keyframe times.
  31598. * @param {Array<number>} values - A list of keyframe values.
  31599. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31600. */
  31601. constructor( name, times, values, interpolation ) {
  31602. super( name, times, values, interpolation );
  31603. }
  31604. }
  31605. /**
  31606. * The value type name.
  31607. *
  31608. * @type {string}
  31609. * @default 'number'
  31610. */
  31611. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31612. /**
  31613. * Spherical linear unit quaternion interpolant.
  31614. *
  31615. * @augments Interpolant
  31616. */
  31617. class QuaternionLinearInterpolant extends Interpolant {
  31618. /**
  31619. * Constructs a new SLERP interpolant.
  31620. *
  31621. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31622. * @param {TypedArray} sampleValues - The sample values.
  31623. * @param {number} sampleSize - The sample size
  31624. * @param {TypedArray} [resultBuffer] - The result buffer.
  31625. */
  31626. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31627. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31628. }
  31629. interpolate_( i1, t0, t, t1 ) {
  31630. const result = this.resultBuffer,
  31631. values = this.sampleValues,
  31632. stride = this.valueSize,
  31633. alpha = ( t - t0 ) / ( t1 - t0 );
  31634. let offset = i1 * stride;
  31635. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31636. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31637. }
  31638. return result;
  31639. }
  31640. }
  31641. /**
  31642. * A track for Quaternion keyframe values.
  31643. *
  31644. * @augments KeyframeTrack
  31645. */
  31646. class QuaternionKeyframeTrack extends KeyframeTrack {
  31647. /**
  31648. * Constructs a new Quaternion keyframe track.
  31649. *
  31650. * @param {string} name - The keyframe track's name.
  31651. * @param {Array<number>} times - A list of keyframe times.
  31652. * @param {Array<number>} values - A list of keyframe values.
  31653. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31654. */
  31655. constructor( name, times, values, interpolation ) {
  31656. super( name, times, values, interpolation );
  31657. }
  31658. /**
  31659. * Overwritten so the method returns Quaternion based interpolant.
  31660. *
  31661. * @static
  31662. * @param {TypedArray} [result] - The result buffer.
  31663. * @return {QuaternionLinearInterpolant} The new interpolant.
  31664. */
  31665. InterpolantFactoryMethodLinear( result ) {
  31666. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31667. }
  31668. }
  31669. /**
  31670. * The value type name.
  31671. *
  31672. * @type {string}
  31673. * @default 'quaternion'
  31674. */
  31675. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31676. // ValueBufferType is inherited
  31677. // DefaultInterpolation is inherited;
  31678. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31679. /**
  31680. * A track for string keyframe values.
  31681. *
  31682. * @augments KeyframeTrack
  31683. */
  31684. class StringKeyframeTrack extends KeyframeTrack {
  31685. /**
  31686. * Constructs a new string keyframe track.
  31687. *
  31688. * This keyframe track type has no `interpolation` parameter because the
  31689. * interpolation is always discrete.
  31690. *
  31691. * @param {string} name - The keyframe track's name.
  31692. * @param {Array<number>} times - A list of keyframe times.
  31693. * @param {Array<string>} values - A list of keyframe values.
  31694. */
  31695. constructor( name, times, values ) {
  31696. super( name, times, values );
  31697. }
  31698. }
  31699. /**
  31700. * The value type name.
  31701. *
  31702. * @type {string}
  31703. * @default 'string'
  31704. */
  31705. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31706. /**
  31707. * The value buffer type of this keyframe track.
  31708. *
  31709. * @type {TypedArray|Array}
  31710. * @default Array.constructor
  31711. */
  31712. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31713. /**
  31714. * The default interpolation type of this keyframe track.
  31715. *
  31716. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31717. * @default InterpolateDiscrete
  31718. */
  31719. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31720. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31721. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31722. /**
  31723. * A track for vector keyframe values.
  31724. *
  31725. * @augments KeyframeTrack
  31726. */
  31727. class VectorKeyframeTrack extends KeyframeTrack {
  31728. /**
  31729. * Constructs a new vector keyframe track.
  31730. *
  31731. * @param {string} name - The keyframe track's name.
  31732. * @param {Array<number>} times - A list of keyframe times.
  31733. * @param {Array<number>} values - A list of keyframe values.
  31734. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31735. */
  31736. constructor( name, times, values, interpolation ) {
  31737. super( name, times, values, interpolation );
  31738. }
  31739. }
  31740. /**
  31741. * The value type name.
  31742. *
  31743. * @type {string}
  31744. * @default 'vector'
  31745. */
  31746. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31747. /**
  31748. * A reusable set of keyframe tracks which represent an animation.
  31749. */
  31750. class AnimationClip {
  31751. /**
  31752. * Constructs a new animation clip.
  31753. *
  31754. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31755. * use the static interface of this class for creating clips. In most cases though, animation clips
  31756. * will automatically be created by loaders when importing animated 3D assets.
  31757. *
  31758. * @param {string} [name=''] - The clip's name.
  31759. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31760. * the duration will be calculated from the passed keyframes.
  31761. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31762. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31763. * is blended/combined when two or more animations are simultaneously played.
  31764. */
  31765. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31766. /**
  31767. * The clip's name.
  31768. *
  31769. * @type {string}
  31770. */
  31771. this.name = name;
  31772. /**
  31773. * An array of keyframe tracks.
  31774. *
  31775. * @type {Array<KeyframeTrack>}
  31776. */
  31777. this.tracks = tracks;
  31778. /**
  31779. * The clip's duration in seconds.
  31780. *
  31781. * @type {number}
  31782. */
  31783. this.duration = duration;
  31784. /**
  31785. * Defines how the animation is blended/combined when two or more animations
  31786. * are simultaneously played.
  31787. *
  31788. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31789. */
  31790. this.blendMode = blendMode;
  31791. /**
  31792. * The UUID of the animation clip.
  31793. *
  31794. * @type {string}
  31795. * @readonly
  31796. */
  31797. this.uuid = generateUUID();
  31798. /**
  31799. * An object that can be used to store custom data about the animation clip.
  31800. * It should not hold references to functions as these will not be cloned.
  31801. *
  31802. * @type {Object}
  31803. */
  31804. this.userData = {};
  31805. // this means it should figure out its duration by scanning the tracks
  31806. if ( this.duration < 0 ) {
  31807. this.resetDuration();
  31808. }
  31809. }
  31810. /**
  31811. * Factory method for creating an animation clip from the given JSON.
  31812. *
  31813. * @static
  31814. * @param {Object} json - The serialized animation clip.
  31815. * @return {AnimationClip} The new animation clip.
  31816. */
  31817. static parse( json ) {
  31818. const tracks = [],
  31819. jsonTracks = json.tracks,
  31820. frameTime = 1.0 / ( json.fps || 1.0 );
  31821. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31822. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31823. }
  31824. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31825. clip.uuid = json.uuid;
  31826. clip.userData = JSON.parse( json.userData || '{}' );
  31827. return clip;
  31828. }
  31829. /**
  31830. * Serializes the given animation clip into JSON.
  31831. *
  31832. * @static
  31833. * @param {AnimationClip} clip - The animation clip to serialize.
  31834. * @return {Object} The JSON object.
  31835. */
  31836. static toJSON( clip ) {
  31837. const tracks = [],
  31838. clipTracks = clip.tracks;
  31839. const json = {
  31840. 'name': clip.name,
  31841. 'duration': clip.duration,
  31842. 'tracks': tracks,
  31843. 'uuid': clip.uuid,
  31844. 'blendMode': clip.blendMode,
  31845. 'userData': JSON.stringify( clip.userData ),
  31846. };
  31847. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31848. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31849. }
  31850. return json;
  31851. }
  31852. /**
  31853. * Returns a new animation clip from the passed morph targets array of a
  31854. * geometry, taking a name and the number of frames per second.
  31855. *
  31856. * Note: The fps parameter is required, but the animation speed can be
  31857. * overridden via {@link AnimationAction#setDuration}.
  31858. *
  31859. * @static
  31860. * @param {string} name - The name of the animation clip.
  31861. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31862. * @param {number} fps - The Frames-Per-Second value.
  31863. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31864. * @return {AnimationClip} The new animation clip.
  31865. */
  31866. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31867. const numMorphTargets = morphTargetSequence.length;
  31868. const tracks = [];
  31869. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31870. let times = [];
  31871. let values = [];
  31872. times.push(
  31873. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31874. i,
  31875. ( i + 1 ) % numMorphTargets );
  31876. values.push( 0, 1, 0 );
  31877. const order = getKeyframeOrder( times );
  31878. times = sortedArray( times, 1, order );
  31879. values = sortedArray( values, 1, order );
  31880. // if there is a key at the first frame, duplicate it as the
  31881. // last frame as well for perfect loop.
  31882. if ( ! noLoop && times[ 0 ] === 0 ) {
  31883. times.push( numMorphTargets );
  31884. values.push( values[ 0 ] );
  31885. }
  31886. tracks.push(
  31887. new NumberKeyframeTrack(
  31888. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31889. times, values
  31890. ).scale( 1.0 / fps ) );
  31891. }
  31892. return new this( name, -1, tracks );
  31893. }
  31894. /**
  31895. * Searches for an animation clip by name, taking as its first parameter
  31896. * either an array of clips, or a mesh or geometry that contains an
  31897. * array named "animations" property.
  31898. *
  31899. * @static
  31900. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31901. * @param {string} name - The name to search for.
  31902. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31903. */
  31904. static findByName( objectOrClipArray, name ) {
  31905. let clipArray = objectOrClipArray;
  31906. if ( ! Array.isArray( objectOrClipArray ) ) {
  31907. const o = objectOrClipArray;
  31908. clipArray = o.geometry && o.geometry.animations || o.animations;
  31909. }
  31910. for ( let i = 0; i < clipArray.length; i ++ ) {
  31911. if ( clipArray[ i ].name === name ) {
  31912. return clipArray[ i ];
  31913. }
  31914. }
  31915. return null;
  31916. }
  31917. /**
  31918. * Returns an array of new AnimationClips created from the morph target
  31919. * sequences of a geometry, trying to sort morph target names into
  31920. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31921. *
  31922. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31923. *
  31924. * @static
  31925. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31926. * @param {number} fps - The Frames-Per-Second value.
  31927. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31928. * @return {Array<AnimationClip>} An array of new animation clips.
  31929. */
  31930. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31931. const animationToMorphTargets = {};
  31932. // tested with https://regex101.com/ on trick sequences
  31933. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31934. const pattern = /^([\w-]*?)([\d]+)$/;
  31935. // sort morph target names into animation groups based
  31936. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31937. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31938. const morphTarget = morphTargets[ i ];
  31939. const parts = morphTarget.name.match( pattern );
  31940. if ( parts && parts.length > 1 ) {
  31941. const name = parts[ 1 ];
  31942. let animationMorphTargets = animationToMorphTargets[ name ];
  31943. if ( ! animationMorphTargets ) {
  31944. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31945. }
  31946. animationMorphTargets.push( morphTarget );
  31947. }
  31948. }
  31949. const clips = [];
  31950. for ( const name in animationToMorphTargets ) {
  31951. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31952. }
  31953. return clips;
  31954. }
  31955. /**
  31956. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31957. *
  31958. * @static
  31959. * @deprecated since r175.
  31960. * @param {Object} animation - A serialized animation clip as JSON.
  31961. * @param {Array<Bone>} bones - An array of bones.
  31962. * @return {?AnimationClip} The new animation clip.
  31963. */
  31964. static parseAnimation( animation, bones ) {
  31965. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31966. if ( ! animation ) {
  31967. error( 'AnimationClip: No animation in JSONLoader data.' );
  31968. return null;
  31969. }
  31970. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31971. // only return track if there are actually keys.
  31972. if ( animationKeys.length !== 0 ) {
  31973. const times = [];
  31974. const values = [];
  31975. flattenJSON( animationKeys, times, values, propertyName );
  31976. // empty keys are filtered out, so check again
  31977. if ( times.length !== 0 ) {
  31978. destTracks.push( new trackType( trackName, times, values ) );
  31979. }
  31980. }
  31981. };
  31982. const tracks = [];
  31983. const clipName = animation.name || 'default';
  31984. const fps = animation.fps || 30;
  31985. const blendMode = animation.blendMode;
  31986. // automatic length determination in AnimationClip.
  31987. let duration = animation.length || -1;
  31988. const hierarchyTracks = animation.hierarchy || [];
  31989. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31990. const animationKeys = hierarchyTracks[ h ].keys;
  31991. // skip empty tracks
  31992. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31993. // process morph targets
  31994. if ( animationKeys[ 0 ].morphTargets ) {
  31995. // figure out all morph targets used in this track
  31996. const morphTargetNames = {};
  31997. let k;
  31998. for ( k = 0; k < animationKeys.length; k ++ ) {
  31999. if ( animationKeys[ k ].morphTargets ) {
  32000. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  32001. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  32002. }
  32003. }
  32004. }
  32005. // create a track for each morph target with all zero
  32006. // morphTargetInfluences except for the keys in which
  32007. // the morphTarget is named.
  32008. for ( const morphTargetName in morphTargetNames ) {
  32009. const times = [];
  32010. const values = [];
  32011. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  32012. const animationKey = animationKeys[ k ];
  32013. times.push( animationKey.time );
  32014. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  32015. }
  32016. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  32017. }
  32018. duration = morphTargetNames.length * fps;
  32019. } else {
  32020. // ...assume skeletal animation
  32021. const boneName = '.bones[' + bones[ h ].name + ']';
  32022. addNonemptyTrack(
  32023. VectorKeyframeTrack, boneName + '.position',
  32024. animationKeys, 'pos', tracks );
  32025. addNonemptyTrack(
  32026. QuaternionKeyframeTrack, boneName + '.quaternion',
  32027. animationKeys, 'rot', tracks );
  32028. addNonemptyTrack(
  32029. VectorKeyframeTrack, boneName + '.scale',
  32030. animationKeys, 'scl', tracks );
  32031. }
  32032. }
  32033. if ( tracks.length === 0 ) {
  32034. return null;
  32035. }
  32036. const clip = new this( clipName, duration, tracks, blendMode );
  32037. return clip;
  32038. }
  32039. /**
  32040. * Sets the duration of this clip to the duration of its longest keyframe track.
  32041. *
  32042. * @return {AnimationClip} A reference to this animation clip.
  32043. */
  32044. resetDuration() {
  32045. const tracks = this.tracks;
  32046. let duration = 0;
  32047. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  32048. const track = this.tracks[ i ];
  32049. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  32050. }
  32051. this.duration = duration;
  32052. return this;
  32053. }
  32054. /**
  32055. * Trims all tracks to the clip's duration.
  32056. *
  32057. * @return {AnimationClip} A reference to this animation clip.
  32058. */
  32059. trim() {
  32060. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32061. this.tracks[ i ].trim( 0, this.duration );
  32062. }
  32063. return this;
  32064. }
  32065. /**
  32066. * Performs minimal validation on each track in the clip. Returns `true` if all
  32067. * tracks are valid.
  32068. *
  32069. * @return {boolean} Whether the clip's keyframes are valid or not.
  32070. */
  32071. validate() {
  32072. let valid = true;
  32073. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32074. valid = valid && this.tracks[ i ].validate();
  32075. }
  32076. return valid;
  32077. }
  32078. /**
  32079. * Optimizes each track by removing equivalent sequential keys (which are
  32080. * common in morph target sequences).
  32081. *
  32082. * @return {AnimationClip} A reference to this animation clip.
  32083. */
  32084. optimize() {
  32085. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32086. this.tracks[ i ].optimize();
  32087. }
  32088. return this;
  32089. }
  32090. /**
  32091. * Returns a new animation clip with copied values from this instance.
  32092. *
  32093. * @return {AnimationClip} A clone of this instance.
  32094. */
  32095. clone() {
  32096. const tracks = [];
  32097. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32098. tracks.push( this.tracks[ i ].clone() );
  32099. }
  32100. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  32101. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  32102. return clip;
  32103. }
  32104. /**
  32105. * Serializes this animation clip into JSON.
  32106. *
  32107. * @return {Object} The JSON object.
  32108. */
  32109. toJSON() {
  32110. return this.constructor.toJSON( this );
  32111. }
  32112. }
  32113. function getTrackTypeForValueTypeName( typeName ) {
  32114. switch ( typeName.toLowerCase() ) {
  32115. case 'scalar':
  32116. case 'double':
  32117. case 'float':
  32118. case 'number':
  32119. case 'integer':
  32120. return NumberKeyframeTrack;
  32121. case 'vector':
  32122. case 'vector2':
  32123. case 'vector3':
  32124. case 'vector4':
  32125. return VectorKeyframeTrack;
  32126. case 'color':
  32127. return ColorKeyframeTrack;
  32128. case 'quaternion':
  32129. return QuaternionKeyframeTrack;
  32130. case 'bool':
  32131. case 'boolean':
  32132. return BooleanKeyframeTrack;
  32133. case 'string':
  32134. return StringKeyframeTrack;
  32135. }
  32136. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  32137. }
  32138. function parseKeyframeTrack( json ) {
  32139. if ( json.type === undefined ) {
  32140. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  32141. }
  32142. const trackType = getTrackTypeForValueTypeName( json.type );
  32143. if ( json.times === undefined ) {
  32144. const times = [], values = [];
  32145. flattenJSON( json.keys, times, values, 'value' );
  32146. json.times = times;
  32147. json.values = values;
  32148. }
  32149. // derived classes can define a static parse method
  32150. if ( trackType.parse !== undefined ) {
  32151. return trackType.parse( json );
  32152. } else {
  32153. // by default, we assume a constructor compatible with the base
  32154. return new trackType( json.name, json.times, json.values, json.interpolation );
  32155. }
  32156. }
  32157. /**
  32158. * @class
  32159. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  32160. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  32161. * @hideconstructor
  32162. */
  32163. const Cache = {
  32164. /**
  32165. * Whether caching is enabled or not.
  32166. *
  32167. * @static
  32168. * @type {boolean}
  32169. * @default false
  32170. */
  32171. enabled: false,
  32172. /**
  32173. * A dictionary that holds cached files.
  32174. *
  32175. * @static
  32176. * @type {Object<string,Object>}
  32177. */
  32178. files: {},
  32179. /**
  32180. * Adds a cache entry with a key to reference the file. If this key already
  32181. * holds a file, it is overwritten.
  32182. *
  32183. * @static
  32184. * @param {string} key - The key to reference the cached file.
  32185. * @param {Object} file - The file to be cached.
  32186. */
  32187. add: function ( key, file ) {
  32188. if ( this.enabled === false ) return;
  32189. // log( 'Cache', 'Adding key:', key );
  32190. this.files[ key ] = file;
  32191. },
  32192. /**
  32193. * Gets the cached value for the given key.
  32194. *
  32195. * @static
  32196. * @param {string} key - The key to reference the cached file.
  32197. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  32198. */
  32199. get: function ( key ) {
  32200. if ( this.enabled === false ) return;
  32201. // log( 'Cache', 'Checking key:', key );
  32202. return this.files[ key ];
  32203. },
  32204. /**
  32205. * Removes the cached file associated with the given key.
  32206. *
  32207. * @static
  32208. * @param {string} key - The key to reference the cached file.
  32209. */
  32210. remove: function ( key ) {
  32211. delete this.files[ key ];
  32212. },
  32213. /**
  32214. * Remove all values from the cache.
  32215. *
  32216. * @static
  32217. */
  32218. clear: function () {
  32219. this.files = {};
  32220. }
  32221. };
  32222. /**
  32223. * Handles and keeps track of loaded and pending data. A default global
  32224. * instance of this class is created and used by loaders if not supplied
  32225. * manually.
  32226. *
  32227. * In general that should be sufficient, however there are times when it can
  32228. * be useful to have separate loaders - for example if you want to show
  32229. * separate loading bars for objects and textures.
  32230. *
  32231. * ```js
  32232. * const manager = new THREE.LoadingManager();
  32233. * manager.onLoad = () => console.log( 'Loading complete!' );
  32234. *
  32235. * const loader1 = new OBJLoader( manager );
  32236. * const loader2 = new ColladaLoader( manager );
  32237. * ```
  32238. */
  32239. class LoadingManager {
  32240. /**
  32241. * Constructs a new loading manager.
  32242. *
  32243. * @param {Function} [onLoad] - Executes when all items have been loaded.
  32244. * @param {Function} [onProgress] - Executes when single items have been loaded.
  32245. * @param {Function} [onError] - Executes when an error occurs.
  32246. */
  32247. constructor( onLoad, onProgress, onError ) {
  32248. const scope = this;
  32249. let isLoading = false;
  32250. let itemsLoaded = 0;
  32251. let itemsTotal = 0;
  32252. let urlModifier = undefined;
  32253. const handlers = [];
  32254. // Refer to #5689 for the reason why we don't set .onStart
  32255. // in the constructor
  32256. /**
  32257. * Executes when an item starts loading.
  32258. *
  32259. * @type {Function|undefined}
  32260. * @default undefined
  32261. */
  32262. this.onStart = undefined;
  32263. /**
  32264. * Executes when all items have been loaded.
  32265. *
  32266. * @type {Function|undefined}
  32267. * @default undefined
  32268. */
  32269. this.onLoad = onLoad;
  32270. /**
  32271. * Executes when single items have been loaded.
  32272. *
  32273. * @type {Function|undefined}
  32274. * @default undefined
  32275. */
  32276. this.onProgress = onProgress;
  32277. /**
  32278. * Executes when an error occurs.
  32279. *
  32280. * @type {Function|undefined}
  32281. * @default undefined
  32282. */
  32283. this.onError = onError;
  32284. /**
  32285. * Used for aborting ongoing requests in loaders using this manager.
  32286. *
  32287. * @private
  32288. * @type {AbortController | null}
  32289. */
  32290. this._abortController = null;
  32291. /**
  32292. * This should be called by any loader using the manager when the loader
  32293. * starts loading an item.
  32294. *
  32295. * @param {string} url - The URL to load.
  32296. */
  32297. this.itemStart = function ( url ) {
  32298. itemsTotal ++;
  32299. if ( isLoading === false ) {
  32300. if ( scope.onStart !== undefined ) {
  32301. scope.onStart( url, itemsLoaded, itemsTotal );
  32302. }
  32303. }
  32304. isLoading = true;
  32305. };
  32306. /**
  32307. * This should be called by any loader using the manager when the loader
  32308. * ended loading an item.
  32309. *
  32310. * @param {string} url - The URL of the loaded item.
  32311. */
  32312. this.itemEnd = function ( url ) {
  32313. itemsLoaded ++;
  32314. if ( scope.onProgress !== undefined ) {
  32315. scope.onProgress( url, itemsLoaded, itemsTotal );
  32316. }
  32317. if ( itemsLoaded === itemsTotal ) {
  32318. isLoading = false;
  32319. if ( scope.onLoad !== undefined ) {
  32320. scope.onLoad();
  32321. }
  32322. }
  32323. };
  32324. /**
  32325. * This should be called by any loader using the manager when the loader
  32326. * encounters an error when loading an item.
  32327. *
  32328. * @param {string} url - The URL of the item that produces an error.
  32329. */
  32330. this.itemError = function ( url ) {
  32331. if ( scope.onError !== undefined ) {
  32332. scope.onError( url );
  32333. }
  32334. };
  32335. /**
  32336. * Given a URL, uses the URL modifier callback (if any) and returns a
  32337. * resolved URL. If no URL modifier is set, returns the original URL.
  32338. *
  32339. * @param {string} url - The URL to load.
  32340. * @return {string} The resolved URL.
  32341. */
  32342. this.resolveURL = function ( url ) {
  32343. if ( urlModifier ) {
  32344. return urlModifier( url );
  32345. }
  32346. return url;
  32347. };
  32348. /**
  32349. * If provided, the callback will be passed each resource URL before a
  32350. * request is sent. The callback may return the original URL, or a new URL to
  32351. * override loading behavior. This behavior can be used to load assets from
  32352. * .ZIP files, drag-and-drop APIs, and Data URIs.
  32353. *
  32354. * ```js
  32355. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  32356. *
  32357. * const manager = new THREE.LoadingManager();
  32358. *
  32359. * // Initialize loading manager with URL callback.
  32360. * const objectURLs = [];
  32361. * manager.setURLModifier( ( url ) => {
  32362. *
  32363. * url = URL.createObjectURL( blobs[ url ] );
  32364. * objectURLs.push( url );
  32365. * return url;
  32366. *
  32367. * } );
  32368. *
  32369. * // Load as usual, then revoke the blob URLs.
  32370. * const loader = new GLTFLoader( manager );
  32371. * loader.load( 'fish.gltf', (gltf) => {
  32372. *
  32373. * scene.add( gltf.scene );
  32374. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32375. *
  32376. * } );
  32377. * ```
  32378. *
  32379. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32380. * @return {LoadingManager} A reference to this loading manager.
  32381. */
  32382. this.setURLModifier = function ( transform ) {
  32383. urlModifier = transform;
  32384. return this;
  32385. };
  32386. /**
  32387. * Registers a loader with the given regular expression. Can be used to
  32388. * define what loader should be used in order to load specific files. A
  32389. * typical use case is to overwrite the default loader for textures.
  32390. *
  32391. * ```js
  32392. * // add handler for TGA textures
  32393. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32394. * ```
  32395. *
  32396. * @param {string} regex - A regular expression.
  32397. * @param {Loader} loader - A loader that should handle matched cases.
  32398. * @return {LoadingManager} A reference to this loading manager.
  32399. */
  32400. this.addHandler = function ( regex, loader ) {
  32401. handlers.push( regex, loader );
  32402. return this;
  32403. };
  32404. /**
  32405. * Removes the loader for the given regular expression.
  32406. *
  32407. * @param {string} regex - A regular expression.
  32408. * @return {LoadingManager} A reference to this loading manager.
  32409. */
  32410. this.removeHandler = function ( regex ) {
  32411. const index = handlers.indexOf( regex );
  32412. if ( index !== -1 ) {
  32413. handlers.splice( index, 2 );
  32414. }
  32415. return this;
  32416. };
  32417. /**
  32418. * Can be used to retrieve the registered loader for the given file path.
  32419. *
  32420. * @param {string} file - The file path.
  32421. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32422. */
  32423. this.getHandler = function ( file ) {
  32424. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32425. const regex = handlers[ i ];
  32426. const loader = handlers[ i + 1 ];
  32427. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32428. if ( regex.test( file ) ) {
  32429. return loader;
  32430. }
  32431. }
  32432. return null;
  32433. };
  32434. /**
  32435. * Can be used to abort ongoing loading requests in loaders using this manager.
  32436. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32437. * is supported in the browser.
  32438. *
  32439. * @return {LoadingManager} A reference to this loading manager.
  32440. */
  32441. this.abort = function () {
  32442. this.abortController.abort();
  32443. this._abortController = null;
  32444. return this;
  32445. };
  32446. }
  32447. // TODO: Revert this back to a single member variable once this issue has been fixed
  32448. // https://github.com/cloudflare/workerd/issues/3657
  32449. /**
  32450. * Used for aborting ongoing requests in loaders using this manager.
  32451. *
  32452. * @type {AbortController}
  32453. */
  32454. get abortController() {
  32455. if ( ! this._abortController ) {
  32456. this._abortController = new AbortController();
  32457. }
  32458. return this._abortController;
  32459. }
  32460. }
  32461. /**
  32462. * The global default loading manager.
  32463. *
  32464. * @constant
  32465. * @type {LoadingManager}
  32466. */
  32467. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32468. /**
  32469. * Abstract base class for loaders.
  32470. *
  32471. * @abstract
  32472. */
  32473. class Loader {
  32474. /**
  32475. * Constructs a new loader.
  32476. *
  32477. * @param {LoadingManager} [manager] - The loading manager.
  32478. */
  32479. constructor( manager ) {
  32480. /**
  32481. * The loading manager.
  32482. *
  32483. * @type {LoadingManager}
  32484. * @default DefaultLoadingManager
  32485. */
  32486. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32487. /**
  32488. * The crossOrigin string to implement CORS for loading the url from a
  32489. * different domain that allows CORS.
  32490. *
  32491. * @type {string}
  32492. * @default 'anonymous'
  32493. */
  32494. this.crossOrigin = 'anonymous';
  32495. /**
  32496. * Whether the XMLHttpRequest uses credentials.
  32497. *
  32498. * @type {boolean}
  32499. * @default false
  32500. */
  32501. this.withCredentials = false;
  32502. /**
  32503. * The base path from which the asset will be loaded.
  32504. *
  32505. * @type {string}
  32506. */
  32507. this.path = '';
  32508. /**
  32509. * The base path from which additional resources like textures will be loaded.
  32510. *
  32511. * @type {string}
  32512. */
  32513. this.resourcePath = '';
  32514. /**
  32515. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32516. * used in HTTP request.
  32517. *
  32518. * @type {Object<string, any>}
  32519. */
  32520. this.requestHeader = {};
  32521. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32522. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32523. }
  32524. }
  32525. /**
  32526. * This method needs to be implemented by all concrete loaders. It holds the
  32527. * logic for loading assets from the backend.
  32528. *
  32529. * @abstract
  32530. * @param {string} url - The path/URL of the file to be loaded.
  32531. * @param {Function} onLoad - Executed when the loading process has been finished.
  32532. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32533. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32534. */
  32535. load( /* url, onLoad, onProgress, onError */ ) {}
  32536. /**
  32537. * A async version of {@link Loader#load}.
  32538. *
  32539. * @param {string} url - The path/URL of the file to be loaded.
  32540. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32541. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32542. */
  32543. loadAsync( url, onProgress ) {
  32544. const scope = this;
  32545. return new Promise( function ( resolve, reject ) {
  32546. scope.load( url, resolve, onProgress, reject );
  32547. } );
  32548. }
  32549. /**
  32550. * This method needs to be implemented by all concrete loaders. It holds the
  32551. * logic for parsing the asset into three.js entities.
  32552. *
  32553. * @abstract
  32554. * @param {any} data - The data to parse.
  32555. */
  32556. parse( /* data */ ) {}
  32557. /**
  32558. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32559. * from a different domain that allows CORS.
  32560. *
  32561. * @param {string} crossOrigin - The `crossOrigin` value.
  32562. * @return {Loader} A reference to this instance.
  32563. */
  32564. setCrossOrigin( crossOrigin ) {
  32565. this.crossOrigin = crossOrigin;
  32566. return this;
  32567. }
  32568. /**
  32569. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32570. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32571. *
  32572. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32573. *
  32574. * @param {boolean} value - The `withCredentials` value.
  32575. * @return {Loader} A reference to this instance.
  32576. */
  32577. setWithCredentials( value ) {
  32578. this.withCredentials = value;
  32579. return this;
  32580. }
  32581. /**
  32582. * Sets the base path for the asset.
  32583. *
  32584. * @param {string} path - The base path.
  32585. * @return {Loader} A reference to this instance.
  32586. */
  32587. setPath( path ) {
  32588. this.path = path;
  32589. return this;
  32590. }
  32591. /**
  32592. * Sets the base path for dependent resources like textures.
  32593. *
  32594. * @param {string} resourcePath - The resource path.
  32595. * @return {Loader} A reference to this instance.
  32596. */
  32597. setResourcePath( resourcePath ) {
  32598. this.resourcePath = resourcePath;
  32599. return this;
  32600. }
  32601. /**
  32602. * Sets the given request header.
  32603. *
  32604. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32605. * for configuring the HTTP request.
  32606. * @return {Loader} A reference to this instance.
  32607. */
  32608. setRequestHeader( requestHeader ) {
  32609. this.requestHeader = requestHeader;
  32610. return this;
  32611. }
  32612. /**
  32613. * This method can be implemented in loaders for aborting ongoing requests.
  32614. *
  32615. * @abstract
  32616. * @return {Loader} A reference to this instance.
  32617. */
  32618. abort() {
  32619. return this;
  32620. }
  32621. }
  32622. /**
  32623. * Callback for onProgress in loaders.
  32624. *
  32625. * @callback onProgressCallback
  32626. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32627. */
  32628. /**
  32629. * Callback for onError in loaders.
  32630. *
  32631. * @callback onErrorCallback
  32632. * @param {Error} error - The error which occurred during the loading process.
  32633. */
  32634. /**
  32635. * The default material name that is used by loaders
  32636. * when creating materials for loaded 3D objects.
  32637. *
  32638. * Note: Not all loaders might honor this setting.
  32639. *
  32640. * @static
  32641. * @type {string}
  32642. * @default '__DEFAULT'
  32643. */
  32644. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32645. const loading = {};
  32646. class HttpError extends Error {
  32647. constructor( message, response ) {
  32648. super( message );
  32649. this.response = response;
  32650. }
  32651. }
  32652. /**
  32653. * A low level class for loading resources with the Fetch API, used internally by
  32654. * most loaders. It can also be used directly to load any file type that does
  32655. * not have a loader.
  32656. *
  32657. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32658. * once to your application.
  32659. *
  32660. * ```js
  32661. * const loader = new THREE.FileLoader();
  32662. * const data = await loader.loadAsync( 'example.txt' );
  32663. * ```
  32664. *
  32665. * @augments Loader
  32666. */
  32667. class FileLoader extends Loader {
  32668. /**
  32669. * Constructs a new file loader.
  32670. *
  32671. * @param {LoadingManager} [manager] - The loading manager.
  32672. */
  32673. constructor( manager ) {
  32674. super( manager );
  32675. /**
  32676. * The expected mime type. Valid values can be found
  32677. * [here](hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32678. *
  32679. * @type {string}
  32680. */
  32681. this.mimeType = '';
  32682. /**
  32683. * The expected response type.
  32684. *
  32685. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32686. * @default ''
  32687. */
  32688. this.responseType = '';
  32689. /**
  32690. * Used for aborting requests.
  32691. *
  32692. * @private
  32693. * @type {AbortController}
  32694. */
  32695. this._abortController = new AbortController();
  32696. }
  32697. /**
  32698. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32699. *
  32700. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32701. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32702. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32703. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32704. * @return {any|undefined} The cached resource if available.
  32705. */
  32706. load( url, onLoad, onProgress, onError ) {
  32707. if ( url === undefined ) url = '';
  32708. if ( this.path !== undefined ) url = this.path + url;
  32709. url = this.manager.resolveURL( url );
  32710. const cached = Cache.get( `file:${url}` );
  32711. if ( cached !== undefined ) {
  32712. this.manager.itemStart( url );
  32713. setTimeout( () => {
  32714. if ( onLoad ) onLoad( cached );
  32715. this.manager.itemEnd( url );
  32716. }, 0 );
  32717. return cached;
  32718. }
  32719. // Check if request is duplicate
  32720. if ( loading[ url ] !== undefined ) {
  32721. loading[ url ].push( {
  32722. onLoad: onLoad,
  32723. onProgress: onProgress,
  32724. onError: onError
  32725. } );
  32726. return;
  32727. }
  32728. // Initialise array for duplicate requests
  32729. loading[ url ] = [];
  32730. loading[ url ].push( {
  32731. onLoad: onLoad,
  32732. onProgress: onProgress,
  32733. onError: onError,
  32734. } );
  32735. // create request
  32736. const req = new Request( url, {
  32737. headers: new Headers( this.requestHeader ),
  32738. credentials: this.withCredentials ? 'include' : 'same-origin',
  32739. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32740. } );
  32741. // record states ( avoid data race )
  32742. const mimeType = this.mimeType;
  32743. const responseType = this.responseType;
  32744. // start the fetch
  32745. fetch( req )
  32746. .then( response => {
  32747. if ( response.status === 200 || response.status === 0 ) {
  32748. // Some browsers return HTTP Status 0 when using non-http protocol
  32749. // e.g. 'file://' or 'data://'. Handle as success.
  32750. if ( response.status === 0 ) {
  32751. warn( 'FileLoader: HTTP Status 0 received.' );
  32752. }
  32753. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32754. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32755. return response;
  32756. }
  32757. const callbacks = loading[ url ];
  32758. const reader = response.body.getReader();
  32759. // Nginx needs X-File-Size check
  32760. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32761. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32762. const total = contentLength ? parseInt( contentLength ) : 0;
  32763. const lengthComputable = total !== 0;
  32764. let loaded = 0;
  32765. // periodically read data into the new stream tracking while download progress
  32766. const stream = new ReadableStream( {
  32767. start( controller ) {
  32768. readData();
  32769. function readData() {
  32770. reader.read().then( ( { done, value } ) => {
  32771. if ( done ) {
  32772. controller.close();
  32773. } else {
  32774. loaded += value.byteLength;
  32775. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32776. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32777. const callback = callbacks[ i ];
  32778. if ( callback.onProgress ) callback.onProgress( event );
  32779. }
  32780. controller.enqueue( value );
  32781. readData();
  32782. }
  32783. }, ( e ) => {
  32784. controller.error( e );
  32785. } );
  32786. }
  32787. }
  32788. } );
  32789. return new Response( stream );
  32790. } else {
  32791. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32792. }
  32793. } )
  32794. .then( response => {
  32795. switch ( responseType ) {
  32796. case 'arraybuffer':
  32797. return response.arrayBuffer();
  32798. case 'blob':
  32799. return response.blob();
  32800. case 'document':
  32801. return response.text()
  32802. .then( text => {
  32803. const parser = new DOMParser();
  32804. return parser.parseFromString( text, mimeType );
  32805. } );
  32806. case 'json':
  32807. return response.json();
  32808. default:
  32809. if ( mimeType === '' ) {
  32810. return response.text();
  32811. } else {
  32812. // sniff encoding
  32813. const re = /charset="?([^;"\s]*)"?/i;
  32814. const exec = re.exec( mimeType );
  32815. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32816. const decoder = new TextDecoder( label );
  32817. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32818. }
  32819. }
  32820. } )
  32821. .then( data => {
  32822. // Add to cache only on HTTP success, so that we do not cache
  32823. // error response bodies as proper responses to requests.
  32824. Cache.add( `file:${url}`, data );
  32825. const callbacks = loading[ url ];
  32826. delete loading[ url ];
  32827. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32828. const callback = callbacks[ i ];
  32829. if ( callback.onLoad ) callback.onLoad( data );
  32830. }
  32831. } )
  32832. .catch( err => {
  32833. // Abort errors and other errors are handled the same
  32834. const callbacks = loading[ url ];
  32835. if ( callbacks === undefined ) {
  32836. // When onLoad was called and url was deleted in `loading`
  32837. this.manager.itemError( url );
  32838. throw err;
  32839. }
  32840. delete loading[ url ];
  32841. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32842. const callback = callbacks[ i ];
  32843. if ( callback.onError ) callback.onError( err );
  32844. }
  32845. this.manager.itemError( url );
  32846. } )
  32847. .finally( () => {
  32848. this.manager.itemEnd( url );
  32849. } );
  32850. this.manager.itemStart( url );
  32851. }
  32852. /**
  32853. * Sets the expected response type.
  32854. *
  32855. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32856. * @return {FileLoader} A reference to this file loader.
  32857. */
  32858. setResponseType( value ) {
  32859. this.responseType = value;
  32860. return this;
  32861. }
  32862. /**
  32863. * Sets the expected mime type of the loaded file.
  32864. *
  32865. * @param {string} value - The mime type.
  32866. * @return {FileLoader} A reference to this file loader.
  32867. */
  32868. setMimeType( value ) {
  32869. this.mimeType = value;
  32870. return this;
  32871. }
  32872. /**
  32873. * Aborts ongoing fetch requests.
  32874. *
  32875. * @return {FileLoader} A reference to this instance.
  32876. */
  32877. abort() {
  32878. this._abortController.abort();
  32879. this._abortController = new AbortController();
  32880. return this;
  32881. }
  32882. }
  32883. /**
  32884. * Class for loading animation clips in the JSON format. The files are internally
  32885. * loaded via {@link FileLoader}.
  32886. *
  32887. * ```js
  32888. * const loader = new THREE.AnimationLoader();
  32889. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32890. * ```
  32891. *
  32892. * @augments Loader
  32893. */
  32894. class AnimationLoader extends Loader {
  32895. /**
  32896. * Constructs a new animation loader.
  32897. *
  32898. * @param {LoadingManager} [manager] - The loading manager.
  32899. */
  32900. constructor( manager ) {
  32901. super( manager );
  32902. }
  32903. /**
  32904. * Starts loading from the given URL and pass the loaded animations as an array
  32905. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32906. *
  32907. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32908. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32909. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32910. * @param {onErrorCallback} onError - Executed when errors occur.
  32911. */
  32912. load( url, onLoad, onProgress, onError ) {
  32913. const scope = this;
  32914. const loader = new FileLoader( this.manager );
  32915. loader.setPath( this.path );
  32916. loader.setRequestHeader( this.requestHeader );
  32917. loader.setWithCredentials( this.withCredentials );
  32918. loader.load( url, function ( text ) {
  32919. try {
  32920. onLoad( scope.parse( JSON.parse( text ) ) );
  32921. } catch ( e ) {
  32922. if ( onError ) {
  32923. onError( e );
  32924. } else {
  32925. error( e );
  32926. }
  32927. scope.manager.itemError( url );
  32928. }
  32929. }, onProgress, onError );
  32930. }
  32931. /**
  32932. * Parses the given JSON object and returns an array of animation clips.
  32933. *
  32934. * @param {Object} json - The serialized animation clips.
  32935. * @return {Array<AnimationClip>} The parsed animation clips.
  32936. */
  32937. parse( json ) {
  32938. const animations = [];
  32939. for ( let i = 0; i < json.length; i ++ ) {
  32940. const clip = AnimationClip.parse( json[ i ] );
  32941. animations.push( clip );
  32942. }
  32943. return animations;
  32944. }
  32945. }
  32946. /**
  32947. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32948. * Textures are internally loaded via {@link FileLoader}.
  32949. *
  32950. * Derived classes have to implement the `parse()` method which holds the parsing
  32951. * for the respective format.
  32952. *
  32953. * @abstract
  32954. * @augments Loader
  32955. */
  32956. class CompressedTextureLoader extends Loader {
  32957. /**
  32958. * Constructs a new compressed texture loader.
  32959. *
  32960. * @param {LoadingManager} [manager] - The loading manager.
  32961. */
  32962. constructor( manager ) {
  32963. super( manager );
  32964. }
  32965. /**
  32966. * Starts loading from the given URL and passes the loaded compressed texture
  32967. * to the `onLoad()` callback. The method also returns a new texture object which can
  32968. * directly be used for material creation. If you do it this way, the texture
  32969. * may pop up in your scene once the respective loading process is finished.
  32970. *
  32971. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32972. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32973. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32974. * @param {onErrorCallback} onError - Executed when errors occur.
  32975. * @return {CompressedTexture} The compressed texture.
  32976. */
  32977. load( url, onLoad, onProgress, onError ) {
  32978. const scope = this;
  32979. const images = [];
  32980. const texture = new CompressedTexture();
  32981. const loader = new FileLoader( this.manager );
  32982. loader.setPath( this.path );
  32983. loader.setResponseType( 'arraybuffer' );
  32984. loader.setRequestHeader( this.requestHeader );
  32985. loader.setWithCredentials( scope.withCredentials );
  32986. let loaded = 0;
  32987. function loadTexture( i ) {
  32988. loader.load( url[ i ], function ( buffer ) {
  32989. const texDatas = scope.parse( buffer, true );
  32990. images[ i ] = {
  32991. width: texDatas.width,
  32992. height: texDatas.height,
  32993. format: texDatas.format,
  32994. mipmaps: texDatas.mipmaps
  32995. };
  32996. loaded += 1;
  32997. if ( loaded === 6 ) {
  32998. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32999. texture.image = images;
  33000. texture.format = texDatas.format;
  33001. texture.needsUpdate = true;
  33002. if ( onLoad ) onLoad( texture );
  33003. }
  33004. }, onProgress, onError );
  33005. }
  33006. if ( Array.isArray( url ) ) {
  33007. for ( let i = 0, il = url.length; i < il; ++ i ) {
  33008. loadTexture( i );
  33009. }
  33010. } else {
  33011. // compressed cubemap texture stored in a single DDS file
  33012. loader.load( url, function ( buffer ) {
  33013. const texDatas = scope.parse( buffer, true );
  33014. if ( texDatas.isCubemap ) {
  33015. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  33016. for ( let f = 0; f < faces; f ++ ) {
  33017. images[ f ] = { mipmaps: [] };
  33018. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  33019. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  33020. images[ f ].format = texDatas.format;
  33021. images[ f ].width = texDatas.width;
  33022. images[ f ].height = texDatas.height;
  33023. }
  33024. }
  33025. texture.image = images;
  33026. } else {
  33027. texture.image.width = texDatas.width;
  33028. texture.image.height = texDatas.height;
  33029. texture.mipmaps = texDatas.mipmaps;
  33030. }
  33031. if ( texDatas.mipmapCount === 1 ) {
  33032. texture.minFilter = LinearFilter;
  33033. }
  33034. texture.format = texDatas.format;
  33035. texture.needsUpdate = true;
  33036. if ( onLoad ) onLoad( texture );
  33037. }, onProgress, onError );
  33038. }
  33039. return texture;
  33040. }
  33041. }
  33042. const _loading = new WeakMap();
  33043. /**
  33044. * A loader for loading images. The class loads images with the HTML `Image` API.
  33045. *
  33046. * ```js
  33047. * const loader = new THREE.ImageLoader();
  33048. * const image = await loader.loadAsync( 'image.png' );
  33049. * ```
  33050. * Please note that `ImageLoader` has dropped support for progress
  33051. * events in `r84`. For an `ImageLoader` that supports progress events, see
  33052. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  33053. *
  33054. * @augments Loader
  33055. */
  33056. class ImageLoader extends Loader {
  33057. /**
  33058. * Constructs a new image loader.
  33059. *
  33060. * @param {LoadingManager} [manager] - The loading manager.
  33061. */
  33062. constructor( manager ) {
  33063. super( manager );
  33064. }
  33065. /**
  33066. * Starts loading from the given URL and passes the loaded image
  33067. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  33068. * directly be used for texture creation. If you do it this way, the texture
  33069. * may pop up in your scene once the respective loading process is finished.
  33070. *
  33071. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33072. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  33073. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33074. * @param {onErrorCallback} onError - Executed when errors occur.
  33075. * @return {Image} The image.
  33076. */
  33077. load( url, onLoad, onProgress, onError ) {
  33078. if ( this.path !== undefined ) url = this.path + url;
  33079. url = this.manager.resolveURL( url );
  33080. const scope = this;
  33081. const cached = Cache.get( `image:${url}` );
  33082. if ( cached !== undefined ) {
  33083. if ( cached.complete === true ) {
  33084. scope.manager.itemStart( url );
  33085. setTimeout( function () {
  33086. if ( onLoad ) onLoad( cached );
  33087. scope.manager.itemEnd( url );
  33088. }, 0 );
  33089. } else {
  33090. let arr = _loading.get( cached );
  33091. if ( arr === undefined ) {
  33092. arr = [];
  33093. _loading.set( cached, arr );
  33094. }
  33095. arr.push( { onLoad, onError } );
  33096. }
  33097. return cached;
  33098. }
  33099. const image = createElementNS( 'img' );
  33100. function onImageLoad() {
  33101. removeEventListeners();
  33102. if ( onLoad ) onLoad( this );
  33103. //
  33104. const callbacks = _loading.get( this ) || [];
  33105. for ( let i = 0; i < callbacks.length; i ++ ) {
  33106. const callback = callbacks[ i ];
  33107. if ( callback.onLoad ) callback.onLoad( this );
  33108. }
  33109. _loading.delete( this );
  33110. scope.manager.itemEnd( url );
  33111. }
  33112. function onImageError( event ) {
  33113. removeEventListeners();
  33114. if ( onError ) onError( event );
  33115. Cache.remove( `image:${url}` );
  33116. //
  33117. const callbacks = _loading.get( this ) || [];
  33118. for ( let i = 0; i < callbacks.length; i ++ ) {
  33119. const callback = callbacks[ i ];
  33120. if ( callback.onError ) callback.onError( event );
  33121. }
  33122. _loading.delete( this );
  33123. scope.manager.itemError( url );
  33124. scope.manager.itemEnd( url );
  33125. }
  33126. function removeEventListeners() {
  33127. image.removeEventListener( 'load', onImageLoad, false );
  33128. image.removeEventListener( 'error', onImageError, false );
  33129. }
  33130. image.addEventListener( 'load', onImageLoad, false );
  33131. image.addEventListener( 'error', onImageError, false );
  33132. if ( url.slice( 0, 5 ) !== 'data:' ) {
  33133. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  33134. }
  33135. Cache.add( `image:${url}`, image );
  33136. scope.manager.itemStart( url );
  33137. image.src = url;
  33138. return image;
  33139. }
  33140. }
  33141. /**
  33142. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  33143. *
  33144. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  33145. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  33146. * like vertical and horizontal cross, column and row layouts are not supported.
  33147. *
  33148. * Note that, by convention, cube maps are specified in a coordinate system
  33149. * in which positive-x is to the right when looking up the positive-z axis --
  33150. * in other words, using a left-handed coordinate system. Since three.js uses
  33151. * a right-handed coordinate system, environment maps used in three.js will
  33152. * have pos-x and neg-x swapped.
  33153. *
  33154. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  33155. * is set to `SRGBColorSpace` by default.
  33156. *
  33157. * ```js
  33158. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  33159. * const cubeTexture = await loader.loadAsync( [
  33160. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  33161. * ] );
  33162. * scene.background = cubeTexture;
  33163. * ```
  33164. *
  33165. * @augments Loader
  33166. */
  33167. class CubeTextureLoader extends Loader {
  33168. /**
  33169. * Constructs a new cube texture loader.
  33170. *
  33171. * @param {LoadingManager} [manager] - The loading manager.
  33172. */
  33173. constructor( manager ) {
  33174. super( manager );
  33175. }
  33176. /**
  33177. * Starts loading from the given URL and pass the fully loaded cube texture
  33178. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  33179. * directly be used for material creation. If you do it this way, the cube texture
  33180. * may pop up in your scene once the respective loading process is finished.
  33181. *
  33182. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  33183. * cube texture. The urls should be specified in the following order: pos-x,
  33184. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  33185. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  33186. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33187. * @param {onErrorCallback} onError - Executed when errors occur.
  33188. * @return {CubeTexture} The cube texture.
  33189. */
  33190. load( urls, onLoad, onProgress, onError ) {
  33191. const texture = new CubeTexture();
  33192. texture.colorSpace = SRGBColorSpace;
  33193. const loader = new ImageLoader( this.manager );
  33194. loader.setCrossOrigin( this.crossOrigin );
  33195. loader.setPath( this.path );
  33196. let loaded = 0;
  33197. function loadTexture( i ) {
  33198. loader.load( urls[ i ], function ( image ) {
  33199. texture.images[ i ] = image;
  33200. loaded ++;
  33201. if ( loaded === 6 ) {
  33202. texture.needsUpdate = true;
  33203. if ( onLoad ) onLoad( texture );
  33204. }
  33205. }, undefined, onError );
  33206. }
  33207. for ( let i = 0; i < urls.length; ++ i ) {
  33208. loadTexture( i );
  33209. }
  33210. return texture;
  33211. }
  33212. }
  33213. /**
  33214. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  33215. * Textures are internally loaded via {@link FileLoader}.
  33216. *
  33217. * Derived classes have to implement the `parse()` method which holds the parsing
  33218. * for the respective format.
  33219. *
  33220. * @abstract
  33221. * @augments Loader
  33222. */
  33223. class DataTextureLoader extends Loader {
  33224. /**
  33225. * Constructs a new data texture loader.
  33226. *
  33227. * @param {LoadingManager} [manager] - The loading manager.
  33228. */
  33229. constructor( manager ) {
  33230. super( manager );
  33231. }
  33232. /**
  33233. * Starts loading from the given URL and passes the loaded data texture
  33234. * to the `onLoad()` callback. The method also returns a new texture object which can
  33235. * directly be used for material creation. If you do it this way, the texture
  33236. * may pop up in your scene once the respective loading process is finished.
  33237. *
  33238. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33239. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  33240. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33241. * @param {onErrorCallback} onError - Executed when errors occur.
  33242. * @return {DataTexture} The data texture.
  33243. */
  33244. load( url, onLoad, onProgress, onError ) {
  33245. const scope = this;
  33246. const texture = new DataTexture();
  33247. const loader = new FileLoader( this.manager );
  33248. loader.setResponseType( 'arraybuffer' );
  33249. loader.setRequestHeader( this.requestHeader );
  33250. loader.setPath( this.path );
  33251. loader.setWithCredentials( scope.withCredentials );
  33252. loader.load( url, function ( buffer ) {
  33253. let texData;
  33254. try {
  33255. texData = scope.parse( buffer );
  33256. } catch ( error ) {
  33257. if ( onError !== undefined ) {
  33258. onError( error );
  33259. } else {
  33260. error( error );
  33261. return;
  33262. }
  33263. }
  33264. if ( texData.image !== undefined ) {
  33265. texture.image = texData.image;
  33266. } else if ( texData.data !== undefined ) {
  33267. texture.image.width = texData.width;
  33268. texture.image.height = texData.height;
  33269. texture.image.data = texData.data;
  33270. }
  33271. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  33272. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  33273. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  33274. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  33275. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  33276. if ( texData.colorSpace !== undefined ) {
  33277. texture.colorSpace = texData.colorSpace;
  33278. }
  33279. if ( texData.flipY !== undefined ) {
  33280. texture.flipY = texData.flipY;
  33281. }
  33282. if ( texData.format !== undefined ) {
  33283. texture.format = texData.format;
  33284. }
  33285. if ( texData.type !== undefined ) {
  33286. texture.type = texData.type;
  33287. }
  33288. if ( texData.mipmaps !== undefined ) {
  33289. texture.mipmaps = texData.mipmaps;
  33290. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  33291. }
  33292. if ( texData.mipmapCount === 1 ) {
  33293. texture.minFilter = LinearFilter;
  33294. }
  33295. if ( texData.generateMipmaps !== undefined ) {
  33296. texture.generateMipmaps = texData.generateMipmaps;
  33297. }
  33298. texture.needsUpdate = true;
  33299. if ( onLoad ) onLoad( texture, texData );
  33300. }, onProgress, onError );
  33301. return texture;
  33302. }
  33303. }
  33304. /**
  33305. * Class for loading textures. Images are internally
  33306. * loaded via {@link ImageLoader}.
  33307. *
  33308. * ```js
  33309. * const loader = new THREE.TextureLoader();
  33310. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  33311. *
  33312. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  33313. * ```
  33314. * Please note that `TextureLoader` has dropped support for progress
  33315. * events in `r84`. For a `TextureLoader` that supports progress events, see
  33316. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  33317. *
  33318. * @augments Loader
  33319. */
  33320. class TextureLoader extends Loader {
  33321. /**
  33322. * Constructs a new texture loader.
  33323. *
  33324. * @param {LoadingManager} [manager] - The loading manager.
  33325. */
  33326. constructor( manager ) {
  33327. super( manager );
  33328. }
  33329. /**
  33330. * Starts loading from the given URL and pass the fully loaded texture
  33331. * to the `onLoad()` callback. The method also returns a new texture object which can
  33332. * directly be used for material creation. If you do it this way, the texture
  33333. * may pop up in your scene once the respective loading process is finished.
  33334. *
  33335. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33336. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  33337. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33338. * @param {onErrorCallback} onError - Executed when errors occur.
  33339. * @return {Texture} The texture.
  33340. */
  33341. load( url, onLoad, onProgress, onError ) {
  33342. const texture = new Texture();
  33343. const loader = new ImageLoader( this.manager );
  33344. loader.setCrossOrigin( this.crossOrigin );
  33345. loader.setPath( this.path );
  33346. loader.load( url, function ( image ) {
  33347. texture.image = image;
  33348. texture.needsUpdate = true;
  33349. if ( onLoad !== undefined ) {
  33350. onLoad( texture );
  33351. }
  33352. }, onProgress, onError );
  33353. return texture;
  33354. }
  33355. }
  33356. /**
  33357. * Abstract base class for lights - all other light types inherit the
  33358. * properties and methods described here.
  33359. *
  33360. * @abstract
  33361. * @augments Object3D
  33362. */
  33363. class Light extends Object3D {
  33364. /**
  33365. * Constructs a new light.
  33366. *
  33367. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33368. * @param {number} [intensity=1] - The light's strength/intensity.
  33369. */
  33370. constructor( color, intensity = 1 ) {
  33371. super();
  33372. /**
  33373. * This flag can be used for type testing.
  33374. *
  33375. * @type {boolean}
  33376. * @readonly
  33377. * @default true
  33378. */
  33379. this.isLight = true;
  33380. this.type = 'Light';
  33381. /**
  33382. * The light's color.
  33383. *
  33384. * @type {Color}
  33385. */
  33386. this.color = new Color( color );
  33387. /**
  33388. * The light's intensity.
  33389. *
  33390. * @type {number}
  33391. * @default 1
  33392. */
  33393. this.intensity = intensity;
  33394. }
  33395. /**
  33396. * Frees the GPU-related resources allocated by this instance. Call this
  33397. * method whenever this instance is no longer used in your app.
  33398. */
  33399. dispose() {
  33400. this.dispatchEvent( { type: 'dispose' } );
  33401. }
  33402. copy( source, recursive ) {
  33403. super.copy( source, recursive );
  33404. this.color.copy( source.color );
  33405. this.intensity = source.intensity;
  33406. return this;
  33407. }
  33408. toJSON( meta ) {
  33409. const data = super.toJSON( meta );
  33410. data.object.color = this.color.getHex();
  33411. data.object.intensity = this.intensity;
  33412. return data;
  33413. }
  33414. }
  33415. /**
  33416. * A light source positioned directly above the scene, with color fading from
  33417. * the sky color to the ground color.
  33418. *
  33419. * This light cannot be used to cast shadows.
  33420. *
  33421. * ```js
  33422. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33423. * scene.add( light );
  33424. * ```
  33425. *
  33426. * @augments Light
  33427. */
  33428. class HemisphereLight extends Light {
  33429. /**
  33430. * Constructs a new hemisphere light.
  33431. *
  33432. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33433. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33434. * @param {number} [intensity=1] - The light's strength/intensity.
  33435. */
  33436. constructor( skyColor, groundColor, intensity ) {
  33437. super( skyColor, intensity );
  33438. /**
  33439. * This flag can be used for type testing.
  33440. *
  33441. * @type {boolean}
  33442. * @readonly
  33443. * @default true
  33444. */
  33445. this.isHemisphereLight = true;
  33446. this.type = 'HemisphereLight';
  33447. this.position.copy( Object3D.DEFAULT_UP );
  33448. this.updateMatrix();
  33449. /**
  33450. * The light's ground color.
  33451. *
  33452. * @type {Color}
  33453. */
  33454. this.groundColor = new Color( groundColor );
  33455. }
  33456. copy( source, recursive ) {
  33457. super.copy( source, recursive );
  33458. this.groundColor.copy( source.groundColor );
  33459. return this;
  33460. }
  33461. toJSON( meta ) {
  33462. const data = super.toJSON( meta );
  33463. data.object.groundColor = this.groundColor.getHex();
  33464. return data;
  33465. }
  33466. }
  33467. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33468. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33469. const _lookTarget = /*@__PURE__*/ new Vector3();
  33470. /**
  33471. * Abstract base class for light shadow classes. These classes
  33472. * represent the shadow configuration for different light types.
  33473. *
  33474. * @abstract
  33475. */
  33476. class LightShadow {
  33477. /**
  33478. * Constructs a new light shadow.
  33479. *
  33480. * @param {Camera} camera - The light's view of the world.
  33481. */
  33482. constructor( camera ) {
  33483. /**
  33484. * The light's view of the world.
  33485. *
  33486. * @type {Camera}
  33487. */
  33488. this.camera = camera;
  33489. /**
  33490. * The intensity of the shadow. The default is `1`.
  33491. * Valid values are in the range `[0, 1]`.
  33492. *
  33493. * @type {number}
  33494. * @default 1
  33495. */
  33496. this.intensity = 1;
  33497. /**
  33498. * Shadow map bias, how much to add or subtract from the normalized depth
  33499. * when deciding whether a surface is in shadow.
  33500. *
  33501. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33502. * may help reduce artifacts in shadows.
  33503. *
  33504. * @type {number}
  33505. * @default 0
  33506. */
  33507. this.bias = 0;
  33508. /**
  33509. * Defines how much the position used to query the shadow map is offset along
  33510. * the object normal. The default is `0`. Increasing this value can be used to
  33511. * reduce shadow acne especially in large scenes where light shines onto
  33512. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33513. *
  33514. * @type {number}
  33515. * @default 0
  33516. */
  33517. this.normalBias = 0;
  33518. /**
  33519. * Setting this to values greater than 1 will blur the edges of the shadow.
  33520. * High values will cause unwanted banding effects in the shadows - a greater
  33521. * map size will allow for a higher value to be used here before these effects
  33522. * become visible.
  33523. *
  33524. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33525. *
  33526. * @type {number}
  33527. * @default 1
  33528. */
  33529. this.radius = 1;
  33530. /**
  33531. * The amount of samples to use when blurring a VSM shadow map.
  33532. *
  33533. * @type {number}
  33534. * @default 8
  33535. */
  33536. this.blurSamples = 8;
  33537. /**
  33538. * Defines the width and height of the shadow map. Higher values give better quality
  33539. * shadows at the cost of computation time. Values must be powers of two.
  33540. *
  33541. * @type {Vector2}
  33542. * @default (512,512)
  33543. */
  33544. this.mapSize = new Vector2( 512, 512 );
  33545. /**
  33546. * The type of shadow texture. The default is `UnsignedByteType`.
  33547. *
  33548. * @type {number}
  33549. * @default UnsignedByteType
  33550. */
  33551. this.mapType = UnsignedByteType;
  33552. /**
  33553. * The depth map generated using the internal camera; a location beyond a
  33554. * pixel's depth is in shadow. Computed internally during rendering.
  33555. *
  33556. * @type {?RenderTarget}
  33557. * @default null
  33558. */
  33559. this.map = null;
  33560. /**
  33561. * The distribution map generated using the internal camera; an occlusion is
  33562. * calculated based on the distribution of depths. Computed internally during
  33563. * rendering.
  33564. *
  33565. * @type {?RenderTarget}
  33566. * @default null
  33567. */
  33568. this.mapPass = null;
  33569. /**
  33570. * Model to shadow camera space, to compute location and depth in shadow map.
  33571. * This is computed internally during rendering.
  33572. *
  33573. * @type {Matrix4}
  33574. */
  33575. this.matrix = new Matrix4();
  33576. /**
  33577. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33578. * lighting / shadows, you may set this to `false`.
  33579. *
  33580. * @type {boolean}
  33581. * @default true
  33582. */
  33583. this.autoUpdate = true;
  33584. /**
  33585. * When set to `true`, shadow maps will be updated in the next `render` call.
  33586. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33587. * set this property to `true` and then make a render call to update the light's shadow.
  33588. *
  33589. * @type {boolean}
  33590. * @default false
  33591. */
  33592. this.needsUpdate = false;
  33593. this._frustum = new Frustum();
  33594. this._frameExtents = new Vector2( 1, 1 );
  33595. this._viewportCount = 1;
  33596. this._viewports = [
  33597. new Vector4( 0, 0, 1, 1 )
  33598. ];
  33599. }
  33600. /**
  33601. * Used internally by the renderer to get the number of viewports that need
  33602. * to be rendered for this shadow.
  33603. *
  33604. * @return {number} The viewport count.
  33605. */
  33606. getViewportCount() {
  33607. return this._viewportCount;
  33608. }
  33609. /**
  33610. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33611. *
  33612. * @return {Frustum} The shadow camera frustum.
  33613. */
  33614. getFrustum() {
  33615. return this._frustum;
  33616. }
  33617. /**
  33618. * Update the matrices for the camera and shadow, used internally by the renderer.
  33619. *
  33620. * @param {Light} light - The light for which the shadow is being rendered.
  33621. */
  33622. updateMatrices( light ) {
  33623. const shadowCamera = this.camera;
  33624. const shadowMatrix = this.matrix;
  33625. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33626. shadowCamera.position.copy( _lightPositionWorld );
  33627. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  33628. shadowCamera.lookAt( _lookTarget );
  33629. shadowCamera.updateMatrixWorld();
  33630. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33631. this._frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33632. if ( shadowCamera.reversedDepth ) {
  33633. shadowMatrix.set(
  33634. 0.5, 0.0, 0.0, 0.5,
  33635. 0.0, 0.5, 0.0, 0.5,
  33636. 0.0, 0.0, 1.0, 0.0,
  33637. 0.0, 0.0, 0.0, 1.0
  33638. );
  33639. } else {
  33640. shadowMatrix.set(
  33641. 0.5, 0.0, 0.0, 0.5,
  33642. 0.0, 0.5, 0.0, 0.5,
  33643. 0.0, 0.0, 0.5, 0.5,
  33644. 0.0, 0.0, 0.0, 1.0
  33645. );
  33646. }
  33647. shadowMatrix.multiply( _projScreenMatrix );
  33648. }
  33649. /**
  33650. * Returns a viewport definition for the given viewport index.
  33651. *
  33652. * @param {number} viewportIndex - The viewport index.
  33653. * @return {Vector4} The viewport.
  33654. */
  33655. getViewport( viewportIndex ) {
  33656. return this._viewports[ viewportIndex ];
  33657. }
  33658. /**
  33659. * Returns the frame extends.
  33660. *
  33661. * @return {Vector2} The frame extends.
  33662. */
  33663. getFrameExtents() {
  33664. return this._frameExtents;
  33665. }
  33666. /**
  33667. * Frees the GPU-related resources allocated by this instance. Call this
  33668. * method whenever this instance is no longer used in your app.
  33669. */
  33670. dispose() {
  33671. if ( this.map ) {
  33672. this.map.dispose();
  33673. }
  33674. if ( this.mapPass ) {
  33675. this.mapPass.dispose();
  33676. }
  33677. }
  33678. /**
  33679. * Copies the values of the given light shadow instance to this instance.
  33680. *
  33681. * @param {LightShadow} source - The light shadow to copy.
  33682. * @return {LightShadow} A reference to this light shadow instance.
  33683. */
  33684. copy( source ) {
  33685. this.camera = source.camera.clone();
  33686. this.intensity = source.intensity;
  33687. this.bias = source.bias;
  33688. this.radius = source.radius;
  33689. this.autoUpdate = source.autoUpdate;
  33690. this.needsUpdate = source.needsUpdate;
  33691. this.normalBias = source.normalBias;
  33692. this.blurSamples = source.blurSamples;
  33693. this.mapSize.copy( source.mapSize );
  33694. return this;
  33695. }
  33696. /**
  33697. * Returns a new light shadow instance with copied values from this instance.
  33698. *
  33699. * @return {LightShadow} A clone of this instance.
  33700. */
  33701. clone() {
  33702. return new this.constructor().copy( this );
  33703. }
  33704. /**
  33705. * Serializes the light shadow into JSON.
  33706. *
  33707. * @return {Object} A JSON object representing the serialized light shadow.
  33708. * @see {@link ObjectLoader#parse}
  33709. */
  33710. toJSON() {
  33711. const object = {};
  33712. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33713. if ( this.bias !== 0 ) object.bias = this.bias;
  33714. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33715. if ( this.radius !== 1 ) object.radius = this.radius;
  33716. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33717. object.camera = this.camera.toJSON( false ).object;
  33718. delete object.camera.matrix;
  33719. return object;
  33720. }
  33721. }
  33722. /**
  33723. * Represents the shadow configuration of directional lights.
  33724. *
  33725. * @augments LightShadow
  33726. */
  33727. class SpotLightShadow extends LightShadow {
  33728. /**
  33729. * Constructs a new spot light shadow.
  33730. */
  33731. constructor() {
  33732. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33733. /**
  33734. * This flag can be used for type testing.
  33735. *
  33736. * @type {boolean}
  33737. * @readonly
  33738. * @default true
  33739. */
  33740. this.isSpotLightShadow = true;
  33741. /**
  33742. * Used to focus the shadow camera. The camera's field of view is set as a
  33743. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33744. *
  33745. * @type {number}
  33746. * @default 1
  33747. */
  33748. this.focus = 1;
  33749. /**
  33750. * Texture aspect ratio.
  33751. *
  33752. * @type {number}
  33753. * @default 1
  33754. */
  33755. this.aspect = 1;
  33756. }
  33757. updateMatrices( light ) {
  33758. const camera = this.camera;
  33759. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33760. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33761. const far = light.distance || camera.far;
  33762. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33763. camera.fov = fov;
  33764. camera.aspect = aspect;
  33765. camera.far = far;
  33766. camera.updateProjectionMatrix();
  33767. }
  33768. super.updateMatrices( light );
  33769. }
  33770. copy( source ) {
  33771. super.copy( source );
  33772. this.focus = source.focus;
  33773. return this;
  33774. }
  33775. }
  33776. /**
  33777. * This light gets emitted from a single point in one direction, along a cone
  33778. * that increases in size the further from the light it gets.
  33779. *
  33780. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33781. *
  33782. * ```js
  33783. * // white spotlight shining from the side, modulated by a texture
  33784. * const spotLight = new THREE.SpotLight( 0xffffff );
  33785. * spotLight.position.set( 100, 1000, 100 );
  33786. * spotLight.map = new THREE.TextureLoader().load( url );
  33787. *
  33788. * spotLight.castShadow = true;
  33789. * spotLight.shadow.mapSize.width = 1024;
  33790. * spotLight.shadow.mapSize.height = 1024;
  33791. * spotLight.shadow.camera.near = 500;
  33792. * spotLight.shadow.camera.far = 4000;
  33793. * spotLight.shadow.camera.fov = 30;s
  33794. * ```
  33795. *
  33796. * @augments Light
  33797. */
  33798. class SpotLight extends Light {
  33799. /**
  33800. * Constructs a new spot light.
  33801. *
  33802. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33803. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33804. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33805. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33806. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33807. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33808. */
  33809. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33810. super( color, intensity );
  33811. /**
  33812. * This flag can be used for type testing.
  33813. *
  33814. * @type {boolean}
  33815. * @readonly
  33816. * @default true
  33817. */
  33818. this.isSpotLight = true;
  33819. this.type = 'SpotLight';
  33820. this.position.copy( Object3D.DEFAULT_UP );
  33821. this.updateMatrix();
  33822. /**
  33823. * The spot light points from its position to the
  33824. * target's position.
  33825. *
  33826. * For the target's position to be changed to anything other
  33827. * than the default, it must be added to the scene.
  33828. *
  33829. * It is also possible to set the target to be another 3D object
  33830. * in the scene. The light will now track the target object.
  33831. *
  33832. * @type {Object3D}
  33833. */
  33834. this.target = new Object3D();
  33835. /**
  33836. * Maximum range of the light. `0` means no limit.
  33837. *
  33838. * @type {number}
  33839. * @default 0
  33840. */
  33841. this.distance = distance;
  33842. /**
  33843. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33844. *
  33845. * @type {number}
  33846. * @default Math.PI/3
  33847. */
  33848. this.angle = angle;
  33849. /**
  33850. * Percent of the spotlight cone that is attenuated due to penumbra.
  33851. * Value range is `[0,1]`.
  33852. *
  33853. * @type {number}
  33854. * @default 0
  33855. */
  33856. this.penumbra = penumbra;
  33857. /**
  33858. * The amount the light dims along the distance of the light. In context of
  33859. * physically-correct rendering the default value should not be changed.
  33860. *
  33861. * @type {number}
  33862. * @default 2
  33863. */
  33864. this.decay = decay;
  33865. /**
  33866. * A texture used to modulate the color of the light. The spot light
  33867. * color is mixed with the RGB value of this texture, with a ratio
  33868. * corresponding to its alpha value. The cookie-like masking effect is
  33869. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33870. *
  33871. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33872. *
  33873. * @type {?Texture}
  33874. * @default null
  33875. */
  33876. this.map = null;
  33877. /**
  33878. * This property holds the light's shadow configuration.
  33879. *
  33880. * @type {SpotLightShadow}
  33881. */
  33882. this.shadow = new SpotLightShadow();
  33883. }
  33884. /**
  33885. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33886. * Changing the power will also change the light's intensity.
  33887. *
  33888. * @type {number}
  33889. */
  33890. get power() {
  33891. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33892. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33893. return this.intensity * Math.PI;
  33894. }
  33895. set power( power ) {
  33896. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33897. this.intensity = power / Math.PI;
  33898. }
  33899. dispose() {
  33900. super.dispose();
  33901. this.shadow.dispose();
  33902. }
  33903. copy( source, recursive ) {
  33904. super.copy( source, recursive );
  33905. this.distance = source.distance;
  33906. this.angle = source.angle;
  33907. this.penumbra = source.penumbra;
  33908. this.decay = source.decay;
  33909. this.target = source.target.clone();
  33910. this.map = source.map;
  33911. this.shadow = source.shadow.clone();
  33912. return this;
  33913. }
  33914. toJSON( meta ) {
  33915. const data = super.toJSON( meta );
  33916. data.object.distance = this.distance;
  33917. data.object.angle = this.angle;
  33918. data.object.decay = this.decay;
  33919. data.object.penumbra = this.penumbra;
  33920. data.object.target = this.target.uuid;
  33921. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  33922. data.object.shadow = this.shadow.toJSON();
  33923. return data;
  33924. }
  33925. }
  33926. /**
  33927. * Represents the shadow configuration of point lights.
  33928. *
  33929. * @augments LightShadow
  33930. */
  33931. class PointLightShadow extends LightShadow {
  33932. /**
  33933. * Constructs a new point light shadow.
  33934. */
  33935. constructor() {
  33936. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33937. /**
  33938. * This flag can be used for type testing.
  33939. *
  33940. * @type {boolean}
  33941. * @readonly
  33942. * @default true
  33943. */
  33944. this.isPointLightShadow = true;
  33945. }
  33946. }
  33947. /**
  33948. * A light that gets emitted from a single point in all directions. A common
  33949. * use case for this is to replicate the light emitted from a bare
  33950. * lightbulb.
  33951. *
  33952. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33953. *
  33954. * ```js
  33955. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33956. * light.position.set( 50, 50, 50 );
  33957. * scene.add( light );
  33958. * ```
  33959. *
  33960. * @augments Light
  33961. */
  33962. class PointLight extends Light {
  33963. /**
  33964. * Constructs a new point light.
  33965. *
  33966. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33967. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33968. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33969. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33970. */
  33971. constructor( color, intensity, distance = 0, decay = 2 ) {
  33972. super( color, intensity );
  33973. /**
  33974. * This flag can be used for type testing.
  33975. *
  33976. * @type {boolean}
  33977. * @readonly
  33978. * @default true
  33979. */
  33980. this.isPointLight = true;
  33981. this.type = 'PointLight';
  33982. /**
  33983. * When distance is zero, light will attenuate according to inverse-square
  33984. * law to infinite distance. When distance is non-zero, light will attenuate
  33985. * according to inverse-square law until near the distance cutoff, where it
  33986. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33987. * physically correct.
  33988. *
  33989. * @type {number}
  33990. * @default 0
  33991. */
  33992. this.distance = distance;
  33993. /**
  33994. * The amount the light dims along the distance of the light. In context of
  33995. * physically-correct rendering the default value should not be changed.
  33996. *
  33997. * @type {number}
  33998. * @default 2
  33999. */
  34000. this.decay = decay;
  34001. /**
  34002. * This property holds the light's shadow configuration.
  34003. *
  34004. * @type {PointLightShadow}
  34005. */
  34006. this.shadow = new PointLightShadow();
  34007. }
  34008. /**
  34009. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34010. * Changing the power will also change the light's intensity.
  34011. *
  34012. * @type {number}
  34013. */
  34014. get power() {
  34015. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34016. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  34017. return this.intensity * 4 * Math.PI;
  34018. }
  34019. set power( power ) {
  34020. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34021. this.intensity = power / ( 4 * Math.PI );
  34022. }
  34023. dispose() {
  34024. super.dispose();
  34025. this.shadow.dispose();
  34026. }
  34027. copy( source, recursive ) {
  34028. super.copy( source, recursive );
  34029. this.distance = source.distance;
  34030. this.decay = source.decay;
  34031. this.shadow = source.shadow.clone();
  34032. return this;
  34033. }
  34034. toJSON( meta ) {
  34035. const data = super.toJSON( meta );
  34036. data.object.distance = this.distance;
  34037. data.object.decay = this.decay;
  34038. data.object.shadow = this.shadow.toJSON();
  34039. return data;
  34040. }
  34041. }
  34042. /**
  34043. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  34044. *
  34045. * In this projection mode, an object's size in the rendered image stays
  34046. * constant regardless of its distance from the camera. This can be useful
  34047. * for rendering 2D scenes and UI elements, amongst other things.
  34048. *
  34049. * ```js
  34050. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  34051. * scene.add( camera );
  34052. * ```
  34053. *
  34054. * @augments Camera
  34055. */
  34056. class OrthographicCamera extends Camera {
  34057. /**
  34058. * Constructs a new orthographic camera.
  34059. *
  34060. * @param {number} [left=-1] - The left plane of the camera's frustum.
  34061. * @param {number} [right=1] - The right plane of the camera's frustum.
  34062. * @param {number} [top=1] - The top plane of the camera's frustum.
  34063. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  34064. * @param {number} [near=0.1] - The camera's near plane.
  34065. * @param {number} [far=2000] - The camera's far plane.
  34066. */
  34067. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  34068. super();
  34069. /**
  34070. * This flag can be used for type testing.
  34071. *
  34072. * @type {boolean}
  34073. * @readonly
  34074. * @default true
  34075. */
  34076. this.isOrthographicCamera = true;
  34077. this.type = 'OrthographicCamera';
  34078. /**
  34079. * The zoom factor of the camera.
  34080. *
  34081. * @type {number}
  34082. * @default 1
  34083. */
  34084. this.zoom = 1;
  34085. /**
  34086. * Represents the frustum window specification. This property should not be edited
  34087. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34088. *
  34089. * @type {?Object}
  34090. * @default null
  34091. */
  34092. this.view = null;
  34093. /**
  34094. * The left plane of the camera's frustum.
  34095. *
  34096. * @type {number}
  34097. * @default -1
  34098. */
  34099. this.left = left;
  34100. /**
  34101. * The right plane of the camera's frustum.
  34102. *
  34103. * @type {number}
  34104. * @default 1
  34105. */
  34106. this.right = right;
  34107. /**
  34108. * The top plane of the camera's frustum.
  34109. *
  34110. * @type {number}
  34111. * @default 1
  34112. */
  34113. this.top = top;
  34114. /**
  34115. * The bottom plane of the camera's frustum.
  34116. *
  34117. * @type {number}
  34118. * @default -1
  34119. */
  34120. this.bottom = bottom;
  34121. /**
  34122. * The camera's near plane. The valid range is greater than `0`
  34123. * and less than the current value of {@link OrthographicCamera#far}.
  34124. *
  34125. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  34126. * valid value for an orthographic camera's near plane.
  34127. *
  34128. * @type {number}
  34129. * @default 0.1
  34130. */
  34131. this.near = near;
  34132. /**
  34133. * The camera's far plane. Must be greater than the
  34134. * current value of {@link OrthographicCamera#near}.
  34135. *
  34136. * @type {number}
  34137. * @default 2000
  34138. */
  34139. this.far = far;
  34140. this.updateProjectionMatrix();
  34141. }
  34142. copy( source, recursive ) {
  34143. super.copy( source, recursive );
  34144. this.left = source.left;
  34145. this.right = source.right;
  34146. this.top = source.top;
  34147. this.bottom = source.bottom;
  34148. this.near = source.near;
  34149. this.far = source.far;
  34150. this.zoom = source.zoom;
  34151. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34152. return this;
  34153. }
  34154. /**
  34155. * Sets an offset in a larger frustum. This is useful for multi-window or
  34156. * multi-monitor/multi-machine setups.
  34157. *
  34158. * @param {number} fullWidth - The full width of multiview setup.
  34159. * @param {number} fullHeight - The full height of multiview setup.
  34160. * @param {number} x - The horizontal offset of the subcamera.
  34161. * @param {number} y - The vertical offset of the subcamera.
  34162. * @param {number} width - The width of subcamera.
  34163. * @param {number} height - The height of subcamera.
  34164. * @see {@link PerspectiveCamera#setViewOffset}
  34165. */
  34166. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34167. if ( this.view === null ) {
  34168. this.view = {
  34169. enabled: true,
  34170. fullWidth: 1,
  34171. fullHeight: 1,
  34172. offsetX: 0,
  34173. offsetY: 0,
  34174. width: 1,
  34175. height: 1
  34176. };
  34177. }
  34178. this.view.enabled = true;
  34179. this.view.fullWidth = fullWidth;
  34180. this.view.fullHeight = fullHeight;
  34181. this.view.offsetX = x;
  34182. this.view.offsetY = y;
  34183. this.view.width = width;
  34184. this.view.height = height;
  34185. this.updateProjectionMatrix();
  34186. }
  34187. /**
  34188. * Removes the view offset from the projection matrix.
  34189. */
  34190. clearViewOffset() {
  34191. if ( this.view !== null ) {
  34192. this.view.enabled = false;
  34193. }
  34194. this.updateProjectionMatrix();
  34195. }
  34196. /**
  34197. * Updates the camera's projection matrix. Must be called after any change of
  34198. * camera properties.
  34199. */
  34200. updateProjectionMatrix() {
  34201. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34202. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34203. const cx = ( this.right + this.left ) / 2;
  34204. const cy = ( this.top + this.bottom ) / 2;
  34205. let left = cx - dx;
  34206. let right = cx + dx;
  34207. let top = cy + dy;
  34208. let bottom = cy - dy;
  34209. if ( this.view !== null && this.view.enabled ) {
  34210. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34211. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34212. left += scaleW * this.view.offsetX;
  34213. right = left + scaleW * this.view.width;
  34214. top -= scaleH * this.view.offsetY;
  34215. bottom = top - scaleH * this.view.height;
  34216. }
  34217. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34218. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34219. }
  34220. toJSON( meta ) {
  34221. const data = super.toJSON( meta );
  34222. data.object.zoom = this.zoom;
  34223. data.object.left = this.left;
  34224. data.object.right = this.right;
  34225. data.object.top = this.top;
  34226. data.object.bottom = this.bottom;
  34227. data.object.near = this.near;
  34228. data.object.far = this.far;
  34229. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34230. return data;
  34231. }
  34232. }
  34233. /**
  34234. * Represents the shadow configuration of directional lights.
  34235. *
  34236. * @augments LightShadow
  34237. */
  34238. class DirectionalLightShadow extends LightShadow {
  34239. /**
  34240. * Constructs a new directional light shadow.
  34241. */
  34242. constructor() {
  34243. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34244. /**
  34245. * This flag can be used for type testing.
  34246. *
  34247. * @type {boolean}
  34248. * @readonly
  34249. * @default true
  34250. */
  34251. this.isDirectionalLightShadow = true;
  34252. }
  34253. }
  34254. /**
  34255. * A light that gets emitted in a specific direction. This light will behave
  34256. * as though it is infinitely far away and the rays produced from it are all
  34257. * parallel. The common use case for this is to simulate daylight; the sun is
  34258. * far enough away that its position can be considered to be infinite, and
  34259. * all light rays coming from it are parallel.
  34260. *
  34261. * A common point of confusion for directional lights is that setting the
  34262. * rotation has no effect. This is because three.js's DirectionalLight is the
  34263. * equivalent to what is often called a 'Target Direct Light' in other
  34264. * applications.
  34265. *
  34266. * This means that its direction is calculated as pointing from the light's
  34267. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34268. * (as opposed to a 'Free Direct Light' that just has a rotation
  34269. * component).
  34270. *
  34271. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34272. *
  34273. * ```js
  34274. * // White directional light at half intensity shining from the top.
  34275. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34276. * scene.add( directionalLight );
  34277. * ```
  34278. *
  34279. * @augments Light
  34280. */
  34281. class DirectionalLight extends Light {
  34282. /**
  34283. * Constructs a new directional light.
  34284. *
  34285. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34286. * @param {number} [intensity=1] - The light's strength/intensity.
  34287. */
  34288. constructor( color, intensity ) {
  34289. super( color, intensity );
  34290. /**
  34291. * This flag can be used for type testing.
  34292. *
  34293. * @type {boolean}
  34294. * @readonly
  34295. * @default true
  34296. */
  34297. this.isDirectionalLight = true;
  34298. this.type = 'DirectionalLight';
  34299. this.position.copy( Object3D.DEFAULT_UP );
  34300. this.updateMatrix();
  34301. /**
  34302. * The directional light points from its position to the
  34303. * target's position.
  34304. *
  34305. * For the target's position to be changed to anything other
  34306. * than the default, it must be added to the scene.
  34307. *
  34308. * It is also possible to set the target to be another 3D object
  34309. * in the scene. The light will now track the target object.
  34310. *
  34311. * @type {Object3D}
  34312. */
  34313. this.target = new Object3D();
  34314. /**
  34315. * This property holds the light's shadow configuration.
  34316. *
  34317. * @type {DirectionalLightShadow}
  34318. */
  34319. this.shadow = new DirectionalLightShadow();
  34320. }
  34321. dispose() {
  34322. super.dispose();
  34323. this.shadow.dispose();
  34324. }
  34325. copy( source ) {
  34326. super.copy( source );
  34327. this.target = source.target.clone();
  34328. this.shadow = source.shadow.clone();
  34329. return this;
  34330. }
  34331. toJSON( meta ) {
  34332. const data = super.toJSON( meta );
  34333. data.object.shadow = this.shadow.toJSON();
  34334. data.object.target = this.target.uuid;
  34335. return data;
  34336. }
  34337. }
  34338. /**
  34339. * This light globally illuminates all objects in the scene equally.
  34340. *
  34341. * It cannot be used to cast shadows as it does not have a direction.
  34342. *
  34343. * ```js
  34344. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34345. * scene.add( light );
  34346. * ```
  34347. *
  34348. * @augments Light
  34349. */
  34350. class AmbientLight extends Light {
  34351. /**
  34352. * Constructs a new ambient light.
  34353. *
  34354. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34355. * @param {number} [intensity=1] - The light's strength/intensity.
  34356. */
  34357. constructor( color, intensity ) {
  34358. super( color, intensity );
  34359. /**
  34360. * This flag can be used for type testing.
  34361. *
  34362. * @type {boolean}
  34363. * @readonly
  34364. * @default true
  34365. */
  34366. this.isAmbientLight = true;
  34367. this.type = 'AmbientLight';
  34368. }
  34369. }
  34370. /**
  34371. * This class emits light uniformly across the face a rectangular plane.
  34372. * This light type can be used to simulate light sources such as bright
  34373. * windows or strip lighting.
  34374. *
  34375. * Important Notes:
  34376. *
  34377. * - There is no shadow support.
  34378. * - Only PBR materials are supported.
  34379. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34380. * into your app and init the uniforms/textures.
  34381. *
  34382. * ```js
  34383. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34384. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34385. *
  34386. * const intensity = 1; const width = 10; const height = 10;
  34387. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34388. * rectLight.position.set( 5, 5, 0 );
  34389. * rectLight.lookAt( 0, 0, 0 );
  34390. * scene.add( rectLight )
  34391. * ```
  34392. *
  34393. * @augments Light
  34394. */
  34395. class RectAreaLight extends Light {
  34396. /**
  34397. * Constructs a new area light.
  34398. *
  34399. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34400. * @param {number} [intensity=1] - The light's strength/intensity.
  34401. * @param {number} [width=10] - The width of the light.
  34402. * @param {number} [height=10] - The height of the light.
  34403. */
  34404. constructor( color, intensity, width = 10, height = 10 ) {
  34405. super( color, intensity );
  34406. /**
  34407. * This flag can be used for type testing.
  34408. *
  34409. * @type {boolean}
  34410. * @readonly
  34411. * @default true
  34412. */
  34413. this.isRectAreaLight = true;
  34414. this.type = 'RectAreaLight';
  34415. /**
  34416. * The width of the light.
  34417. *
  34418. * @type {number}
  34419. * @default 10
  34420. */
  34421. this.width = width;
  34422. /**
  34423. * The height of the light.
  34424. *
  34425. * @type {number}
  34426. * @default 10
  34427. */
  34428. this.height = height;
  34429. }
  34430. /**
  34431. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34432. * Changing the power will also change the light's intensity.
  34433. *
  34434. * @type {number}
  34435. */
  34436. get power() {
  34437. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34438. return this.intensity * this.width * this.height * Math.PI;
  34439. }
  34440. set power( power ) {
  34441. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34442. this.intensity = power / ( this.width * this.height * Math.PI );
  34443. }
  34444. copy( source ) {
  34445. super.copy( source );
  34446. this.width = source.width;
  34447. this.height = source.height;
  34448. return this;
  34449. }
  34450. toJSON( meta ) {
  34451. const data = super.toJSON( meta );
  34452. data.object.width = this.width;
  34453. data.object.height = this.height;
  34454. return data;
  34455. }
  34456. }
  34457. /**
  34458. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34459. * to encode lighting information.
  34460. *
  34461. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34462. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34463. */
  34464. class SphericalHarmonics3 {
  34465. /**
  34466. * Constructs a new spherical harmonics.
  34467. */
  34468. constructor() {
  34469. /**
  34470. * This flag can be used for type testing.
  34471. *
  34472. * @type {boolean}
  34473. * @readonly
  34474. * @default true
  34475. */
  34476. this.isSphericalHarmonics3 = true;
  34477. /**
  34478. * An array holding the (9) SH coefficients.
  34479. *
  34480. * @type {Array<Vector3>}
  34481. */
  34482. this.coefficients = [];
  34483. for ( let i = 0; i < 9; i ++ ) {
  34484. this.coefficients.push( new Vector3() );
  34485. }
  34486. }
  34487. /**
  34488. * Sets the given SH coefficients to this instance by copying
  34489. * the values.
  34490. *
  34491. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34492. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34493. */
  34494. set( coefficients ) {
  34495. for ( let i = 0; i < 9; i ++ ) {
  34496. this.coefficients[ i ].copy( coefficients[ i ] );
  34497. }
  34498. return this;
  34499. }
  34500. /**
  34501. * Sets all SH coefficients to `0`.
  34502. *
  34503. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34504. */
  34505. zero() {
  34506. for ( let i = 0; i < 9; i ++ ) {
  34507. this.coefficients[ i ].set( 0, 0, 0 );
  34508. }
  34509. return this;
  34510. }
  34511. /**
  34512. * Returns the radiance in the direction of the given normal.
  34513. *
  34514. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34515. * @param {Vector3} target - The target vector that is used to store the method's result.
  34516. * @return {Vector3} The radiance.
  34517. */
  34518. getAt( normal, target ) {
  34519. // normal is assumed to be unit length
  34520. const x = normal.x, y = normal.y, z = normal.z;
  34521. const coeff = this.coefficients;
  34522. // band 0
  34523. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34524. // band 1
  34525. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34526. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34527. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34528. // band 2
  34529. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34530. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34531. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34532. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34533. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34534. return target;
  34535. }
  34536. /**
  34537. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34538. * direction of the given normal.
  34539. *
  34540. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34541. * @param {Vector3} target - The target vector that is used to store the method's result.
  34542. * @return {Vector3} The irradiance.
  34543. */
  34544. getIrradianceAt( normal, target ) {
  34545. // normal is assumed to be unit length
  34546. const x = normal.x, y = normal.y, z = normal.z;
  34547. const coeff = this.coefficients;
  34548. // band 0
  34549. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34550. // band 1
  34551. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34552. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34553. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34554. // band 2
  34555. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34556. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34557. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34558. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34559. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34560. return target;
  34561. }
  34562. /**
  34563. * Adds the given SH to this instance.
  34564. *
  34565. * @param {SphericalHarmonics3} sh - The SH to add.
  34566. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34567. */
  34568. add( sh ) {
  34569. for ( let i = 0; i < 9; i ++ ) {
  34570. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34571. }
  34572. return this;
  34573. }
  34574. /**
  34575. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34576. * {@link SphericalHarmonics3#scale} at once.
  34577. *
  34578. * @param {SphericalHarmonics3} sh - The SH to add.
  34579. * @param {number} s - The scale factor.
  34580. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34581. */
  34582. addScaledSH( sh, s ) {
  34583. for ( let i = 0; i < 9; i ++ ) {
  34584. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34585. }
  34586. return this;
  34587. }
  34588. /**
  34589. * Scales this SH by the given scale factor.
  34590. *
  34591. * @param {number} s - The scale factor.
  34592. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34593. */
  34594. scale( s ) {
  34595. for ( let i = 0; i < 9; i ++ ) {
  34596. this.coefficients[ i ].multiplyScalar( s );
  34597. }
  34598. return this;
  34599. }
  34600. /**
  34601. * Linear interpolates between the given SH and this instance by the given
  34602. * alpha factor.
  34603. *
  34604. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34605. * @param {number} alpha - The alpha factor.
  34606. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34607. */
  34608. lerp( sh, alpha ) {
  34609. for ( let i = 0; i < 9; i ++ ) {
  34610. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34611. }
  34612. return this;
  34613. }
  34614. /**
  34615. * Returns `true` if this spherical harmonics is equal with the given one.
  34616. *
  34617. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34618. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34619. */
  34620. equals( sh ) {
  34621. for ( let i = 0; i < 9; i ++ ) {
  34622. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34623. return false;
  34624. }
  34625. }
  34626. return true;
  34627. }
  34628. /**
  34629. * Copies the values of the given spherical harmonics to this instance.
  34630. *
  34631. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34632. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34633. */
  34634. copy( sh ) {
  34635. return this.set( sh.coefficients );
  34636. }
  34637. /**
  34638. * Returns a new spherical harmonics with copied values from this instance.
  34639. *
  34640. * @return {SphericalHarmonics3} A clone of this instance.
  34641. */
  34642. clone() {
  34643. return new this.constructor().copy( this );
  34644. }
  34645. /**
  34646. * Sets the SH coefficients of this instance from the given array.
  34647. *
  34648. * @param {Array<number>} array - An array holding the SH coefficients.
  34649. * @param {number} [offset=0] - The array offset where to start copying.
  34650. * @return {SphericalHarmonics3} A clone of this instance.
  34651. */
  34652. fromArray( array, offset = 0 ) {
  34653. const coefficients = this.coefficients;
  34654. for ( let i = 0; i < 9; i ++ ) {
  34655. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34656. }
  34657. return this;
  34658. }
  34659. /**
  34660. * Returns an array with the SH coefficients, or copies them into the provided
  34661. * array. The coefficients are represented as numbers.
  34662. *
  34663. * @param {Array<number>} [array=[]] - The target array.
  34664. * @param {number} [offset=0] - The array offset where to start copying.
  34665. * @return {Array<number>} An array with flat SH coefficients.
  34666. */
  34667. toArray( array = [], offset = 0 ) {
  34668. const coefficients = this.coefficients;
  34669. for ( let i = 0; i < 9; i ++ ) {
  34670. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34671. }
  34672. return array;
  34673. }
  34674. /**
  34675. * Computes the SH basis for the given normal vector.
  34676. *
  34677. * @param {Vector3} normal - The normal.
  34678. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34679. */
  34680. static getBasisAt( normal, shBasis ) {
  34681. // normal is assumed to be unit length
  34682. const x = normal.x, y = normal.y, z = normal.z;
  34683. // band 0
  34684. shBasis[ 0 ] = 0.282095;
  34685. // band 1
  34686. shBasis[ 1 ] = 0.488603 * y;
  34687. shBasis[ 2 ] = 0.488603 * z;
  34688. shBasis[ 3 ] = 0.488603 * x;
  34689. // band 2
  34690. shBasis[ 4 ] = 1.092548 * x * y;
  34691. shBasis[ 5 ] = 1.092548 * y * z;
  34692. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34693. shBasis[ 7 ] = 1.092548 * x * z;
  34694. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34695. }
  34696. }
  34697. /**
  34698. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34699. * classical light sources (e.g. directional, point or spot lights), light
  34700. * probes do not emit light. Instead they store information about light
  34701. * passing through 3D space. During rendering, the light that hits a 3D
  34702. * object is approximated by using the data from the light probe.
  34703. *
  34704. * Light probes are usually created from (radiance) environment maps. The
  34705. * class {@link LightProbeGenerator} can be used to create light probes from
  34706. * cube textures or render targets. However, light estimation data could also
  34707. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34708. * augmented reality content that reacts to real world lighting.
  34709. *
  34710. * The current probe implementation in three.js supports so-called diffuse
  34711. * light probes. This type of light probe is functionally equivalent to an
  34712. * irradiance environment map.
  34713. *
  34714. * @augments Light
  34715. */
  34716. class LightProbe extends Light {
  34717. /**
  34718. * Constructs a new light probe.
  34719. *
  34720. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34721. * @param {number} [intensity=1] - The light's strength/intensity.
  34722. */
  34723. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34724. super( undefined, intensity );
  34725. /**
  34726. * This flag can be used for type testing.
  34727. *
  34728. * @type {boolean}
  34729. * @readonly
  34730. * @default true
  34731. */
  34732. this.isLightProbe = true;
  34733. /**
  34734. * A light probe uses spherical harmonics to encode lighting information.
  34735. *
  34736. * @type {SphericalHarmonics3}
  34737. */
  34738. this.sh = sh;
  34739. }
  34740. copy( source ) {
  34741. super.copy( source );
  34742. this.sh.copy( source.sh );
  34743. return this;
  34744. }
  34745. toJSON( meta ) {
  34746. const data = super.toJSON( meta );
  34747. data.object.sh = this.sh.toArray();
  34748. return data;
  34749. }
  34750. }
  34751. /**
  34752. * Class for loading materials. The files are internally
  34753. * loaded via {@link FileLoader}.
  34754. *
  34755. * ```js
  34756. * const loader = new THREE.MaterialLoader();
  34757. * const material = await loader.loadAsync( 'material.json' );
  34758. * ```
  34759. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34760. *
  34761. * @augments Loader
  34762. */
  34763. class MaterialLoader extends Loader {
  34764. /**
  34765. * Constructs a new material loader.
  34766. *
  34767. * @param {LoadingManager} [manager] - The loading manager.
  34768. */
  34769. constructor( manager ) {
  34770. super( manager );
  34771. /**
  34772. * A dictionary holding textures used by the material.
  34773. *
  34774. * @type {Object<string,Texture>}
  34775. */
  34776. this.textures = {};
  34777. }
  34778. /**
  34779. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34780. *
  34781. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34782. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34783. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34784. * @param {onErrorCallback} onError - Executed when errors occur.
  34785. */
  34786. load( url, onLoad, onProgress, onError ) {
  34787. const scope = this;
  34788. const loader = new FileLoader( scope.manager );
  34789. loader.setPath( scope.path );
  34790. loader.setRequestHeader( scope.requestHeader );
  34791. loader.setWithCredentials( scope.withCredentials );
  34792. loader.load( url, function ( text ) {
  34793. try {
  34794. onLoad( scope.parse( JSON.parse( text ) ) );
  34795. } catch ( e ) {
  34796. if ( onError ) {
  34797. onError( e );
  34798. } else {
  34799. error( e );
  34800. }
  34801. scope.manager.itemError( url );
  34802. }
  34803. }, onProgress, onError );
  34804. }
  34805. /**
  34806. * Parses the given JSON object and returns a material.
  34807. *
  34808. * @param {Object} json - The serialized material.
  34809. * @return {Material} The parsed material.
  34810. */
  34811. parse( json ) {
  34812. const textures = this.textures;
  34813. function getTexture( name ) {
  34814. if ( textures[ name ] === undefined ) {
  34815. warn( 'MaterialLoader: Undefined texture', name );
  34816. }
  34817. return textures[ name ];
  34818. }
  34819. const material = this.createMaterialFromType( json.type );
  34820. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34821. if ( json.name !== undefined ) material.name = json.name;
  34822. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34823. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34824. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34825. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34826. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34827. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34828. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34829. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34830. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34831. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34832. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34833. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34834. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34835. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34836. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34837. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34838. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34839. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34840. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34841. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34842. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34843. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34844. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34845. if ( json.fog !== undefined ) material.fog = json.fog;
  34846. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34847. if ( json.blending !== undefined ) material.blending = json.blending;
  34848. if ( json.combine !== undefined ) material.combine = json.combine;
  34849. if ( json.side !== undefined ) material.side = json.side;
  34850. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34851. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34852. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34853. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34854. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34855. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34856. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34857. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34858. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34859. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34860. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34861. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34862. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34863. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34864. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34865. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34866. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34867. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34868. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34869. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34870. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34871. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34872. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34873. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34874. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34875. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34876. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34877. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34878. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34879. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34880. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34881. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34882. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34883. if ( json.scale !== undefined ) material.scale = json.scale;
  34884. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34885. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34886. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34887. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34888. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34889. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34890. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34891. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  34892. if ( json.visible !== undefined ) material.visible = json.visible;
  34893. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34894. if ( json.userData !== undefined ) material.userData = json.userData;
  34895. if ( json.vertexColors !== undefined ) {
  34896. if ( typeof json.vertexColors === 'number' ) {
  34897. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34898. } else {
  34899. material.vertexColors = json.vertexColors;
  34900. }
  34901. }
  34902. // Shader Material
  34903. if ( json.uniforms !== undefined ) {
  34904. for ( const name in json.uniforms ) {
  34905. const uniform = json.uniforms[ name ];
  34906. material.uniforms[ name ] = {};
  34907. switch ( uniform.type ) {
  34908. case 't':
  34909. material.uniforms[ name ].value = getTexture( uniform.value );
  34910. break;
  34911. case 'c':
  34912. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34913. break;
  34914. case 'v2':
  34915. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34916. break;
  34917. case 'v3':
  34918. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34919. break;
  34920. case 'v4':
  34921. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34922. break;
  34923. case 'm3':
  34924. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34925. break;
  34926. case 'm4':
  34927. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34928. break;
  34929. default:
  34930. material.uniforms[ name ].value = uniform.value;
  34931. }
  34932. }
  34933. }
  34934. if ( json.defines !== undefined ) material.defines = json.defines;
  34935. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34936. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34937. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34938. if ( json.extensions !== undefined ) {
  34939. for ( const key in json.extensions ) {
  34940. material.extensions[ key ] = json.extensions[ key ];
  34941. }
  34942. }
  34943. if ( json.lights !== undefined ) material.lights = json.lights;
  34944. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34945. // for PointsMaterial
  34946. if ( json.size !== undefined ) material.size = json.size;
  34947. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34948. // maps
  34949. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34950. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34951. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34952. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34953. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34954. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34955. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34956. if ( json.normalScale !== undefined ) {
  34957. let normalScale = json.normalScale;
  34958. if ( Array.isArray( normalScale ) === false ) {
  34959. // Blender exporter used to export a scalar. See #7459
  34960. normalScale = [ normalScale, normalScale ];
  34961. }
  34962. material.normalScale = new Vector2().fromArray( normalScale );
  34963. }
  34964. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34965. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34966. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34967. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34968. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34969. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34970. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34971. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34972. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34973. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34974. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34975. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34976. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34977. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34978. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34979. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34980. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34981. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34982. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34983. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34984. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34985. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34986. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34987. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34988. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34989. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34990. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34991. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34992. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34993. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34994. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34995. return material;
  34996. }
  34997. /**
  34998. * Textures are not embedded in the material JSON so they have
  34999. * to be injected before the loading process starts.
  35000. *
  35001. * @param {Object} value - A dictionary holding textures for material properties.
  35002. * @return {MaterialLoader} A reference to this material loader.
  35003. */
  35004. setTextures( value ) {
  35005. this.textures = value;
  35006. return this;
  35007. }
  35008. /**
  35009. * Creates a material for the given type.
  35010. *
  35011. * @param {string} type - The material type.
  35012. * @return {Material} The new material.
  35013. */
  35014. createMaterialFromType( type ) {
  35015. return MaterialLoader.createMaterialFromType( type );
  35016. }
  35017. /**
  35018. * Creates a material for the given type.
  35019. *
  35020. * @static
  35021. * @param {string} type - The material type.
  35022. * @return {Material} The new material.
  35023. */
  35024. static createMaterialFromType( type ) {
  35025. const materialLib = {
  35026. ShadowMaterial,
  35027. SpriteMaterial,
  35028. RawShaderMaterial,
  35029. ShaderMaterial,
  35030. PointsMaterial,
  35031. MeshPhysicalMaterial,
  35032. MeshStandardMaterial,
  35033. MeshPhongMaterial,
  35034. MeshToonMaterial,
  35035. MeshNormalMaterial,
  35036. MeshLambertMaterial,
  35037. MeshDepthMaterial,
  35038. MeshDistanceMaterial,
  35039. MeshBasicMaterial,
  35040. MeshMatcapMaterial,
  35041. LineDashedMaterial,
  35042. LineBasicMaterial,
  35043. Material
  35044. };
  35045. return new materialLib[ type ]();
  35046. }
  35047. }
  35048. /**
  35049. * A class with loader utility functions.
  35050. */
  35051. class LoaderUtils {
  35052. /**
  35053. * Extracts the base URL from the given URL.
  35054. *
  35055. * @param {string} url -The URL to extract the base URL from.
  35056. * @return {string} The extracted base URL.
  35057. */
  35058. static extractUrlBase( url ) {
  35059. const index = url.lastIndexOf( '/' );
  35060. if ( index === -1 ) return './';
  35061. return url.slice( 0, index + 1 );
  35062. }
  35063. /**
  35064. * Resolves relative URLs against the given path. Absolute paths, data urls,
  35065. * and blob URLs will be returned as is. Invalid URLs will return an empty
  35066. * string.
  35067. *
  35068. * @param {string} url -The URL to resolve.
  35069. * @param {string} path - The base path for relative URLs to be resolved against.
  35070. * @return {string} The resolved URL.
  35071. */
  35072. static resolveURL( url, path ) {
  35073. // Invalid URL
  35074. if ( typeof url !== 'string' || url === '' ) return '';
  35075. // Host Relative URL
  35076. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  35077. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  35078. }
  35079. // Absolute URL http://,https://,//
  35080. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35081. // Data URI
  35082. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35083. // Blob URL
  35084. if ( /^blob:.*$/i.test( url ) ) return url;
  35085. // Relative URL
  35086. return path + url;
  35087. }
  35088. }
  35089. /**
  35090. * An instanced version of a geometry.
  35091. */
  35092. class InstancedBufferGeometry extends BufferGeometry {
  35093. /**
  35094. * Constructs a new instanced buffer geometry.
  35095. */
  35096. constructor() {
  35097. super();
  35098. /**
  35099. * This flag can be used for type testing.
  35100. *
  35101. * @type {boolean}
  35102. * @readonly
  35103. * @default true
  35104. */
  35105. this.isInstancedBufferGeometry = true;
  35106. this.type = 'InstancedBufferGeometry';
  35107. /**
  35108. * The instance count.
  35109. *
  35110. * @type {number}
  35111. * @default Infinity
  35112. */
  35113. this.instanceCount = Infinity;
  35114. }
  35115. copy( source ) {
  35116. super.copy( source );
  35117. this.instanceCount = source.instanceCount;
  35118. return this;
  35119. }
  35120. toJSON() {
  35121. const data = super.toJSON();
  35122. data.instanceCount = this.instanceCount;
  35123. data.isInstancedBufferGeometry = true;
  35124. return data;
  35125. }
  35126. }
  35127. /**
  35128. * Class for loading geometries. The files are internally
  35129. * loaded via {@link FileLoader}.
  35130. *
  35131. * ```js
  35132. * const loader = new THREE.BufferGeometryLoader();
  35133. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  35134. *
  35135. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  35136. * const object = new THREE.Mesh( geometry, material );
  35137. * scene.add( object );
  35138. * ```
  35139. *
  35140. * @augments Loader
  35141. */
  35142. class BufferGeometryLoader extends Loader {
  35143. /**
  35144. * Constructs a new geometry loader.
  35145. *
  35146. * @param {LoadingManager} [manager] - The loading manager.
  35147. */
  35148. constructor( manager ) {
  35149. super( manager );
  35150. }
  35151. /**
  35152. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  35153. *
  35154. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35155. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  35156. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35157. * @param {onErrorCallback} onError - Executed when errors occur.
  35158. */
  35159. load( url, onLoad, onProgress, onError ) {
  35160. const scope = this;
  35161. const loader = new FileLoader( scope.manager );
  35162. loader.setPath( scope.path );
  35163. loader.setRequestHeader( scope.requestHeader );
  35164. loader.setWithCredentials( scope.withCredentials );
  35165. loader.load( url, function ( text ) {
  35166. try {
  35167. onLoad( scope.parse( JSON.parse( text ) ) );
  35168. } catch ( e ) {
  35169. if ( onError ) {
  35170. onError( e );
  35171. } else {
  35172. error( e );
  35173. }
  35174. scope.manager.itemError( url );
  35175. }
  35176. }, onProgress, onError );
  35177. }
  35178. /**
  35179. * Parses the given JSON object and returns a geometry.
  35180. *
  35181. * @param {Object} json - The serialized geometry.
  35182. * @return {BufferGeometry} The parsed geometry.
  35183. */
  35184. parse( json ) {
  35185. const interleavedBufferMap = {};
  35186. const arrayBufferMap = {};
  35187. function getInterleavedBuffer( json, uuid ) {
  35188. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  35189. const interleavedBuffers = json.interleavedBuffers;
  35190. const interleavedBuffer = interleavedBuffers[ uuid ];
  35191. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  35192. const array = getTypedArray( interleavedBuffer.type, buffer );
  35193. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  35194. ib.uuid = interleavedBuffer.uuid;
  35195. interleavedBufferMap[ uuid ] = ib;
  35196. return ib;
  35197. }
  35198. function getArrayBuffer( json, uuid ) {
  35199. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  35200. const arrayBuffers = json.arrayBuffers;
  35201. const arrayBuffer = arrayBuffers[ uuid ];
  35202. const ab = new Uint32Array( arrayBuffer ).buffer;
  35203. arrayBufferMap[ uuid ] = ab;
  35204. return ab;
  35205. }
  35206. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35207. const index = json.data.index;
  35208. if ( index !== undefined ) {
  35209. const typedArray = getTypedArray( index.type, index.array );
  35210. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35211. }
  35212. const attributes = json.data.attributes;
  35213. for ( const key in attributes ) {
  35214. const attribute = attributes[ key ];
  35215. let bufferAttribute;
  35216. if ( attribute.isInterleavedBufferAttribute ) {
  35217. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35218. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35219. } else {
  35220. const typedArray = getTypedArray( attribute.type, attribute.array );
  35221. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35222. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35223. }
  35224. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35225. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35226. geometry.setAttribute( key, bufferAttribute );
  35227. }
  35228. const morphAttributes = json.data.morphAttributes;
  35229. if ( morphAttributes ) {
  35230. for ( const key in morphAttributes ) {
  35231. const attributeArray = morphAttributes[ key ];
  35232. const array = [];
  35233. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35234. const attribute = attributeArray[ i ];
  35235. let bufferAttribute;
  35236. if ( attribute.isInterleavedBufferAttribute ) {
  35237. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35238. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35239. } else {
  35240. const typedArray = getTypedArray( attribute.type, attribute.array );
  35241. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35242. }
  35243. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35244. array.push( bufferAttribute );
  35245. }
  35246. geometry.morphAttributes[ key ] = array;
  35247. }
  35248. }
  35249. const morphTargetsRelative = json.data.morphTargetsRelative;
  35250. if ( morphTargetsRelative ) {
  35251. geometry.morphTargetsRelative = true;
  35252. }
  35253. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35254. if ( groups !== undefined ) {
  35255. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35256. const group = groups[ i ];
  35257. geometry.addGroup( group.start, group.count, group.materialIndex );
  35258. }
  35259. }
  35260. const boundingSphere = json.data.boundingSphere;
  35261. if ( boundingSphere !== undefined ) {
  35262. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35263. }
  35264. if ( json.name ) geometry.name = json.name;
  35265. if ( json.userData ) geometry.userData = json.userData;
  35266. return geometry;
  35267. }
  35268. }
  35269. /**
  35270. * 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).
  35271. * The files are internally loaded via {@link FileLoader}.
  35272. *
  35273. * ```js
  35274. * const loader = new THREE.ObjectLoader();
  35275. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35276. * scene.add( obj );
  35277. *
  35278. * // Alternatively, to parse a previously loaded JSON structure
  35279. * const object = await loader.parseAsync( a_json_object );
  35280. * scene.add( object );
  35281. * ```
  35282. *
  35283. * @augments Loader
  35284. */
  35285. class ObjectLoader extends Loader {
  35286. /**
  35287. * Constructs a new object loader.
  35288. *
  35289. * @param {LoadingManager} [manager] - The loading manager.
  35290. */
  35291. constructor( manager ) {
  35292. super( manager );
  35293. }
  35294. /**
  35295. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35296. *
  35297. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35298. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35299. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35300. * @param {onErrorCallback} onError - Executed when errors occur.
  35301. */
  35302. load( url, onLoad, onProgress, onError ) {
  35303. const scope = this;
  35304. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35305. this.resourcePath = this.resourcePath || path;
  35306. const loader = new FileLoader( this.manager );
  35307. loader.setPath( this.path );
  35308. loader.setRequestHeader( this.requestHeader );
  35309. loader.setWithCredentials( this.withCredentials );
  35310. loader.load( url, function ( text ) {
  35311. let json = null;
  35312. try {
  35313. json = JSON.parse( text );
  35314. } catch ( error ) {
  35315. if ( onError !== undefined ) onError( error );
  35316. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  35317. return;
  35318. }
  35319. const metadata = json.metadata;
  35320. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35321. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35322. error( 'ObjectLoader: Can\'t load ' + url );
  35323. return;
  35324. }
  35325. scope.parse( json, onLoad );
  35326. }, onProgress, onError );
  35327. }
  35328. /**
  35329. * Async version of {@link ObjectLoader#load}.
  35330. *
  35331. * @async
  35332. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35333. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35334. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35335. */
  35336. async loadAsync( url, onProgress ) {
  35337. const scope = this;
  35338. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35339. this.resourcePath = this.resourcePath || path;
  35340. const loader = new FileLoader( this.manager );
  35341. loader.setPath( this.path );
  35342. loader.setRequestHeader( this.requestHeader );
  35343. loader.setWithCredentials( this.withCredentials );
  35344. const text = await loader.loadAsync( url, onProgress );
  35345. const json = JSON.parse( text );
  35346. const metadata = json.metadata;
  35347. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35348. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35349. }
  35350. return await scope.parseAsync( json );
  35351. }
  35352. /**
  35353. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35354. * but can also be used directly to parse a previously loaded JSON structure.
  35355. *
  35356. * @param {Object} json - The serialized 3D object.
  35357. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35358. * @return {Object3D} The parsed 3D object.
  35359. */
  35360. parse( json, onLoad ) {
  35361. const animations = this.parseAnimations( json.animations );
  35362. const shapes = this.parseShapes( json.shapes );
  35363. const geometries = this.parseGeometries( json.geometries, shapes );
  35364. const images = this.parseImages( json.images, function () {
  35365. if ( onLoad !== undefined ) onLoad( object );
  35366. } );
  35367. const textures = this.parseTextures( json.textures, images );
  35368. const materials = this.parseMaterials( json.materials, textures );
  35369. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35370. const skeletons = this.parseSkeletons( json.skeletons, object );
  35371. this.bindSkeletons( object, skeletons );
  35372. this.bindLightTargets( object );
  35373. //
  35374. if ( onLoad !== undefined ) {
  35375. let hasImages = false;
  35376. for ( const uuid in images ) {
  35377. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35378. hasImages = true;
  35379. break;
  35380. }
  35381. }
  35382. if ( hasImages === false ) onLoad( object );
  35383. }
  35384. return object;
  35385. }
  35386. /**
  35387. * Async version of {@link ObjectLoader#parse}.
  35388. *
  35389. * @param {Object} json - The serialized 3D object.
  35390. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35391. */
  35392. async parseAsync( json ) {
  35393. const animations = this.parseAnimations( json.animations );
  35394. const shapes = this.parseShapes( json.shapes );
  35395. const geometries = this.parseGeometries( json.geometries, shapes );
  35396. const images = await this.parseImagesAsync( json.images );
  35397. const textures = this.parseTextures( json.textures, images );
  35398. const materials = this.parseMaterials( json.materials, textures );
  35399. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35400. const skeletons = this.parseSkeletons( json.skeletons, object );
  35401. this.bindSkeletons( object, skeletons );
  35402. this.bindLightTargets( object );
  35403. return object;
  35404. }
  35405. // internals
  35406. parseShapes( json ) {
  35407. const shapes = {};
  35408. if ( json !== undefined ) {
  35409. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35410. const shape = new Shape().fromJSON( json[ i ] );
  35411. shapes[ shape.uuid ] = shape;
  35412. }
  35413. }
  35414. return shapes;
  35415. }
  35416. parseSkeletons( json, object ) {
  35417. const skeletons = {};
  35418. const bones = {};
  35419. // generate bone lookup table
  35420. object.traverse( function ( child ) {
  35421. if ( child.isBone ) bones[ child.uuid ] = child;
  35422. } );
  35423. // create skeletons
  35424. if ( json !== undefined ) {
  35425. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35426. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35427. skeletons[ skeleton.uuid ] = skeleton;
  35428. }
  35429. }
  35430. return skeletons;
  35431. }
  35432. parseGeometries( json, shapes ) {
  35433. const geometries = {};
  35434. if ( json !== undefined ) {
  35435. const bufferGeometryLoader = new BufferGeometryLoader();
  35436. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35437. let geometry;
  35438. const data = json[ i ];
  35439. switch ( data.type ) {
  35440. case 'BufferGeometry':
  35441. case 'InstancedBufferGeometry':
  35442. geometry = bufferGeometryLoader.parse( data );
  35443. break;
  35444. default:
  35445. if ( data.type in Geometries ) {
  35446. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35447. } else {
  35448. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35449. }
  35450. }
  35451. geometry.uuid = data.uuid;
  35452. if ( data.name !== undefined ) geometry.name = data.name;
  35453. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35454. geometries[ data.uuid ] = geometry;
  35455. }
  35456. }
  35457. return geometries;
  35458. }
  35459. parseMaterials( json, textures ) {
  35460. const cache = {}; // MultiMaterial
  35461. const materials = {};
  35462. if ( json !== undefined ) {
  35463. const loader = new MaterialLoader();
  35464. loader.setTextures( textures );
  35465. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35466. const data = json[ i ];
  35467. if ( cache[ data.uuid ] === undefined ) {
  35468. cache[ data.uuid ] = loader.parse( data );
  35469. }
  35470. materials[ data.uuid ] = cache[ data.uuid ];
  35471. }
  35472. }
  35473. return materials;
  35474. }
  35475. parseAnimations( json ) {
  35476. const animations = {};
  35477. if ( json !== undefined ) {
  35478. for ( let i = 0; i < json.length; i ++ ) {
  35479. const data = json[ i ];
  35480. const clip = AnimationClip.parse( data );
  35481. animations[ clip.uuid ] = clip;
  35482. }
  35483. }
  35484. return animations;
  35485. }
  35486. parseImages( json, onLoad ) {
  35487. const scope = this;
  35488. const images = {};
  35489. let loader;
  35490. function loadImage( url ) {
  35491. scope.manager.itemStart( url );
  35492. return loader.load( url, function () {
  35493. scope.manager.itemEnd( url );
  35494. }, undefined, function () {
  35495. scope.manager.itemError( url );
  35496. scope.manager.itemEnd( url );
  35497. } );
  35498. }
  35499. function deserializeImage( image ) {
  35500. if ( typeof image === 'string' ) {
  35501. const url = image;
  35502. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35503. return loadImage( path );
  35504. } else {
  35505. if ( image.data ) {
  35506. return {
  35507. data: getTypedArray( image.type, image.data ),
  35508. width: image.width,
  35509. height: image.height
  35510. };
  35511. } else {
  35512. return null;
  35513. }
  35514. }
  35515. }
  35516. if ( json !== undefined && json.length > 0 ) {
  35517. const manager = new LoadingManager( onLoad );
  35518. loader = new ImageLoader( manager );
  35519. loader.setCrossOrigin( this.crossOrigin );
  35520. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35521. const image = json[ i ];
  35522. const url = image.url;
  35523. if ( Array.isArray( url ) ) {
  35524. // load array of images e.g CubeTexture
  35525. const imageArray = [];
  35526. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35527. const currentUrl = url[ j ];
  35528. const deserializedImage = deserializeImage( currentUrl );
  35529. if ( deserializedImage !== null ) {
  35530. if ( deserializedImage instanceof HTMLImageElement ) {
  35531. imageArray.push( deserializedImage );
  35532. } else {
  35533. // special case: handle array of data textures for cube textures
  35534. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35535. }
  35536. }
  35537. }
  35538. images[ image.uuid ] = new Source( imageArray );
  35539. } else {
  35540. // load single image
  35541. const deserializedImage = deserializeImage( image.url );
  35542. images[ image.uuid ] = new Source( deserializedImage );
  35543. }
  35544. }
  35545. }
  35546. return images;
  35547. }
  35548. async parseImagesAsync( json ) {
  35549. const scope = this;
  35550. const images = {};
  35551. let loader;
  35552. async function deserializeImage( image ) {
  35553. if ( typeof image === 'string' ) {
  35554. const url = image;
  35555. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35556. return await loader.loadAsync( path );
  35557. } else {
  35558. if ( image.data ) {
  35559. return {
  35560. data: getTypedArray( image.type, image.data ),
  35561. width: image.width,
  35562. height: image.height
  35563. };
  35564. } else {
  35565. return null;
  35566. }
  35567. }
  35568. }
  35569. if ( json !== undefined && json.length > 0 ) {
  35570. loader = new ImageLoader( this.manager );
  35571. loader.setCrossOrigin( this.crossOrigin );
  35572. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35573. const image = json[ i ];
  35574. const url = image.url;
  35575. if ( Array.isArray( url ) ) {
  35576. // load array of images e.g CubeTexture
  35577. const imageArray = [];
  35578. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35579. const currentUrl = url[ j ];
  35580. const deserializedImage = await deserializeImage( currentUrl );
  35581. if ( deserializedImage !== null ) {
  35582. if ( deserializedImage instanceof HTMLImageElement ) {
  35583. imageArray.push( deserializedImage );
  35584. } else {
  35585. // special case: handle array of data textures for cube textures
  35586. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35587. }
  35588. }
  35589. }
  35590. images[ image.uuid ] = new Source( imageArray );
  35591. } else {
  35592. // load single image
  35593. const deserializedImage = await deserializeImage( image.url );
  35594. images[ image.uuid ] = new Source( deserializedImage );
  35595. }
  35596. }
  35597. }
  35598. return images;
  35599. }
  35600. parseTextures( json, images ) {
  35601. function parseConstant( value, type ) {
  35602. if ( typeof value === 'number' ) return value;
  35603. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35604. return type[ value ];
  35605. }
  35606. const textures = {};
  35607. if ( json !== undefined ) {
  35608. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35609. const data = json[ i ];
  35610. if ( data.image === undefined ) {
  35611. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35612. }
  35613. if ( images[ data.image ] === undefined ) {
  35614. warn( 'ObjectLoader: Undefined image', data.image );
  35615. }
  35616. const source = images[ data.image ];
  35617. const image = source.data;
  35618. let texture;
  35619. if ( Array.isArray( image ) ) {
  35620. texture = new CubeTexture();
  35621. if ( image.length === 6 ) texture.needsUpdate = true;
  35622. } else {
  35623. if ( image && image.data ) {
  35624. texture = new DataTexture();
  35625. } else {
  35626. texture = new Texture();
  35627. }
  35628. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35629. }
  35630. texture.source = source;
  35631. texture.uuid = data.uuid;
  35632. if ( data.name !== undefined ) texture.name = data.name;
  35633. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35634. if ( data.channel !== undefined ) texture.channel = data.channel;
  35635. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35636. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35637. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35638. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35639. if ( data.wrap !== undefined ) {
  35640. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35641. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35642. }
  35643. if ( data.format !== undefined ) texture.format = data.format;
  35644. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35645. if ( data.type !== undefined ) texture.type = data.type;
  35646. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35647. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35648. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35649. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35650. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35651. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35652. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35653. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35654. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35655. if ( data.userData !== undefined ) texture.userData = data.userData;
  35656. textures[ data.uuid ] = texture;
  35657. }
  35658. }
  35659. return textures;
  35660. }
  35661. parseObject( data, geometries, materials, textures, animations ) {
  35662. let object;
  35663. function getGeometry( name ) {
  35664. if ( geometries[ name ] === undefined ) {
  35665. warn( 'ObjectLoader: Undefined geometry', name );
  35666. }
  35667. return geometries[ name ];
  35668. }
  35669. function getMaterial( name ) {
  35670. if ( name === undefined ) return undefined;
  35671. if ( Array.isArray( name ) ) {
  35672. const array = [];
  35673. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35674. const uuid = name[ i ];
  35675. if ( materials[ uuid ] === undefined ) {
  35676. warn( 'ObjectLoader: Undefined material', uuid );
  35677. }
  35678. array.push( materials[ uuid ] );
  35679. }
  35680. return array;
  35681. }
  35682. if ( materials[ name ] === undefined ) {
  35683. warn( 'ObjectLoader: Undefined material', name );
  35684. }
  35685. return materials[ name ];
  35686. }
  35687. function getTexture( uuid ) {
  35688. if ( textures[ uuid ] === undefined ) {
  35689. warn( 'ObjectLoader: Undefined texture', uuid );
  35690. }
  35691. return textures[ uuid ];
  35692. }
  35693. let geometry, material;
  35694. switch ( data.type ) {
  35695. case 'Scene':
  35696. object = new Scene();
  35697. if ( data.background !== undefined ) {
  35698. if ( Number.isInteger( data.background ) ) {
  35699. object.background = new Color( data.background );
  35700. } else {
  35701. object.background = getTexture( data.background );
  35702. }
  35703. }
  35704. if ( data.environment !== undefined ) {
  35705. object.environment = getTexture( data.environment );
  35706. }
  35707. if ( data.fog !== undefined ) {
  35708. if ( data.fog.type === 'Fog' ) {
  35709. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35710. } else if ( data.fog.type === 'FogExp2' ) {
  35711. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35712. }
  35713. if ( data.fog.name !== '' ) {
  35714. object.fog.name = data.fog.name;
  35715. }
  35716. }
  35717. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35718. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35719. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35720. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35721. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35722. break;
  35723. case 'PerspectiveCamera':
  35724. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35725. if ( data.focus !== undefined ) object.focus = data.focus;
  35726. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35727. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35728. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35729. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35730. break;
  35731. case 'OrthographicCamera':
  35732. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35733. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35734. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35735. break;
  35736. case 'AmbientLight':
  35737. object = new AmbientLight( data.color, data.intensity );
  35738. break;
  35739. case 'DirectionalLight':
  35740. object = new DirectionalLight( data.color, data.intensity );
  35741. object.target = data.target || '';
  35742. break;
  35743. case 'PointLight':
  35744. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35745. break;
  35746. case 'RectAreaLight':
  35747. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35748. break;
  35749. case 'SpotLight':
  35750. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35751. object.target = data.target || '';
  35752. break;
  35753. case 'HemisphereLight':
  35754. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35755. break;
  35756. case 'LightProbe':
  35757. const sh = new SphericalHarmonics3().fromArray( data.sh );
  35758. object = new LightProbe( sh, data.intensity );
  35759. break;
  35760. case 'SkinnedMesh':
  35761. geometry = getGeometry( data.geometry );
  35762. material = getMaterial( data.material );
  35763. object = new SkinnedMesh( geometry, material );
  35764. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35765. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35766. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35767. break;
  35768. case 'Mesh':
  35769. geometry = getGeometry( data.geometry );
  35770. material = getMaterial( data.material );
  35771. object = new Mesh( geometry, material );
  35772. break;
  35773. case 'InstancedMesh':
  35774. geometry = getGeometry( data.geometry );
  35775. material = getMaterial( data.material );
  35776. const count = data.count;
  35777. const instanceMatrix = data.instanceMatrix;
  35778. const instanceColor = data.instanceColor;
  35779. object = new InstancedMesh( geometry, material, count );
  35780. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35781. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35782. break;
  35783. case 'BatchedMesh':
  35784. geometry = getGeometry( data.geometry );
  35785. material = getMaterial( data.material );
  35786. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35787. object.geometry = geometry;
  35788. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35789. object.sortObjects = data.sortObjects;
  35790. object._drawRanges = data.drawRanges;
  35791. object._reservedRanges = data.reservedRanges;
  35792. object._geometryInfo = data.geometryInfo.map( info => {
  35793. let box = null;
  35794. let sphere = null;
  35795. if ( info.boundingBox !== undefined ) {
  35796. box = new Box3().fromJSON( info.boundingBox );
  35797. }
  35798. if ( info.boundingSphere !== undefined ) {
  35799. sphere = new Sphere().fromJSON( info.boundingSphere );
  35800. }
  35801. return {
  35802. ...info,
  35803. boundingBox: box,
  35804. boundingSphere: sphere
  35805. };
  35806. } );
  35807. object._instanceInfo = data.instanceInfo;
  35808. object._availableInstanceIds = data._availableInstanceIds;
  35809. object._availableGeometryIds = data._availableGeometryIds;
  35810. object._nextIndexStart = data.nextIndexStart;
  35811. object._nextVertexStart = data.nextVertexStart;
  35812. object._geometryCount = data.geometryCount;
  35813. object._maxInstanceCount = data.maxInstanceCount;
  35814. object._maxVertexCount = data.maxVertexCount;
  35815. object._maxIndexCount = data.maxIndexCount;
  35816. object._geometryInitialized = data.geometryInitialized;
  35817. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35818. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35819. if ( data.colorsTexture !== undefined ) {
  35820. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35821. }
  35822. if ( data.boundingSphere !== undefined ) {
  35823. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35824. }
  35825. if ( data.boundingBox !== undefined ) {
  35826. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35827. }
  35828. break;
  35829. case 'LOD':
  35830. object = new LOD();
  35831. break;
  35832. case 'Line':
  35833. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35834. break;
  35835. case 'LineLoop':
  35836. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35837. break;
  35838. case 'LineSegments':
  35839. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35840. break;
  35841. case 'PointCloud':
  35842. case 'Points':
  35843. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35844. break;
  35845. case 'Sprite':
  35846. object = new Sprite( getMaterial( data.material ) );
  35847. break;
  35848. case 'Group':
  35849. object = new Group();
  35850. break;
  35851. case 'Bone':
  35852. object = new Bone();
  35853. break;
  35854. default:
  35855. object = new Object3D();
  35856. }
  35857. object.uuid = data.uuid;
  35858. if ( data.name !== undefined ) object.name = data.name;
  35859. if ( data.matrix !== undefined ) {
  35860. object.matrix.fromArray( data.matrix );
  35861. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35862. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35863. } else {
  35864. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35865. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35866. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35867. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35868. }
  35869. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35870. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  35871. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35872. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35873. if ( data.shadow ) {
  35874. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35875. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35876. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35877. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35878. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35879. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35880. }
  35881. if ( data.visible !== undefined ) object.visible = data.visible;
  35882. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35883. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35884. if ( data.static !== undefined ) object.static = data.static;
  35885. if ( data.userData !== undefined ) object.userData = data.userData;
  35886. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35887. if ( data.children !== undefined ) {
  35888. const children = data.children;
  35889. for ( let i = 0; i < children.length; i ++ ) {
  35890. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35891. }
  35892. }
  35893. if ( data.animations !== undefined ) {
  35894. const objectAnimations = data.animations;
  35895. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35896. const uuid = objectAnimations[ i ];
  35897. object.animations.push( animations[ uuid ] );
  35898. }
  35899. }
  35900. if ( data.type === 'LOD' ) {
  35901. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35902. const levels = data.levels;
  35903. for ( let l = 0; l < levels.length; l ++ ) {
  35904. const level = levels[ l ];
  35905. const child = object.getObjectByProperty( 'uuid', level.object );
  35906. if ( child !== undefined ) {
  35907. object.addLevel( child, level.distance, level.hysteresis );
  35908. }
  35909. }
  35910. }
  35911. return object;
  35912. }
  35913. bindSkeletons( object, skeletons ) {
  35914. if ( Object.keys( skeletons ).length === 0 ) return;
  35915. object.traverse( function ( child ) {
  35916. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35917. const skeleton = skeletons[ child.skeleton ];
  35918. if ( skeleton === undefined ) {
  35919. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35920. } else {
  35921. child.bind( skeleton, child.bindMatrix );
  35922. }
  35923. }
  35924. } );
  35925. }
  35926. bindLightTargets( object ) {
  35927. object.traverse( function ( child ) {
  35928. if ( child.isDirectionalLight || child.isSpotLight ) {
  35929. const uuid = child.target;
  35930. const target = object.getObjectByProperty( 'uuid', uuid );
  35931. if ( target !== undefined ) {
  35932. child.target = target;
  35933. } else {
  35934. child.target = new Object3D();
  35935. }
  35936. }
  35937. } );
  35938. }
  35939. }
  35940. const TEXTURE_MAPPING = {
  35941. UVMapping: UVMapping,
  35942. CubeReflectionMapping: CubeReflectionMapping,
  35943. CubeRefractionMapping: CubeRefractionMapping,
  35944. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35945. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35946. CubeUVReflectionMapping: CubeUVReflectionMapping
  35947. };
  35948. const TEXTURE_WRAPPING = {
  35949. RepeatWrapping: RepeatWrapping,
  35950. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35951. MirroredRepeatWrapping: MirroredRepeatWrapping
  35952. };
  35953. const TEXTURE_FILTER = {
  35954. NearestFilter: NearestFilter,
  35955. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35956. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35957. LinearFilter: LinearFilter,
  35958. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35959. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35960. };
  35961. const _errorMap = new WeakMap();
  35962. /**
  35963. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  35964. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35965. * textures for rendering.
  35966. *
  35967. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35968. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  35969. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  35970. *
  35971. * To match the default behaviour of {@link Texture}, the following options are needed:
  35972. *
  35973. * ```js
  35974. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  35975. * ```
  35976. *
  35977. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  35978. *
  35979. * ```js
  35980. * const loader = new THREE.ImageBitmapLoader();
  35981. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35982. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35983. *
  35984. * const texture = new THREE.Texture( imageBitmap );
  35985. * texture.needsUpdate = true;
  35986. * ```
  35987. *
  35988. * @augments Loader
  35989. */
  35990. class ImageBitmapLoader extends Loader {
  35991. /**
  35992. * Constructs a new image bitmap loader.
  35993. *
  35994. * @param {LoadingManager} [manager] - The loading manager.
  35995. */
  35996. constructor( manager ) {
  35997. super( manager );
  35998. /**
  35999. * This flag can be used for type testing.
  36000. *
  36001. * @type {boolean}
  36002. * @readonly
  36003. * @default true
  36004. */
  36005. this.isImageBitmapLoader = true;
  36006. if ( typeof createImageBitmap === 'undefined' ) {
  36007. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  36008. }
  36009. if ( typeof fetch === 'undefined' ) {
  36010. warn( 'ImageBitmapLoader: fetch() not supported.' );
  36011. }
  36012. /**
  36013. * Represents the loader options.
  36014. *
  36015. * @type {Object}
  36016. * @default {premultiplyAlpha:'none'}
  36017. */
  36018. this.options = { premultiplyAlpha: 'none' };
  36019. /**
  36020. * Used for aborting requests.
  36021. *
  36022. * @private
  36023. * @type {AbortController}
  36024. */
  36025. this._abortController = new AbortController();
  36026. }
  36027. /**
  36028. * Sets the given loader options. The structure of the object must match the `options` parameter of
  36029. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  36030. *
  36031. * @param {Object} options - The loader options to set.
  36032. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  36033. */
  36034. setOptions( options ) {
  36035. this.options = options;
  36036. return this;
  36037. }
  36038. /**
  36039. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  36040. *
  36041. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36042. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  36043. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  36044. * @param {onErrorCallback} onError - Executed when errors occur.
  36045. * @return {ImageBitmap|undefined} The image bitmap.
  36046. */
  36047. load( url, onLoad, onProgress, onError ) {
  36048. if ( url === undefined ) url = '';
  36049. if ( this.path !== undefined ) url = this.path + url;
  36050. url = this.manager.resolveURL( url );
  36051. const scope = this;
  36052. const cached = Cache.get( `image-bitmap:${url}` );
  36053. if ( cached !== undefined ) {
  36054. scope.manager.itemStart( url );
  36055. // If cached is a promise, wait for it to resolve
  36056. if ( cached.then ) {
  36057. cached.then( imageBitmap => {
  36058. // check if there is an error for the cached promise
  36059. if ( _errorMap.has( cached ) === true ) {
  36060. if ( onError ) onError( _errorMap.get( cached ) );
  36061. scope.manager.itemError( url );
  36062. scope.manager.itemEnd( url );
  36063. } else {
  36064. if ( onLoad ) onLoad( imageBitmap );
  36065. scope.manager.itemEnd( url );
  36066. return imageBitmap;
  36067. }
  36068. } );
  36069. return;
  36070. }
  36071. // If cached is not a promise (i.e., it's already an imageBitmap)
  36072. setTimeout( function () {
  36073. if ( onLoad ) onLoad( cached );
  36074. scope.manager.itemEnd( url );
  36075. }, 0 );
  36076. return cached;
  36077. }
  36078. const fetchOptions = {};
  36079. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  36080. fetchOptions.headers = this.requestHeader;
  36081. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  36082. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  36083. return res.blob();
  36084. } ).then( function ( blob ) {
  36085. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  36086. } ).then( function ( imageBitmap ) {
  36087. Cache.add( `image-bitmap:${url}`, imageBitmap );
  36088. if ( onLoad ) onLoad( imageBitmap );
  36089. scope.manager.itemEnd( url );
  36090. return imageBitmap;
  36091. } ).catch( function ( e ) {
  36092. if ( onError ) onError( e );
  36093. _errorMap.set( promise, e );
  36094. Cache.remove( `image-bitmap:${url}` );
  36095. scope.manager.itemError( url );
  36096. scope.manager.itemEnd( url );
  36097. } );
  36098. Cache.add( `image-bitmap:${url}`, promise );
  36099. scope.manager.itemStart( url );
  36100. }
  36101. /**
  36102. * Aborts ongoing fetch requests.
  36103. *
  36104. * @return {ImageBitmapLoader} A reference to this instance.
  36105. */
  36106. abort() {
  36107. this._abortController.abort();
  36108. this._abortController = new AbortController();
  36109. return this;
  36110. }
  36111. }
  36112. let _context;
  36113. /**
  36114. * Manages the global audio context in the engine.
  36115. *
  36116. * @hideconstructor
  36117. */
  36118. class AudioContext {
  36119. /**
  36120. * Returns the global native audio context.
  36121. *
  36122. * @return {AudioContext} The native audio context.
  36123. */
  36124. static getContext() {
  36125. if ( _context === undefined ) {
  36126. _context = new ( window.AudioContext || window.webkitAudioContext )();
  36127. }
  36128. return _context;
  36129. }
  36130. /**
  36131. * Allows to set the global native audio context from outside.
  36132. *
  36133. * @param {AudioContext} value - The native context to set.
  36134. */
  36135. static setContext( value ) {
  36136. _context = value;
  36137. }
  36138. }
  36139. /**
  36140. * Class for loading audio buffers. Audios are internally
  36141. * loaded via {@link FileLoader}.
  36142. *
  36143. * ```js
  36144. * const audioListener = new THREE.AudioListener();
  36145. * const ambientSound = new THREE.Audio( audioListener );
  36146. *
  36147. * const loader = new THREE.AudioLoader();
  36148. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  36149. *
  36150. * ambientSound.setBuffer( audioBuffer );
  36151. * ambientSound.play();
  36152. * ```
  36153. *
  36154. * @augments Loader
  36155. */
  36156. class AudioLoader extends Loader {
  36157. /**
  36158. * Constructs a new audio loader.
  36159. *
  36160. * @param {LoadingManager} [manager] - The loading manager.
  36161. */
  36162. constructor( manager ) {
  36163. super( manager );
  36164. }
  36165. /**
  36166. * Starts loading from the given URL and passes the loaded audio buffer
  36167. * to the `onLoad()` callback.
  36168. *
  36169. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36170. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  36171. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36172. * @param {onErrorCallback} onError - Executed when errors occur.
  36173. */
  36174. load( url, onLoad, onProgress, onError ) {
  36175. const scope = this;
  36176. const loader = new FileLoader( this.manager );
  36177. loader.setResponseType( 'arraybuffer' );
  36178. loader.setPath( this.path );
  36179. loader.setRequestHeader( this.requestHeader );
  36180. loader.setWithCredentials( this.withCredentials );
  36181. loader.load( url, function ( buffer ) {
  36182. try {
  36183. // Create a copy of the buffer. The `decodeAudioData` method
  36184. // detaches the buffer when complete, preventing reuse.
  36185. const bufferCopy = buffer.slice( 0 );
  36186. const context = AudioContext.getContext();
  36187. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  36188. onLoad( audioBuffer );
  36189. } ).catch( handleError );
  36190. } catch ( e ) {
  36191. handleError( e );
  36192. }
  36193. }, onProgress, onError );
  36194. function handleError( e ) {
  36195. if ( onError ) {
  36196. onError( e );
  36197. } else {
  36198. error( e );
  36199. }
  36200. scope.manager.itemError( url );
  36201. }
  36202. }
  36203. }
  36204. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36205. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36206. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36207. /**
  36208. * A special type of camera that uses two perspective cameras with
  36209. * stereoscopic projection. Can be used for rendering stereo effects
  36210. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36211. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36212. */
  36213. class StereoCamera {
  36214. /**
  36215. * Constructs a new stereo camera.
  36216. */
  36217. constructor() {
  36218. /**
  36219. * The type property is used for detecting the object type
  36220. * in context of serialization/deserialization.
  36221. *
  36222. * @type {string}
  36223. * @readonly
  36224. */
  36225. this.type = 'StereoCamera';
  36226. /**
  36227. * The aspect.
  36228. *
  36229. * @type {number}
  36230. * @default 1
  36231. */
  36232. this.aspect = 1;
  36233. /**
  36234. * The eye separation which represents the distance
  36235. * between the left and right camera.
  36236. *
  36237. * @type {number}
  36238. * @default 0.064
  36239. */
  36240. this.eyeSep = 0.064;
  36241. /**
  36242. * The camera representing the left eye. This is added to layer `1` so objects to be
  36243. * rendered by the left camera must also be added to this layer.
  36244. *
  36245. * @type {PerspectiveCamera}
  36246. */
  36247. this.cameraL = new PerspectiveCamera();
  36248. this.cameraL.layers.enable( 1 );
  36249. this.cameraL.matrixAutoUpdate = false;
  36250. /**
  36251. * The camera representing the right eye. This is added to layer `2` so objects to be
  36252. * rendered by the right camera must also be added to this layer.
  36253. *
  36254. * @type {PerspectiveCamera}
  36255. */
  36256. this.cameraR = new PerspectiveCamera();
  36257. this.cameraR.layers.enable( 2 );
  36258. this.cameraR.matrixAutoUpdate = false;
  36259. this._cache = {
  36260. focus: null,
  36261. fov: null,
  36262. aspect: null,
  36263. near: null,
  36264. far: null,
  36265. zoom: null,
  36266. eyeSep: null
  36267. };
  36268. }
  36269. /**
  36270. * Updates the stereo camera based on the given perspective camera.
  36271. *
  36272. * @param {PerspectiveCamera} camera - The perspective camera.
  36273. */
  36274. update( camera ) {
  36275. const cache = this._cache;
  36276. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36277. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36278. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36279. if ( needsUpdate ) {
  36280. cache.focus = camera.focus;
  36281. cache.fov = camera.fov;
  36282. cache.aspect = camera.aspect * this.aspect;
  36283. cache.near = camera.near;
  36284. cache.far = camera.far;
  36285. cache.zoom = camera.zoom;
  36286. cache.eyeSep = this.eyeSep;
  36287. // Off-axis stereoscopic effect based on
  36288. // http://paulbourke.net/stereographics/stereorender/
  36289. _projectionMatrix.copy( camera.projectionMatrix );
  36290. const eyeSepHalf = cache.eyeSep / 2;
  36291. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36292. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36293. let xmin, xmax;
  36294. // translate xOffset
  36295. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36296. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36297. // for left eye
  36298. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36299. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36300. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36301. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36302. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36303. // for right eye
  36304. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36305. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36306. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36307. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36308. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36309. }
  36310. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36311. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36312. }
  36313. }
  36314. /**
  36315. * This type of camera can be used in order to efficiently render a scene with a
  36316. * predefined set of cameras. This is an important performance aspect for
  36317. * rendering VR scenes.
  36318. *
  36319. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36320. * to define for each sub camera the `viewport` property which determines the
  36321. * part of the viewport that is rendered with this camera.
  36322. *
  36323. * @augments PerspectiveCamera
  36324. */
  36325. class ArrayCamera extends PerspectiveCamera {
  36326. /**
  36327. * Constructs a new array camera.
  36328. *
  36329. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36330. */
  36331. constructor( array = [] ) {
  36332. super();
  36333. /**
  36334. * This flag can be used for type testing.
  36335. *
  36336. * @type {boolean}
  36337. * @readonly
  36338. * @default true
  36339. */
  36340. this.isArrayCamera = true;
  36341. /**
  36342. * Whether this camera is used with multiview rendering or not.
  36343. *
  36344. * @type {boolean}
  36345. * @readonly
  36346. * @default false
  36347. */
  36348. this.isMultiViewCamera = false;
  36349. /**
  36350. * An array of perspective sub cameras.
  36351. *
  36352. * @type {Array<PerspectiveCamera>}
  36353. */
  36354. this.cameras = array;
  36355. }
  36356. }
  36357. /**
  36358. * Class for keeping track of time.
  36359. */
  36360. class Clock {
  36361. /**
  36362. * Constructs a new clock.
  36363. *
  36364. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  36365. * `getDelta()` is called for the first time.
  36366. */
  36367. constructor( autoStart = true ) {
  36368. /**
  36369. * If set to `true`, the clock starts automatically when `getDelta()` is called
  36370. * for the first time.
  36371. *
  36372. * @type {boolean}
  36373. * @default true
  36374. */
  36375. this.autoStart = autoStart;
  36376. /**
  36377. * Holds the time at which the clock's `start()` method was last called.
  36378. *
  36379. * @type {number}
  36380. * @default 0
  36381. */
  36382. this.startTime = 0;
  36383. /**
  36384. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  36385. * `getDelta()` methods were last called.
  36386. *
  36387. * @type {number}
  36388. * @default 0
  36389. */
  36390. this.oldTime = 0;
  36391. /**
  36392. * Keeps track of the total time that the clock has been running.
  36393. *
  36394. * @type {number}
  36395. * @default 0
  36396. */
  36397. this.elapsedTime = 0;
  36398. /**
  36399. * Whether the clock is running or not.
  36400. *
  36401. * @type {boolean}
  36402. * @default true
  36403. */
  36404. this.running = false;
  36405. }
  36406. /**
  36407. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  36408. * called by the class.
  36409. */
  36410. start() {
  36411. this.startTime = performance.now();
  36412. this.oldTime = this.startTime;
  36413. this.elapsedTime = 0;
  36414. this.running = true;
  36415. }
  36416. /**
  36417. * Stops the clock.
  36418. */
  36419. stop() {
  36420. this.getElapsedTime();
  36421. this.running = false;
  36422. this.autoStart = false;
  36423. }
  36424. /**
  36425. * Returns the elapsed time in seconds.
  36426. *
  36427. * @return {number} The elapsed time.
  36428. */
  36429. getElapsedTime() {
  36430. this.getDelta();
  36431. return this.elapsedTime;
  36432. }
  36433. /**
  36434. * Returns the delta time in seconds.
  36435. *
  36436. * @return {number} The delta time.
  36437. */
  36438. getDelta() {
  36439. let diff = 0;
  36440. if ( this.autoStart && ! this.running ) {
  36441. this.start();
  36442. return 0;
  36443. }
  36444. if ( this.running ) {
  36445. const newTime = performance.now();
  36446. diff = ( newTime - this.oldTime ) / 1000;
  36447. this.oldTime = newTime;
  36448. this.elapsedTime += diff;
  36449. }
  36450. return diff;
  36451. }
  36452. }
  36453. const _position$1 = /*@__PURE__*/ new Vector3();
  36454. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36455. const _scale$1 = /*@__PURE__*/ new Vector3();
  36456. const _forward = /*@__PURE__*/ new Vector3();
  36457. const _up = /*@__PURE__*/ new Vector3();
  36458. /**
  36459. * The class represents a virtual listener of the all positional and non-positional audio effects
  36460. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36461. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36462. *
  36463. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36464. * camera represents the 3D transformation of the listener.
  36465. *
  36466. * @augments Object3D
  36467. */
  36468. class AudioListener extends Object3D {
  36469. /**
  36470. * Constructs a new audio listener.
  36471. */
  36472. constructor() {
  36473. super();
  36474. this.type = 'AudioListener';
  36475. /**
  36476. * The native audio context.
  36477. *
  36478. * @type {AudioContext}
  36479. * @readonly
  36480. */
  36481. this.context = AudioContext.getContext();
  36482. /**
  36483. * The gain node used for volume control.
  36484. *
  36485. * @type {GainNode}
  36486. * @readonly
  36487. */
  36488. this.gain = this.context.createGain();
  36489. this.gain.connect( this.context.destination );
  36490. /**
  36491. * An optional filter.
  36492. *
  36493. * Defined via {@link AudioListener#setFilter}.
  36494. *
  36495. * @type {?AudioNode}
  36496. * @default null
  36497. * @readonly
  36498. */
  36499. this.filter = null;
  36500. /**
  36501. * Time delta values required for `linearRampToValueAtTime()` usage.
  36502. *
  36503. * @type {number}
  36504. * @default 0
  36505. * @readonly
  36506. */
  36507. this.timeDelta = 0;
  36508. // private
  36509. this._clock = new Clock();
  36510. }
  36511. /**
  36512. * Returns the listener's input node.
  36513. *
  36514. * This method is used by other audio nodes to connect to this listener.
  36515. *
  36516. * @return {GainNode} The input node.
  36517. */
  36518. getInput() {
  36519. return this.gain;
  36520. }
  36521. /**
  36522. * Removes the current filter from this listener.
  36523. *
  36524. * @return {AudioListener} A reference to this listener.
  36525. */
  36526. removeFilter() {
  36527. if ( this.filter !== null ) {
  36528. this.gain.disconnect( this.filter );
  36529. this.filter.disconnect( this.context.destination );
  36530. this.gain.connect( this.context.destination );
  36531. this.filter = null;
  36532. }
  36533. return this;
  36534. }
  36535. /**
  36536. * Returns the current set filter.
  36537. *
  36538. * @return {?AudioNode} The filter.
  36539. */
  36540. getFilter() {
  36541. return this.filter;
  36542. }
  36543. /**
  36544. * Sets the given filter to this listener.
  36545. *
  36546. * @param {AudioNode} value - The filter to set.
  36547. * @return {AudioListener} A reference to this listener.
  36548. */
  36549. setFilter( value ) {
  36550. if ( this.filter !== null ) {
  36551. this.gain.disconnect( this.filter );
  36552. this.filter.disconnect( this.context.destination );
  36553. } else {
  36554. this.gain.disconnect( this.context.destination );
  36555. }
  36556. this.filter = value;
  36557. this.gain.connect( this.filter );
  36558. this.filter.connect( this.context.destination );
  36559. return this;
  36560. }
  36561. /**
  36562. * Returns the applications master volume.
  36563. *
  36564. * @return {number} The master volume.
  36565. */
  36566. getMasterVolume() {
  36567. return this.gain.gain.value;
  36568. }
  36569. /**
  36570. * Sets the applications master volume. This volume setting affects
  36571. * all audio nodes in the scene.
  36572. *
  36573. * @param {number} value - The master volume to set.
  36574. * @return {AudioListener} A reference to this listener.
  36575. */
  36576. setMasterVolume( value ) {
  36577. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36578. return this;
  36579. }
  36580. updateMatrixWorld( force ) {
  36581. super.updateMatrixWorld( force );
  36582. const listener = this.context.listener;
  36583. this.timeDelta = this._clock.getDelta();
  36584. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36585. // the initial forward and up directions must be orthogonal
  36586. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36587. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36588. if ( listener.positionX ) {
  36589. // code path for Chrome (see #14393)
  36590. const endTime = this.context.currentTime + this.timeDelta;
  36591. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36592. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36593. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36594. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36595. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36596. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36597. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36598. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36599. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36600. } else {
  36601. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36602. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36603. }
  36604. }
  36605. }
  36606. /**
  36607. * Represents a non-positional ( global ) audio object.
  36608. *
  36609. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36610. *
  36611. * ```js
  36612. * // create an AudioListener and add it to the camera
  36613. * const listener = new THREE.AudioListener();
  36614. * camera.add( listener );
  36615. *
  36616. * // create a global audio source
  36617. * const sound = new THREE.Audio( listener );
  36618. *
  36619. * // load a sound and set it as the Audio object's buffer
  36620. * const audioLoader = new THREE.AudioLoader();
  36621. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36622. * sound.setBuffer( buffer );
  36623. * sound.setLoop( true );
  36624. * sound.setVolume( 0.5 );
  36625. * sound.play();
  36626. * });
  36627. * ```
  36628. *
  36629. * @augments Object3D
  36630. */
  36631. class Audio extends Object3D {
  36632. /**
  36633. * Constructs a new audio.
  36634. *
  36635. * @param {AudioListener} listener - The global audio listener.
  36636. */
  36637. constructor( listener ) {
  36638. super();
  36639. this.type = 'Audio';
  36640. /**
  36641. * The global audio listener.
  36642. *
  36643. * @type {AudioListener}
  36644. * @readonly
  36645. */
  36646. this.listener = listener;
  36647. /**
  36648. * The audio context.
  36649. *
  36650. * @type {AudioContext}
  36651. * @readonly
  36652. */
  36653. this.context = listener.context;
  36654. /**
  36655. * The gain node used for volume control.
  36656. *
  36657. * @type {GainNode}
  36658. * @readonly
  36659. */
  36660. this.gain = this.context.createGain();
  36661. this.gain.connect( listener.getInput() );
  36662. /**
  36663. * Whether to start playback automatically or not.
  36664. *
  36665. * @type {boolean}
  36666. * @default false
  36667. */
  36668. this.autoplay = false;
  36669. /**
  36670. * A reference to an audio buffer.
  36671. *
  36672. * Defined via {@link Audio#setBuffer}.
  36673. *
  36674. * @type {?AudioBuffer}
  36675. * @default null
  36676. * @readonly
  36677. */
  36678. this.buffer = null;
  36679. /**
  36680. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36681. * +/- 1200 is an octave.
  36682. *
  36683. * Defined via {@link Audio#setDetune}.
  36684. *
  36685. * @type {number}
  36686. * @default 0
  36687. * @readonly
  36688. */
  36689. this.detune = 0;
  36690. /**
  36691. * Whether the audio should loop or not.
  36692. *
  36693. * Defined via {@link Audio#setLoop}.
  36694. *
  36695. * @type {boolean}
  36696. * @default false
  36697. * @readonly
  36698. */
  36699. this.loop = false;
  36700. /**
  36701. * Defines where in the audio buffer the replay should
  36702. * start, in seconds.
  36703. *
  36704. * @type {number}
  36705. * @default 0
  36706. */
  36707. this.loopStart = 0;
  36708. /**
  36709. * Defines where in the audio buffer the replay should
  36710. * stop, in seconds.
  36711. *
  36712. * @type {number}
  36713. * @default 0
  36714. */
  36715. this.loopEnd = 0;
  36716. /**
  36717. * An offset to the time within the audio buffer the playback
  36718. * should begin, in seconds.
  36719. *
  36720. * @type {number}
  36721. * @default 0
  36722. */
  36723. this.offset = 0;
  36724. /**
  36725. * Overrides the default duration of the audio.
  36726. *
  36727. * @type {undefined|number}
  36728. * @default undefined
  36729. */
  36730. this.duration = undefined;
  36731. /**
  36732. * The playback speed.
  36733. *
  36734. * Defined via {@link Audio#setPlaybackRate}.
  36735. *
  36736. * @type {number}
  36737. * @readonly
  36738. * @default 1
  36739. */
  36740. this.playbackRate = 1;
  36741. /**
  36742. * Indicates whether the audio is playing or not.
  36743. *
  36744. * This flag will be automatically set when using {@link Audio#play},
  36745. * {@link Audio#pause}, {@link Audio#stop}.
  36746. *
  36747. * @type {boolean}
  36748. * @readonly
  36749. * @default false
  36750. */
  36751. this.isPlaying = false;
  36752. /**
  36753. * Indicates whether the audio playback can be controlled
  36754. * with method like {@link Audio#play} or {@link Audio#pause}.
  36755. *
  36756. * This flag will be automatically set when audio sources are
  36757. * defined.
  36758. *
  36759. * @type {boolean}
  36760. * @readonly
  36761. * @default true
  36762. */
  36763. this.hasPlaybackControl = true;
  36764. /**
  36765. * Holds a reference to the current audio source.
  36766. *
  36767. * The property is automatically by one of the `set*()` methods.
  36768. *
  36769. * @type {?AudioNode}
  36770. * @readonly
  36771. * @default null
  36772. */
  36773. this.source = null;
  36774. /**
  36775. * Defines the source type.
  36776. *
  36777. * The property is automatically set by one of the `set*()` methods.
  36778. *
  36779. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36780. * @readonly
  36781. * @default 'empty'
  36782. */
  36783. this.sourceType = 'empty';
  36784. this._startedAt = 0;
  36785. this._progress = 0;
  36786. this._connected = false;
  36787. /**
  36788. * Can be used to apply a variety of low-order filters to create
  36789. * more complex sound effects e.g. via `BiquadFilterNode`.
  36790. *
  36791. * The property is automatically set by {@link Audio#setFilters}.
  36792. *
  36793. * @type {Array<AudioNode>}
  36794. * @readonly
  36795. */
  36796. this.filters = [];
  36797. }
  36798. /**
  36799. * Returns the output audio node.
  36800. *
  36801. * @return {GainNode} The output node.
  36802. */
  36803. getOutput() {
  36804. return this.gain;
  36805. }
  36806. /**
  36807. * Sets the given audio node as the source of this instance.
  36808. *
  36809. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36810. *
  36811. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36812. * @return {Audio} A reference to this instance.
  36813. */
  36814. setNodeSource( audioNode ) {
  36815. this.hasPlaybackControl = false;
  36816. this.sourceType = 'audioNode';
  36817. this.source = audioNode;
  36818. this.connect();
  36819. return this;
  36820. }
  36821. /**
  36822. * Sets the given media element as the source of this instance.
  36823. *
  36824. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36825. *
  36826. * @param {HTMLMediaElement} mediaElement - The media element.
  36827. * @return {Audio} A reference to this instance.
  36828. */
  36829. setMediaElementSource( mediaElement ) {
  36830. this.hasPlaybackControl = false;
  36831. this.sourceType = 'mediaNode';
  36832. this.source = this.context.createMediaElementSource( mediaElement );
  36833. this.connect();
  36834. return this;
  36835. }
  36836. /**
  36837. * Sets the given media stream as the source of this instance.
  36838. *
  36839. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36840. *
  36841. * @param {MediaStream} mediaStream - The media stream.
  36842. * @return {Audio} A reference to this instance.
  36843. */
  36844. setMediaStreamSource( mediaStream ) {
  36845. this.hasPlaybackControl = false;
  36846. this.sourceType = 'mediaStreamNode';
  36847. this.source = this.context.createMediaStreamSource( mediaStream );
  36848. this.connect();
  36849. return this;
  36850. }
  36851. /**
  36852. * Sets the given audio buffer as the source of this instance.
  36853. *
  36854. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36855. *
  36856. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36857. * @return {Audio} A reference to this instance.
  36858. */
  36859. setBuffer( audioBuffer ) {
  36860. this.buffer = audioBuffer;
  36861. this.sourceType = 'buffer';
  36862. if ( this.autoplay ) this.play();
  36863. return this;
  36864. }
  36865. /**
  36866. * Starts the playback of the audio.
  36867. *
  36868. * Can only be used with compatible audio sources that allow playback control.
  36869. *
  36870. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36871. * @return {Audio|undefined} A reference to this instance.
  36872. */
  36873. play( delay = 0 ) {
  36874. if ( this.isPlaying === true ) {
  36875. warn( 'Audio: Audio is already playing.' );
  36876. return;
  36877. }
  36878. if ( this.hasPlaybackControl === false ) {
  36879. warn( 'Audio: this Audio has no playback control.' );
  36880. return;
  36881. }
  36882. this._startedAt = this.context.currentTime + delay;
  36883. const source = this.context.createBufferSource();
  36884. source.buffer = this.buffer;
  36885. source.loop = this.loop;
  36886. source.loopStart = this.loopStart;
  36887. source.loopEnd = this.loopEnd;
  36888. source.onended = this.onEnded.bind( this );
  36889. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36890. this.isPlaying = true;
  36891. this.source = source;
  36892. this.setDetune( this.detune );
  36893. this.setPlaybackRate( this.playbackRate );
  36894. return this.connect();
  36895. }
  36896. /**
  36897. * Pauses the playback of the audio.
  36898. *
  36899. * Can only be used with compatible audio sources that allow playback control.
  36900. *
  36901. * @return {Audio|undefined} A reference to this instance.
  36902. */
  36903. pause() {
  36904. if ( this.hasPlaybackControl === false ) {
  36905. warn( 'Audio: this Audio has no playback control.' );
  36906. return;
  36907. }
  36908. if ( this.isPlaying === true ) {
  36909. // update current progress
  36910. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36911. if ( this.loop === true ) {
  36912. // ensure _progress does not exceed duration with looped audios
  36913. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36914. }
  36915. this.source.stop();
  36916. this.source.onended = null;
  36917. this.isPlaying = false;
  36918. }
  36919. return this;
  36920. }
  36921. /**
  36922. * Stops the playback of the audio.
  36923. *
  36924. * Can only be used with compatible audio sources that allow playback control.
  36925. *
  36926. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36927. * @return {Audio|undefined} A reference to this instance.
  36928. */
  36929. stop( delay = 0 ) {
  36930. if ( this.hasPlaybackControl === false ) {
  36931. warn( 'Audio: this Audio has no playback control.' );
  36932. return;
  36933. }
  36934. this._progress = 0;
  36935. if ( this.source !== null ) {
  36936. this.source.stop( this.context.currentTime + delay );
  36937. this.source.onended = null;
  36938. }
  36939. this.isPlaying = false;
  36940. return this;
  36941. }
  36942. /**
  36943. * Connects to the audio source. This is used internally on
  36944. * initialisation and when setting / removing filters.
  36945. *
  36946. * @return {Audio} A reference to this instance.
  36947. */
  36948. connect() {
  36949. if ( this.filters.length > 0 ) {
  36950. this.source.connect( this.filters[ 0 ] );
  36951. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36952. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36953. }
  36954. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36955. } else {
  36956. this.source.connect( this.getOutput() );
  36957. }
  36958. this._connected = true;
  36959. return this;
  36960. }
  36961. /**
  36962. * Disconnects to the audio source. This is used internally on
  36963. * initialisation and when setting / removing filters.
  36964. *
  36965. * @return {Audio|undefined} A reference to this instance.
  36966. */
  36967. disconnect() {
  36968. if ( this._connected === false ) {
  36969. return;
  36970. }
  36971. if ( this.filters.length > 0 ) {
  36972. this.source.disconnect( this.filters[ 0 ] );
  36973. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36974. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36975. }
  36976. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36977. } else {
  36978. this.source.disconnect( this.getOutput() );
  36979. }
  36980. this._connected = false;
  36981. return this;
  36982. }
  36983. /**
  36984. * Returns the current set filters.
  36985. *
  36986. * @return {Array<AudioNode>} The list of filters.
  36987. */
  36988. getFilters() {
  36989. return this.filters;
  36990. }
  36991. /**
  36992. * Sets an array of filters and connects them with the audio source.
  36993. *
  36994. * @param {Array<AudioNode>} [value] - A list of filters.
  36995. * @return {Audio} A reference to this instance.
  36996. */
  36997. setFilters( value ) {
  36998. if ( ! value ) value = [];
  36999. if ( this._connected === true ) {
  37000. this.disconnect();
  37001. this.filters = value.slice();
  37002. this.connect();
  37003. } else {
  37004. this.filters = value.slice();
  37005. }
  37006. return this;
  37007. }
  37008. /**
  37009. * Defines the detuning of oscillation in cents.
  37010. *
  37011. * @param {number} value - The detuning of oscillation in cents.
  37012. * @return {Audio} A reference to this instance.
  37013. */
  37014. setDetune( value ) {
  37015. this.detune = value;
  37016. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  37017. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  37018. }
  37019. return this;
  37020. }
  37021. /**
  37022. * Returns the detuning of oscillation in cents.
  37023. *
  37024. * @return {number} The detuning of oscillation in cents.
  37025. */
  37026. getDetune() {
  37027. return this.detune;
  37028. }
  37029. /**
  37030. * Returns the first filter in the list of filters.
  37031. *
  37032. * @return {AudioNode|undefined} The first filter in the list of filters.
  37033. */
  37034. getFilter() {
  37035. return this.getFilters()[ 0 ];
  37036. }
  37037. /**
  37038. * Applies a single filter node to the audio.
  37039. *
  37040. * @param {AudioNode} [filter] - The filter to set.
  37041. * @return {Audio} A reference to this instance.
  37042. */
  37043. setFilter( filter ) {
  37044. return this.setFilters( filter ? [ filter ] : [] );
  37045. }
  37046. /**
  37047. * Sets the playback rate.
  37048. *
  37049. * Can only be used with compatible audio sources that allow playback control.
  37050. *
  37051. * @param {number} [value] - The playback rate to set.
  37052. * @return {Audio|undefined} A reference to this instance.
  37053. */
  37054. setPlaybackRate( value ) {
  37055. if ( this.hasPlaybackControl === false ) {
  37056. warn( 'Audio: this Audio has no playback control.' );
  37057. return;
  37058. }
  37059. this.playbackRate = value;
  37060. if ( this.isPlaying === true ) {
  37061. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  37062. }
  37063. return this;
  37064. }
  37065. /**
  37066. * Returns the current playback rate.
  37067. * @return {number} The playback rate.
  37068. */
  37069. getPlaybackRate() {
  37070. return this.playbackRate;
  37071. }
  37072. /**
  37073. * Automatically called when playback finished.
  37074. */
  37075. onEnded() {
  37076. this.isPlaying = false;
  37077. this._progress = 0;
  37078. }
  37079. /**
  37080. * Returns the loop flag.
  37081. *
  37082. * Can only be used with compatible audio sources that allow playback control.
  37083. *
  37084. * @return {boolean} Whether the audio should loop or not.
  37085. */
  37086. getLoop() {
  37087. if ( this.hasPlaybackControl === false ) {
  37088. warn( 'Audio: this Audio has no playback control.' );
  37089. return false;
  37090. }
  37091. return this.loop;
  37092. }
  37093. /**
  37094. * Sets the loop flag.
  37095. *
  37096. * Can only be used with compatible audio sources that allow playback control.
  37097. *
  37098. * @param {boolean} value - Whether the audio should loop or not.
  37099. * @return {Audio|undefined} A reference to this instance.
  37100. */
  37101. setLoop( value ) {
  37102. if ( this.hasPlaybackControl === false ) {
  37103. warn( 'Audio: this Audio has no playback control.' );
  37104. return;
  37105. }
  37106. this.loop = value;
  37107. if ( this.isPlaying === true ) {
  37108. this.source.loop = this.loop;
  37109. }
  37110. return this;
  37111. }
  37112. /**
  37113. * Sets the loop start value which defines where in the audio buffer the replay should
  37114. * start, in seconds.
  37115. *
  37116. * @param {number} value - The loop start value.
  37117. * @return {Audio} A reference to this instance.
  37118. */
  37119. setLoopStart( value ) {
  37120. this.loopStart = value;
  37121. return this;
  37122. }
  37123. /**
  37124. * Sets the loop end value which defines where in the audio buffer the replay should
  37125. * stop, in seconds.
  37126. *
  37127. * @param {number} value - The loop end value.
  37128. * @return {Audio} A reference to this instance.
  37129. */
  37130. setLoopEnd( value ) {
  37131. this.loopEnd = value;
  37132. return this;
  37133. }
  37134. /**
  37135. * Returns the volume.
  37136. *
  37137. * @return {number} The volume.
  37138. */
  37139. getVolume() {
  37140. return this.gain.gain.value;
  37141. }
  37142. /**
  37143. * Sets the volume.
  37144. *
  37145. * @param {number} value - The volume to set.
  37146. * @return {Audio} A reference to this instance.
  37147. */
  37148. setVolume( value ) {
  37149. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37150. return this;
  37151. }
  37152. copy( source, recursive ) {
  37153. super.copy( source, recursive );
  37154. if ( source.sourceType !== 'buffer' ) {
  37155. warn( 'Audio: Audio source type cannot be copied.' );
  37156. return this;
  37157. }
  37158. this.autoplay = source.autoplay;
  37159. this.buffer = source.buffer;
  37160. this.detune = source.detune;
  37161. this.loop = source.loop;
  37162. this.loopStart = source.loopStart;
  37163. this.loopEnd = source.loopEnd;
  37164. this.offset = source.offset;
  37165. this.duration = source.duration;
  37166. this.playbackRate = source.playbackRate;
  37167. this.hasPlaybackControl = source.hasPlaybackControl;
  37168. this.sourceType = source.sourceType;
  37169. this.filters = source.filters.slice();
  37170. return this;
  37171. }
  37172. clone( recursive ) {
  37173. return new this.constructor( this.listener ).copy( this, recursive );
  37174. }
  37175. }
  37176. const _position = /*@__PURE__*/ new Vector3();
  37177. const _quaternion = /*@__PURE__*/ new Quaternion();
  37178. const _scale = /*@__PURE__*/ new Vector3();
  37179. const _orientation = /*@__PURE__*/ new Vector3();
  37180. /**
  37181. * Represents a positional audio object.
  37182. *
  37183. * ```js
  37184. * // create an AudioListener and add it to the camera
  37185. * const listener = new THREE.AudioListener();
  37186. * camera.add( listener );
  37187. *
  37188. * // create the PositionalAudio object (passing in the listener)
  37189. * const sound = new THREE.PositionalAudio( listener );
  37190. *
  37191. * // load a sound and set it as the PositionalAudio object's buffer
  37192. * const audioLoader = new THREE.AudioLoader();
  37193. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  37194. * sound.setBuffer( buffer );
  37195. * sound.setRefDistance( 20 );
  37196. * sound.play();
  37197. * });
  37198. *
  37199. * // create an object for the sound to play from
  37200. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  37201. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  37202. * const mesh = new THREE.Mesh( sphere, material );
  37203. * scene.add( mesh );
  37204. *
  37205. * // finally add the sound to the mesh
  37206. * mesh.add( sound );
  37207. *
  37208. * @augments Audio
  37209. */
  37210. class PositionalAudio extends Audio {
  37211. /**
  37212. * Constructs a positional audio.
  37213. *
  37214. * @param {AudioListener} listener - The global audio listener.
  37215. */
  37216. constructor( listener ) {
  37217. super( listener );
  37218. /**
  37219. * The panner node represents the location, direction, and behavior of an audio
  37220. * source in 3D space.
  37221. *
  37222. * @type {PannerNode}
  37223. * @readonly
  37224. */
  37225. this.panner = this.context.createPanner();
  37226. this.panner.panningModel = 'HRTF';
  37227. this.panner.connect( this.gain );
  37228. }
  37229. connect() {
  37230. super.connect();
  37231. this.panner.connect( this.gain );
  37232. return this;
  37233. }
  37234. disconnect() {
  37235. super.disconnect();
  37236. this.panner.disconnect( this.gain );
  37237. return this;
  37238. }
  37239. getOutput() {
  37240. return this.panner;
  37241. }
  37242. /**
  37243. * Returns the current reference distance.
  37244. *
  37245. * @return {number} The reference distance.
  37246. */
  37247. getRefDistance() {
  37248. return this.panner.refDistance;
  37249. }
  37250. /**
  37251. * Defines the reference distance for reducing volume as the audio source moves
  37252. * further from the listener – i.e. the distance at which the volume reduction
  37253. * starts taking effect.
  37254. *
  37255. * @param {number} value - The reference distance to set.
  37256. * @return {PositionalAudio} A reference to this instance.
  37257. */
  37258. setRefDistance( value ) {
  37259. this.panner.refDistance = value;
  37260. return this;
  37261. }
  37262. /**
  37263. * Returns the current rolloff factor.
  37264. *
  37265. * @return {number} The rolloff factor.
  37266. */
  37267. getRolloffFactor() {
  37268. return this.panner.rolloffFactor;
  37269. }
  37270. /**
  37271. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37272. *
  37273. * @param {number} value - The rolloff factor.
  37274. * @return {PositionalAudio} A reference to this instance.
  37275. */
  37276. setRolloffFactor( value ) {
  37277. this.panner.rolloffFactor = value;
  37278. return this;
  37279. }
  37280. /**
  37281. * Returns the current distance model.
  37282. *
  37283. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37284. */
  37285. getDistanceModel() {
  37286. return this.panner.distanceModel;
  37287. }
  37288. /**
  37289. * Defines which algorithm to use to reduce the volume of the audio source
  37290. * as it moves away from the listener.
  37291. *
  37292. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37293. * for more details.
  37294. *
  37295. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37296. * @return {PositionalAudio} A reference to this instance.
  37297. */
  37298. setDistanceModel( value ) {
  37299. this.panner.distanceModel = value;
  37300. return this;
  37301. }
  37302. /**
  37303. * Returns the current max distance.
  37304. *
  37305. * @return {number} The max distance.
  37306. */
  37307. getMaxDistance() {
  37308. return this.panner.maxDistance;
  37309. }
  37310. /**
  37311. * Defines the maximum distance between the audio source and the listener,
  37312. * after which the volume is not reduced any further.
  37313. *
  37314. * This value is used only by the `linear` distance model.
  37315. *
  37316. * @param {number} value - The max distance.
  37317. * @return {PositionalAudio} A reference to this instance.
  37318. */
  37319. setMaxDistance( value ) {
  37320. this.panner.maxDistance = value;
  37321. return this;
  37322. }
  37323. /**
  37324. * Sets the directional cone in which the audio can be listened.
  37325. *
  37326. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37327. * @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.
  37328. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37329. * @return {PositionalAudio} A reference to this instance.
  37330. */
  37331. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37332. this.panner.coneInnerAngle = coneInnerAngle;
  37333. this.panner.coneOuterAngle = coneOuterAngle;
  37334. this.panner.coneOuterGain = coneOuterGain;
  37335. return this;
  37336. }
  37337. updateMatrixWorld( force ) {
  37338. super.updateMatrixWorld( force );
  37339. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37340. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37341. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37342. const panner = this.panner;
  37343. if ( panner.positionX ) {
  37344. // code path for Chrome and Firefox (see #14393)
  37345. const endTime = this.context.currentTime + this.listener.timeDelta;
  37346. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37347. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37348. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37349. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37350. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37351. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37352. } else {
  37353. panner.setPosition( _position.x, _position.y, _position.z );
  37354. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37355. }
  37356. }
  37357. }
  37358. /**
  37359. * This class can be used to analyse audio data.
  37360. *
  37361. * ```js
  37362. * // create an AudioListener and add it to the camera
  37363. * const listener = new THREE.AudioListener();
  37364. * camera.add( listener );
  37365. *
  37366. * // create an Audio source
  37367. * const sound = new THREE.Audio( listener );
  37368. *
  37369. * // load a sound and set it as the Audio object's buffer
  37370. * const audioLoader = new THREE.AudioLoader();
  37371. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37372. * sound.setBuffer( buffer );
  37373. * sound.setLoop(true);
  37374. * sound.setVolume(0.5);
  37375. * sound.play();
  37376. * });
  37377. *
  37378. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37379. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37380. *
  37381. * // get the average frequency of the sound
  37382. * const data = analyser.getAverageFrequency();
  37383. * ```
  37384. */
  37385. class AudioAnalyser {
  37386. /**
  37387. * Constructs a new audio analyzer.
  37388. *
  37389. * @param {Audio} audio - The audio to analyze.
  37390. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37391. */
  37392. constructor( audio, fftSize = 2048 ) {
  37393. /**
  37394. * The global audio listener.
  37395. *
  37396. * @type {AnalyserNode}
  37397. */
  37398. this.analyser = audio.context.createAnalyser();
  37399. this.analyser.fftSize = fftSize;
  37400. /**
  37401. * Holds the analyzed data.
  37402. *
  37403. * @type {Uint8Array}
  37404. */
  37405. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37406. audio.getOutput().connect( this.analyser );
  37407. }
  37408. /**
  37409. * Returns an array with frequency data of the audio.
  37410. *
  37411. * Each item in the array represents the decibel value for a specific frequency.
  37412. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37413. * For example, for 48000 sample rate, the last item of the array will represent
  37414. * the decibel value for 24000 Hz.
  37415. *
  37416. * @return {Uint8Array} The frequency data.
  37417. */
  37418. getFrequencyData() {
  37419. this.analyser.getByteFrequencyData( this.data );
  37420. return this.data;
  37421. }
  37422. /**
  37423. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37424. *
  37425. * @return {number} The average frequency.
  37426. */
  37427. getAverageFrequency() {
  37428. let value = 0;
  37429. const data = this.getFrequencyData();
  37430. for ( let i = 0; i < data.length; i ++ ) {
  37431. value += data[ i ];
  37432. }
  37433. return value / data.length;
  37434. }
  37435. }
  37436. /**
  37437. * Buffered scene graph property that allows weighted accumulation; used internally.
  37438. */
  37439. class PropertyMixer {
  37440. /**
  37441. * Constructs a new property mixer.
  37442. *
  37443. * @param {PropertyBinding} binding - The property binding.
  37444. * @param {string} typeName - The keyframe track type name.
  37445. * @param {number} valueSize - The keyframe track value size.
  37446. */
  37447. constructor( binding, typeName, valueSize ) {
  37448. /**
  37449. * The property binding.
  37450. *
  37451. * @type {PropertyBinding}
  37452. */
  37453. this.binding = binding;
  37454. /**
  37455. * The keyframe track value size.
  37456. *
  37457. * @type {number}
  37458. */
  37459. this.valueSize = valueSize;
  37460. let mixFunction,
  37461. mixFunctionAdditive,
  37462. setIdentity;
  37463. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37464. //
  37465. // interpolators can use .buffer as their .result
  37466. // the data then goes to 'incoming'
  37467. //
  37468. // 'accu0' and 'accu1' are used frame-interleaved for
  37469. // the cumulative result and are compared to detect
  37470. // changes
  37471. //
  37472. // 'orig' stores the original state of the property
  37473. //
  37474. // 'add' is used for additive cumulative results
  37475. //
  37476. // 'work' is optional and is only present for quaternion types. It is used
  37477. // to store intermediate quaternion multiplication results
  37478. switch ( typeName ) {
  37479. case 'quaternion':
  37480. mixFunction = this._slerp;
  37481. mixFunctionAdditive = this._slerpAdditive;
  37482. setIdentity = this._setAdditiveIdentityQuaternion;
  37483. this.buffer = new Float64Array( valueSize * 6 );
  37484. this._workIndex = 5;
  37485. break;
  37486. case 'string':
  37487. case 'bool':
  37488. mixFunction = this._select;
  37489. // Use the regular mix function and for additive on these types,
  37490. // additive is not relevant for non-numeric types
  37491. mixFunctionAdditive = this._select;
  37492. setIdentity = this._setAdditiveIdentityOther;
  37493. this.buffer = new Array( valueSize * 5 );
  37494. break;
  37495. default:
  37496. mixFunction = this._lerp;
  37497. mixFunctionAdditive = this._lerpAdditive;
  37498. setIdentity = this._setAdditiveIdentityNumeric;
  37499. this.buffer = new Float64Array( valueSize * 5 );
  37500. }
  37501. this._mixBufferRegion = mixFunction;
  37502. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37503. this._setIdentity = setIdentity;
  37504. this._origIndex = 3;
  37505. this._addIndex = 4;
  37506. /**
  37507. * TODO
  37508. *
  37509. * @type {number}
  37510. * @default 0
  37511. */
  37512. this.cumulativeWeight = 0;
  37513. /**
  37514. * TODO
  37515. *
  37516. * @type {number}
  37517. * @default 0
  37518. */
  37519. this.cumulativeWeightAdditive = 0;
  37520. /**
  37521. * TODO
  37522. *
  37523. * @type {number}
  37524. * @default 0
  37525. */
  37526. this.useCount = 0;
  37527. /**
  37528. * TODO
  37529. *
  37530. * @type {number}
  37531. * @default 0
  37532. */
  37533. this.referenceCount = 0;
  37534. }
  37535. /**
  37536. * Accumulates data in the `incoming` region into `accu<i>`.
  37537. *
  37538. * @param {number} accuIndex - The accumulation index.
  37539. * @param {number} weight - The weight.
  37540. */
  37541. accumulate( accuIndex, weight ) {
  37542. // note: happily accumulating nothing when weight = 0, the caller knows
  37543. // the weight and shouldn't have made the call in the first place
  37544. const buffer = this.buffer,
  37545. stride = this.valueSize,
  37546. offset = accuIndex * stride + stride;
  37547. let currentWeight = this.cumulativeWeight;
  37548. if ( currentWeight === 0 ) {
  37549. // accuN := incoming * weight
  37550. for ( let i = 0; i !== stride; ++ i ) {
  37551. buffer[ offset + i ] = buffer[ i ];
  37552. }
  37553. currentWeight = weight;
  37554. } else {
  37555. // accuN := accuN + incoming * weight
  37556. currentWeight += weight;
  37557. const mix = weight / currentWeight;
  37558. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37559. }
  37560. this.cumulativeWeight = currentWeight;
  37561. }
  37562. /**
  37563. * Accumulates data in the `incoming` region into `add`.
  37564. *
  37565. * @param {number} weight - The weight.
  37566. */
  37567. accumulateAdditive( weight ) {
  37568. const buffer = this.buffer,
  37569. stride = this.valueSize,
  37570. offset = stride * this._addIndex;
  37571. if ( this.cumulativeWeightAdditive === 0 ) {
  37572. // add = identity
  37573. this._setIdentity();
  37574. }
  37575. // add := add + incoming * weight
  37576. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37577. this.cumulativeWeightAdditive += weight;
  37578. }
  37579. /**
  37580. * Applies the state of `accu<i>` to the binding when accus differ.
  37581. *
  37582. * @param {number} accuIndex - The accumulation index.
  37583. */
  37584. apply( accuIndex ) {
  37585. const stride = this.valueSize,
  37586. buffer = this.buffer,
  37587. offset = accuIndex * stride + stride,
  37588. weight = this.cumulativeWeight,
  37589. weightAdditive = this.cumulativeWeightAdditive,
  37590. binding = this.binding;
  37591. this.cumulativeWeight = 0;
  37592. this.cumulativeWeightAdditive = 0;
  37593. if ( weight < 1 ) {
  37594. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37595. const originalValueOffset = stride * this._origIndex;
  37596. this._mixBufferRegion(
  37597. buffer, offset, originalValueOffset, 1 - weight, stride );
  37598. }
  37599. if ( weightAdditive > 0 ) {
  37600. // accuN := accuN + additive accuN
  37601. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37602. }
  37603. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37604. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37605. // value has changed -> update scene graph
  37606. binding.setValue( buffer, offset );
  37607. break;
  37608. }
  37609. }
  37610. }
  37611. /**
  37612. * Remembers the state of the bound property and copy it to both accus.
  37613. */
  37614. saveOriginalState() {
  37615. const binding = this.binding;
  37616. const buffer = this.buffer,
  37617. stride = this.valueSize,
  37618. originalValueOffset = stride * this._origIndex;
  37619. binding.getValue( buffer, originalValueOffset );
  37620. // accu[0..1] := orig -- initially detect changes against the original
  37621. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37622. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37623. }
  37624. // Add to identity for additive
  37625. this._setIdentity();
  37626. this.cumulativeWeight = 0;
  37627. this.cumulativeWeightAdditive = 0;
  37628. }
  37629. /**
  37630. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37631. */
  37632. restoreOriginalState() {
  37633. const originalValueOffset = this.valueSize * 3;
  37634. this.binding.setValue( this.buffer, originalValueOffset );
  37635. }
  37636. // internals
  37637. _setAdditiveIdentityNumeric() {
  37638. const startIndex = this._addIndex * this.valueSize;
  37639. const endIndex = startIndex + this.valueSize;
  37640. for ( let i = startIndex; i < endIndex; i ++ ) {
  37641. this.buffer[ i ] = 0;
  37642. }
  37643. }
  37644. _setAdditiveIdentityQuaternion() {
  37645. this._setAdditiveIdentityNumeric();
  37646. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37647. }
  37648. _setAdditiveIdentityOther() {
  37649. const startIndex = this._origIndex * this.valueSize;
  37650. const targetIndex = this._addIndex * this.valueSize;
  37651. for ( let i = 0; i < this.valueSize; i ++ ) {
  37652. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37653. }
  37654. }
  37655. // mix functions
  37656. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37657. if ( t >= 0.5 ) {
  37658. for ( let i = 0; i !== stride; ++ i ) {
  37659. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37660. }
  37661. }
  37662. }
  37663. _slerp( buffer, dstOffset, srcOffset, t ) {
  37664. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37665. }
  37666. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37667. const workOffset = this._workIndex * stride;
  37668. // Store result in intermediate buffer offset
  37669. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37670. // Slerp to the intermediate result
  37671. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37672. }
  37673. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37674. const s = 1 - t;
  37675. for ( let i = 0; i !== stride; ++ i ) {
  37676. const j = dstOffset + i;
  37677. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37678. }
  37679. }
  37680. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37681. for ( let i = 0; i !== stride; ++ i ) {
  37682. const j = dstOffset + i;
  37683. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37684. }
  37685. }
  37686. }
  37687. // Characters [].:/ are reserved for track binding syntax.
  37688. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37689. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37690. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37691. // only latin characters, and the unicode \p{L} is not yet supported. So
  37692. // instead, we exclude reserved characters and match everything else.
  37693. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37694. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37695. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37696. // be matched to parse the rest of the track name.
  37697. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37698. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37699. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37700. // Object on target node, and accessor. May not contain reserved
  37701. // characters. Accessor may contain any character except closing bracket.
  37702. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37703. // Property and accessor. May not contain reserved characters. Accessor may
  37704. // contain any non-bracket characters.
  37705. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37706. const _trackRe = new RegExp( ''
  37707. + '^'
  37708. + _directoryRe
  37709. + _nodeRe
  37710. + _objectRe
  37711. + _propertyRe
  37712. + '$'
  37713. );
  37714. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37715. class Composite {
  37716. constructor( targetGroup, path, optionalParsedPath ) {
  37717. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37718. this._targetGroup = targetGroup;
  37719. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37720. }
  37721. getValue( array, offset ) {
  37722. this.bind(); // bind all binding
  37723. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37724. binding = this._bindings[ firstValidIndex ];
  37725. // and only call .getValue on the first
  37726. if ( binding !== undefined ) binding.getValue( array, offset );
  37727. }
  37728. setValue( array, offset ) {
  37729. const bindings = this._bindings;
  37730. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37731. bindings[ i ].setValue( array, offset );
  37732. }
  37733. }
  37734. bind() {
  37735. const bindings = this._bindings;
  37736. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37737. bindings[ i ].bind();
  37738. }
  37739. }
  37740. unbind() {
  37741. const bindings = this._bindings;
  37742. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37743. bindings[ i ].unbind();
  37744. }
  37745. }
  37746. }
  37747. // Note: This class uses a State pattern on a per-method basis:
  37748. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37749. // prototype version of these methods with one that represents
  37750. // the bound state. When the property is not found, the methods
  37751. // become no-ops.
  37752. /**
  37753. * This holds a reference to a real property in the scene graph; used internally.
  37754. */
  37755. class PropertyBinding {
  37756. /**
  37757. * Constructs a new property binding.
  37758. *
  37759. * @param {Object} rootNode - The root node.
  37760. * @param {string} path - The path.
  37761. * @param {?Object} [parsedPath] - The parsed path.
  37762. */
  37763. constructor( rootNode, path, parsedPath ) {
  37764. /**
  37765. * The object path to the animated property.
  37766. *
  37767. * @type {string}
  37768. */
  37769. this.path = path;
  37770. /**
  37771. * An object holding information about the path.
  37772. *
  37773. * @type {Object}
  37774. */
  37775. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37776. /**
  37777. * The object owns the animated property.
  37778. *
  37779. * @type {?Object}
  37780. */
  37781. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37782. /**
  37783. * The root node.
  37784. *
  37785. * @type {Object3D|Skeleton}
  37786. */
  37787. this.rootNode = rootNode;
  37788. // initial state of these methods that calls 'bind'
  37789. this.getValue = this._getValue_unbound;
  37790. this.setValue = this._setValue_unbound;
  37791. }
  37792. /**
  37793. * Factory method for creating a property binding from the given parameters.
  37794. *
  37795. * @static
  37796. * @param {Object} root - The root node.
  37797. * @param {string} path - The path.
  37798. * @param {?Object} [parsedPath] - The parsed path.
  37799. * @return {PropertyBinding|Composite} The created property binding or composite.
  37800. */
  37801. static create( root, path, parsedPath ) {
  37802. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37803. return new PropertyBinding( root, path, parsedPath );
  37804. } else {
  37805. return new PropertyBinding.Composite( root, path, parsedPath );
  37806. }
  37807. }
  37808. /**
  37809. * Replaces spaces with underscores and removes unsupported characters from
  37810. * node names, to ensure compatibility with parseTrackName().
  37811. *
  37812. * @param {string} name - Node name to be sanitized.
  37813. * @return {string} The sanitized node name.
  37814. */
  37815. static sanitizeNodeName( name ) {
  37816. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37817. }
  37818. /**
  37819. * Parses the given track name (an object path to an animated property) and
  37820. * returns an object with information about the path. Matches strings in the following forms:
  37821. *
  37822. * - nodeName.property
  37823. * - nodeName.property[accessor]
  37824. * - nodeName.material.property[accessor]
  37825. * - uuid.property[accessor]
  37826. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37827. * - parentName/nodeName.property
  37828. * - parentName/parentName/nodeName.property[index]
  37829. * - .bone[Armature.DEF_cog].position
  37830. * - scene:helium_balloon_model:helium_balloon_model.position
  37831. *
  37832. * @static
  37833. * @param {string} trackName - The track name to parse.
  37834. * @return {Object} The parsed track name as an object.
  37835. */
  37836. static parseTrackName( trackName ) {
  37837. const matches = _trackRe.exec( trackName );
  37838. if ( matches === null ) {
  37839. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37840. }
  37841. const results = {
  37842. // directoryName: matches[ 1 ], // (tschw) currently unused
  37843. nodeName: matches[ 2 ],
  37844. objectName: matches[ 3 ],
  37845. objectIndex: matches[ 4 ],
  37846. propertyName: matches[ 5 ], // required
  37847. propertyIndex: matches[ 6 ]
  37848. };
  37849. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37850. if ( lastDot !== undefined && lastDot !== -1 ) {
  37851. const objectName = results.nodeName.substring( lastDot + 1 );
  37852. // Object names must be checked against an allowlist. Otherwise, there
  37853. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37854. // 'bar' could be the objectName, or part of a nodeName (which can
  37855. // include '.' characters).
  37856. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37857. results.nodeName = results.nodeName.substring( 0, lastDot );
  37858. results.objectName = objectName;
  37859. }
  37860. }
  37861. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37862. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37863. }
  37864. return results;
  37865. }
  37866. /**
  37867. * Searches for a node in the hierarchy of the given root object by the given
  37868. * node name.
  37869. *
  37870. * @static
  37871. * @param {Object} root - The root object.
  37872. * @param {string|number} nodeName - The name of the node.
  37873. * @return {?Object} The found node. Returns `null` if no object was found.
  37874. */
  37875. static findNode( root, nodeName ) {
  37876. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37877. return root;
  37878. }
  37879. // search into skeleton bones.
  37880. if ( root.skeleton ) {
  37881. const bone = root.skeleton.getBoneByName( nodeName );
  37882. if ( bone !== undefined ) {
  37883. return bone;
  37884. }
  37885. }
  37886. // search into node subtree.
  37887. if ( root.children ) {
  37888. const searchNodeSubtree = function ( children ) {
  37889. for ( let i = 0; i < children.length; i ++ ) {
  37890. const childNode = children[ i ];
  37891. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37892. return childNode;
  37893. }
  37894. const result = searchNodeSubtree( childNode.children );
  37895. if ( result ) return result;
  37896. }
  37897. return null;
  37898. };
  37899. const subTreeNode = searchNodeSubtree( root.children );
  37900. if ( subTreeNode ) {
  37901. return subTreeNode;
  37902. }
  37903. }
  37904. return null;
  37905. }
  37906. // these are used to "bind" a nonexistent property
  37907. _getValue_unavailable() {}
  37908. _setValue_unavailable() {}
  37909. // Getters
  37910. _getValue_direct( buffer, offset ) {
  37911. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37912. }
  37913. _getValue_array( buffer, offset ) {
  37914. const source = this.resolvedProperty;
  37915. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37916. buffer[ offset ++ ] = source[ i ];
  37917. }
  37918. }
  37919. _getValue_arrayElement( buffer, offset ) {
  37920. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37921. }
  37922. _getValue_toArray( buffer, offset ) {
  37923. this.resolvedProperty.toArray( buffer, offset );
  37924. }
  37925. // Direct
  37926. _setValue_direct( buffer, offset ) {
  37927. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37928. }
  37929. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37930. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37931. this.targetObject.needsUpdate = true;
  37932. }
  37933. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37934. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37935. this.targetObject.matrixWorldNeedsUpdate = true;
  37936. }
  37937. // EntireArray
  37938. _setValue_array( buffer, offset ) {
  37939. const dest = this.resolvedProperty;
  37940. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37941. dest[ i ] = buffer[ offset ++ ];
  37942. }
  37943. }
  37944. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37945. const dest = this.resolvedProperty;
  37946. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37947. dest[ i ] = buffer[ offset ++ ];
  37948. }
  37949. this.targetObject.needsUpdate = true;
  37950. }
  37951. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37952. const dest = this.resolvedProperty;
  37953. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37954. dest[ i ] = buffer[ offset ++ ];
  37955. }
  37956. this.targetObject.matrixWorldNeedsUpdate = true;
  37957. }
  37958. // ArrayElement
  37959. _setValue_arrayElement( buffer, offset ) {
  37960. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37961. }
  37962. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37963. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37964. this.targetObject.needsUpdate = true;
  37965. }
  37966. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37967. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37968. this.targetObject.matrixWorldNeedsUpdate = true;
  37969. }
  37970. // HasToFromArray
  37971. _setValue_fromArray( buffer, offset ) {
  37972. this.resolvedProperty.fromArray( buffer, offset );
  37973. }
  37974. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37975. this.resolvedProperty.fromArray( buffer, offset );
  37976. this.targetObject.needsUpdate = true;
  37977. }
  37978. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37979. this.resolvedProperty.fromArray( buffer, offset );
  37980. this.targetObject.matrixWorldNeedsUpdate = true;
  37981. }
  37982. _getValue_unbound( targetArray, offset ) {
  37983. this.bind();
  37984. this.getValue( targetArray, offset );
  37985. }
  37986. _setValue_unbound( sourceArray, offset ) {
  37987. this.bind();
  37988. this.setValue( sourceArray, offset );
  37989. }
  37990. /**
  37991. * Creates a getter / setter pair for the property tracked by this binding.
  37992. */
  37993. bind() {
  37994. let targetObject = this.node;
  37995. const parsedPath = this.parsedPath;
  37996. const objectName = parsedPath.objectName;
  37997. const propertyName = parsedPath.propertyName;
  37998. let propertyIndex = parsedPath.propertyIndex;
  37999. if ( ! targetObject ) {
  38000. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  38001. this.node = targetObject;
  38002. }
  38003. // set fail state so we can just 'return' on error
  38004. this.getValue = this._getValue_unavailable;
  38005. this.setValue = this._setValue_unavailable;
  38006. // ensure there is a value node
  38007. if ( ! targetObject ) {
  38008. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  38009. return;
  38010. }
  38011. if ( objectName ) {
  38012. let objectIndex = parsedPath.objectIndex;
  38013. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  38014. switch ( objectName ) {
  38015. case 'materials':
  38016. if ( ! targetObject.material ) {
  38017. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38018. return;
  38019. }
  38020. if ( ! targetObject.material.materials ) {
  38021. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  38022. return;
  38023. }
  38024. targetObject = targetObject.material.materials;
  38025. break;
  38026. case 'bones':
  38027. if ( ! targetObject.skeleton ) {
  38028. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  38029. return;
  38030. }
  38031. // potential future optimization: skip this if propertyIndex is already an integer
  38032. // and convert the integer string to a true integer.
  38033. targetObject = targetObject.skeleton.bones;
  38034. // support resolving morphTarget names into indices.
  38035. for ( let i = 0; i < targetObject.length; i ++ ) {
  38036. if ( targetObject[ i ].name === objectIndex ) {
  38037. objectIndex = i;
  38038. break;
  38039. }
  38040. }
  38041. break;
  38042. case 'map':
  38043. if ( 'map' in targetObject ) {
  38044. targetObject = targetObject.map;
  38045. break;
  38046. }
  38047. if ( ! targetObject.material ) {
  38048. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38049. return;
  38050. }
  38051. if ( ! targetObject.material.map ) {
  38052. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  38053. return;
  38054. }
  38055. targetObject = targetObject.material.map;
  38056. break;
  38057. default:
  38058. if ( targetObject[ objectName ] === undefined ) {
  38059. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  38060. return;
  38061. }
  38062. targetObject = targetObject[ objectName ];
  38063. }
  38064. if ( objectIndex !== undefined ) {
  38065. if ( targetObject[ objectIndex ] === undefined ) {
  38066. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  38067. return;
  38068. }
  38069. targetObject = targetObject[ objectIndex ];
  38070. }
  38071. }
  38072. // resolve property
  38073. const nodeProperty = targetObject[ propertyName ];
  38074. if ( nodeProperty === undefined ) {
  38075. const nodeName = parsedPath.nodeName;
  38076. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  38077. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  38078. return;
  38079. }
  38080. // determine versioning scheme
  38081. let versioning = this.Versioning.None;
  38082. this.targetObject = targetObject;
  38083. if ( targetObject.isMaterial === true ) {
  38084. versioning = this.Versioning.NeedsUpdate;
  38085. } else if ( targetObject.isObject3D === true ) {
  38086. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  38087. }
  38088. // determine how the property gets bound
  38089. let bindingType = this.BindingType.Direct;
  38090. if ( propertyIndex !== undefined ) {
  38091. // access a sub element of the property array (only primitives are supported right now)
  38092. if ( propertyName === 'morphTargetInfluences' ) {
  38093. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  38094. // support resolving morphTarget names into indices.
  38095. if ( ! targetObject.geometry ) {
  38096. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  38097. return;
  38098. }
  38099. if ( ! targetObject.geometry.morphAttributes ) {
  38100. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  38101. return;
  38102. }
  38103. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  38104. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  38105. }
  38106. }
  38107. bindingType = this.BindingType.ArrayElement;
  38108. this.resolvedProperty = nodeProperty;
  38109. this.propertyIndex = propertyIndex;
  38110. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  38111. // must use copy for Object3D.Euler/Quaternion
  38112. bindingType = this.BindingType.HasFromToArray;
  38113. this.resolvedProperty = nodeProperty;
  38114. } else if ( Array.isArray( nodeProperty ) ) {
  38115. bindingType = this.BindingType.EntireArray;
  38116. this.resolvedProperty = nodeProperty;
  38117. } else {
  38118. this.propertyName = propertyName;
  38119. }
  38120. // select getter / setter
  38121. this.getValue = this.GetterByBindingType[ bindingType ];
  38122. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  38123. }
  38124. /**
  38125. * Unbinds the property.
  38126. */
  38127. unbind() {
  38128. this.node = null;
  38129. // back to the prototype version of getValue / setValue
  38130. // note: avoiding to mutate the shape of 'this' via 'delete'
  38131. this.getValue = this._getValue_unbound;
  38132. this.setValue = this._setValue_unbound;
  38133. }
  38134. }
  38135. PropertyBinding.Composite = Composite;
  38136. PropertyBinding.prototype.BindingType = {
  38137. Direct: 0,
  38138. EntireArray: 1,
  38139. ArrayElement: 2,
  38140. HasFromToArray: 3
  38141. };
  38142. PropertyBinding.prototype.Versioning = {
  38143. None: 0,
  38144. NeedsUpdate: 1,
  38145. MatrixWorldNeedsUpdate: 2
  38146. };
  38147. PropertyBinding.prototype.GetterByBindingType = [
  38148. PropertyBinding.prototype._getValue_direct,
  38149. PropertyBinding.prototype._getValue_array,
  38150. PropertyBinding.prototype._getValue_arrayElement,
  38151. PropertyBinding.prototype._getValue_toArray,
  38152. ];
  38153. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  38154. [
  38155. // Direct
  38156. PropertyBinding.prototype._setValue_direct,
  38157. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  38158. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  38159. ], [
  38160. // EntireArray
  38161. PropertyBinding.prototype._setValue_array,
  38162. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  38163. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  38164. ], [
  38165. // ArrayElement
  38166. PropertyBinding.prototype._setValue_arrayElement,
  38167. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  38168. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  38169. ], [
  38170. // HasToFromArray
  38171. PropertyBinding.prototype._setValue_fromArray,
  38172. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  38173. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  38174. ]
  38175. ];
  38176. /**
  38177. * A group of objects that receives a shared animation state.
  38178. *
  38179. * Usage:
  38180. *
  38181. * - Add objects you would otherwise pass as 'root' to the
  38182. * constructor or the .clipAction method of AnimationMixer.
  38183. * - Instead pass this object as 'root'.
  38184. * - You can also add and remove objects later when the mixer is running.
  38185. *
  38186. * Note:
  38187. *
  38188. * - Objects of this class appear as one object to the mixer,
  38189. * so cache control of the individual objects must be done on the group.
  38190. *
  38191. * Limitation:
  38192. *
  38193. * - The animated properties must be compatible among the all objects in the group.
  38194. * - A single property can either be controlled through a target group or directly, but not both.
  38195. */
  38196. class AnimationObjectGroup {
  38197. /**
  38198. * Constructs a new animation group.
  38199. *
  38200. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  38201. */
  38202. constructor() {
  38203. /**
  38204. * This flag can be used for type testing.
  38205. *
  38206. * @type {boolean}
  38207. * @readonly
  38208. * @default true
  38209. */
  38210. this.isAnimationObjectGroup = true;
  38211. /**
  38212. * The UUID of the 3D object.
  38213. *
  38214. * @type {string}
  38215. * @readonly
  38216. */
  38217. this.uuid = generateUUID();
  38218. // cached objects followed by the active ones
  38219. this._objects = Array.prototype.slice.call( arguments );
  38220. this.nCachedObjects_ = 0; // threshold
  38221. // note: read by PropertyBinding.Composite
  38222. const indices = {};
  38223. this._indicesByUUID = indices; // for bookkeeping
  38224. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38225. indices[ arguments[ i ].uuid ] = i;
  38226. }
  38227. this._paths = []; // inside: string
  38228. this._parsedPaths = []; // inside: { we don't care, here }
  38229. this._bindings = []; // inside: Array< PropertyBinding >
  38230. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38231. const scope = this;
  38232. this.stats = {
  38233. objects: {
  38234. get total() {
  38235. return scope._objects.length;
  38236. },
  38237. get inUse() {
  38238. return this.total - scope.nCachedObjects_;
  38239. }
  38240. },
  38241. get bindingsPerObject() {
  38242. return scope._bindings.length;
  38243. }
  38244. };
  38245. }
  38246. /**
  38247. * Adds an arbitrary number of objects to this animation group.
  38248. *
  38249. * @param {...Object3D} arguments - The 3D objects to add.
  38250. */
  38251. add() {
  38252. const objects = this._objects,
  38253. indicesByUUID = this._indicesByUUID,
  38254. paths = this._paths,
  38255. parsedPaths = this._parsedPaths,
  38256. bindings = this._bindings,
  38257. nBindings = bindings.length;
  38258. let knownObject = undefined,
  38259. nObjects = objects.length,
  38260. nCachedObjects = this.nCachedObjects_;
  38261. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38262. const object = arguments[ i ],
  38263. uuid = object.uuid;
  38264. let index = indicesByUUID[ uuid ];
  38265. if ( index === undefined ) {
  38266. // unknown object -> add it to the ACTIVE region
  38267. index = nObjects ++;
  38268. indicesByUUID[ uuid ] = index;
  38269. objects.push( object );
  38270. // accounting is done, now do the same for all bindings
  38271. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38272. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38273. }
  38274. } else if ( index < nCachedObjects ) {
  38275. knownObject = objects[ index ];
  38276. // move existing object to the ACTIVE region
  38277. const firstActiveIndex = -- nCachedObjects,
  38278. lastCachedObject = objects[ firstActiveIndex ];
  38279. indicesByUUID[ lastCachedObject.uuid ] = index;
  38280. objects[ index ] = lastCachedObject;
  38281. indicesByUUID[ uuid ] = firstActiveIndex;
  38282. objects[ firstActiveIndex ] = object;
  38283. // accounting is done, now do the same for all bindings
  38284. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38285. const bindingsForPath = bindings[ j ],
  38286. lastCached = bindingsForPath[ firstActiveIndex ];
  38287. let binding = bindingsForPath[ index ];
  38288. bindingsForPath[ index ] = lastCached;
  38289. if ( binding === undefined ) {
  38290. // since we do not bother to create new bindings
  38291. // for objects that are cached, the binding may
  38292. // or may not exist
  38293. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38294. }
  38295. bindingsForPath[ firstActiveIndex ] = binding;
  38296. }
  38297. } else if ( objects[ index ] !== knownObject ) {
  38298. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38299. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38300. } // else the object is already where we want it to be
  38301. } // for arguments
  38302. this.nCachedObjects_ = nCachedObjects;
  38303. }
  38304. /**
  38305. * Removes an arbitrary number of objects to this animation group
  38306. *
  38307. * @param {...Object3D} arguments - The 3D objects to remove.
  38308. */
  38309. remove() {
  38310. const objects = this._objects,
  38311. indicesByUUID = this._indicesByUUID,
  38312. bindings = this._bindings,
  38313. nBindings = bindings.length;
  38314. let nCachedObjects = this.nCachedObjects_;
  38315. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38316. const object = arguments[ i ],
  38317. uuid = object.uuid,
  38318. index = indicesByUUID[ uuid ];
  38319. if ( index !== undefined && index >= nCachedObjects ) {
  38320. // move existing object into the CACHED region
  38321. const lastCachedIndex = nCachedObjects ++,
  38322. firstActiveObject = objects[ lastCachedIndex ];
  38323. indicesByUUID[ firstActiveObject.uuid ] = index;
  38324. objects[ index ] = firstActiveObject;
  38325. indicesByUUID[ uuid ] = lastCachedIndex;
  38326. objects[ lastCachedIndex ] = object;
  38327. // accounting is done, now do the same for all bindings
  38328. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38329. const bindingsForPath = bindings[ j ],
  38330. firstActive = bindingsForPath[ lastCachedIndex ],
  38331. binding = bindingsForPath[ index ];
  38332. bindingsForPath[ index ] = firstActive;
  38333. bindingsForPath[ lastCachedIndex ] = binding;
  38334. }
  38335. }
  38336. } // for arguments
  38337. this.nCachedObjects_ = nCachedObjects;
  38338. }
  38339. /**
  38340. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38341. *
  38342. * @param {...Object3D} arguments - The 3D objects to uncache.
  38343. */
  38344. uncache() {
  38345. const objects = this._objects,
  38346. indicesByUUID = this._indicesByUUID,
  38347. bindings = this._bindings,
  38348. nBindings = bindings.length;
  38349. let nCachedObjects = this.nCachedObjects_,
  38350. nObjects = objects.length;
  38351. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38352. const object = arguments[ i ],
  38353. uuid = object.uuid,
  38354. index = indicesByUUID[ uuid ];
  38355. if ( index !== undefined ) {
  38356. delete indicesByUUID[ uuid ];
  38357. if ( index < nCachedObjects ) {
  38358. // object is cached, shrink the CACHED region
  38359. const firstActiveIndex = -- nCachedObjects,
  38360. lastCachedObject = objects[ firstActiveIndex ],
  38361. lastIndex = -- nObjects,
  38362. lastObject = objects[ lastIndex ];
  38363. // last cached object takes this object's place
  38364. indicesByUUID[ lastCachedObject.uuid ] = index;
  38365. objects[ index ] = lastCachedObject;
  38366. // last object goes to the activated slot and pop
  38367. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38368. objects[ firstActiveIndex ] = lastObject;
  38369. objects.pop();
  38370. // accounting is done, now do the same for all bindings
  38371. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38372. const bindingsForPath = bindings[ j ],
  38373. lastCached = bindingsForPath[ firstActiveIndex ],
  38374. last = bindingsForPath[ lastIndex ];
  38375. bindingsForPath[ index ] = lastCached;
  38376. bindingsForPath[ firstActiveIndex ] = last;
  38377. bindingsForPath.pop();
  38378. }
  38379. } else {
  38380. // object is active, just swap with the last and pop
  38381. const lastIndex = -- nObjects,
  38382. lastObject = objects[ lastIndex ];
  38383. if ( lastIndex > 0 ) {
  38384. indicesByUUID[ lastObject.uuid ] = index;
  38385. }
  38386. objects[ index ] = lastObject;
  38387. objects.pop();
  38388. // accounting is done, now do the same for all bindings
  38389. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38390. const bindingsForPath = bindings[ j ];
  38391. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38392. bindingsForPath.pop();
  38393. }
  38394. } // cached or active
  38395. } // if object is known
  38396. } // for arguments
  38397. this.nCachedObjects_ = nCachedObjects;
  38398. }
  38399. // Internal interface used by befriended PropertyBinding.Composite:
  38400. subscribe_( path, parsedPath ) {
  38401. // returns an array of bindings for the given path that is changed
  38402. // according to the contained objects in the group
  38403. const indicesByPath = this._bindingsIndicesByPath;
  38404. let index = indicesByPath[ path ];
  38405. const bindings = this._bindings;
  38406. if ( index !== undefined ) return bindings[ index ];
  38407. const paths = this._paths,
  38408. parsedPaths = this._parsedPaths,
  38409. objects = this._objects,
  38410. nObjects = objects.length,
  38411. nCachedObjects = this.nCachedObjects_,
  38412. bindingsForPath = new Array( nObjects );
  38413. index = bindings.length;
  38414. indicesByPath[ path ] = index;
  38415. paths.push( path );
  38416. parsedPaths.push( parsedPath );
  38417. bindings.push( bindingsForPath );
  38418. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38419. const object = objects[ i ];
  38420. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38421. }
  38422. return bindingsForPath;
  38423. }
  38424. unsubscribe_( path ) {
  38425. // tells the group to forget about a property path and no longer
  38426. // update the array previously obtained with 'subscribe_'
  38427. const indicesByPath = this._bindingsIndicesByPath,
  38428. index = indicesByPath[ path ];
  38429. if ( index !== undefined ) {
  38430. const paths = this._paths,
  38431. parsedPaths = this._parsedPaths,
  38432. bindings = this._bindings,
  38433. lastBindingsIndex = bindings.length - 1,
  38434. lastBindings = bindings[ lastBindingsIndex ],
  38435. lastBindingsPath = path[ lastBindingsIndex ];
  38436. indicesByPath[ lastBindingsPath ] = index;
  38437. bindings[ index ] = lastBindings;
  38438. bindings.pop();
  38439. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38440. parsedPaths.pop();
  38441. paths[ index ] = paths[ lastBindingsIndex ];
  38442. paths.pop();
  38443. }
  38444. }
  38445. }
  38446. /**
  38447. * An instance of `AnimationAction` schedules the playback of an animation which is
  38448. * stored in {@link AnimationClip}.
  38449. */
  38450. class AnimationAction {
  38451. /**
  38452. * Constructs a new animation action.
  38453. *
  38454. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38455. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38456. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38457. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38458. */
  38459. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38460. this._mixer = mixer;
  38461. this._clip = clip;
  38462. this._localRoot = localRoot;
  38463. /**
  38464. * Defines how the animation is blended/combined when two or more animations
  38465. * are simultaneously played.
  38466. *
  38467. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38468. */
  38469. this.blendMode = blendMode;
  38470. const tracks = clip.tracks,
  38471. nTracks = tracks.length,
  38472. interpolants = new Array( nTracks );
  38473. const interpolantSettings = {
  38474. endingStart: ZeroCurvatureEnding,
  38475. endingEnd: ZeroCurvatureEnding
  38476. };
  38477. for ( let i = 0; i !== nTracks; ++ i ) {
  38478. const interpolant = tracks[ i ].createInterpolant( null );
  38479. interpolants[ i ] = interpolant;
  38480. interpolant.settings = interpolantSettings;
  38481. }
  38482. this._interpolantSettings = interpolantSettings;
  38483. this._interpolants = interpolants; // bound by the mixer
  38484. // inside: PropertyMixer (managed by the mixer)
  38485. this._propertyBindings = new Array( nTracks );
  38486. this._cacheIndex = null; // for the memory manager
  38487. this._byClipCacheIndex = null; // for the memory manager
  38488. this._timeScaleInterpolant = null;
  38489. this._weightInterpolant = null;
  38490. /**
  38491. * The loop mode, set via {@link AnimationAction#setLoop}.
  38492. *
  38493. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38494. * @default LoopRepeat
  38495. */
  38496. this.loop = LoopRepeat;
  38497. this._loopCount = -1;
  38498. // global mixer time when the action is to be started
  38499. // it's set back to 'null' upon start of the action
  38500. this._startTime = null;
  38501. /**
  38502. * The local time of this action (in seconds, starting with `0`).
  38503. *
  38504. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38505. * loop state).
  38506. *
  38507. * @type {number}
  38508. * @default Infinity
  38509. */
  38510. this.time = 0;
  38511. /**
  38512. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38513. * animation to pause. Negative values cause the animation to play backwards.
  38514. *
  38515. * @type {number}
  38516. * @default 1
  38517. */
  38518. this.timeScale = 1;
  38519. this._effectiveTimeScale = 1;
  38520. /**
  38521. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38522. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38523. * several actions.
  38524. *
  38525. * @type {number}
  38526. * @default 1
  38527. */
  38528. this.weight = 1;
  38529. this._effectiveWeight = 1;
  38530. /**
  38531. * The number of repetitions of the performed clip over the course of this action.
  38532. * Can be set via {@link AnimationAction#setLoop}.
  38533. *
  38534. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38535. * `THREE:LoopOnce`.
  38536. *
  38537. * @type {number}
  38538. * @default Infinity
  38539. */
  38540. this.repetitions = Infinity;
  38541. /**
  38542. * If set to `true`, the playback of the action is paused.
  38543. *
  38544. * @type {boolean}
  38545. * @default false
  38546. */
  38547. this.paused = false;
  38548. /**
  38549. * If set to `false`, the action is disabled so it has no impact.
  38550. *
  38551. * When the action is re-enabled, the animation continues from its current
  38552. * time (setting `enabled` to `false` doesn't reset the action).
  38553. *
  38554. * @type {boolean}
  38555. * @default true
  38556. */
  38557. this.enabled = true;
  38558. /**
  38559. * If set to true the animation will automatically be paused on its last frame.
  38560. *
  38561. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38562. * to `false` when the last loop of the action has finished, so that this action has
  38563. * no further impact.
  38564. *
  38565. * Note: This member has no impact if the action is interrupted (it
  38566. * has only an effect if its last loop has really finished).
  38567. *
  38568. * @type {boolean}
  38569. * @default false
  38570. */
  38571. this.clampWhenFinished = false;
  38572. /**
  38573. * Enables smooth interpolation without separate clips for start, loop and end.
  38574. *
  38575. * @type {boolean}
  38576. * @default true
  38577. */
  38578. this.zeroSlopeAtStart = true;
  38579. /**
  38580. * Enables smooth interpolation without separate clips for start, loop and end.
  38581. *
  38582. * @type {boolean}
  38583. * @default true
  38584. */
  38585. this.zeroSlopeAtEnd = true;
  38586. }
  38587. /**
  38588. * Starts the playback of the animation.
  38589. *
  38590. * @return {AnimationAction} A reference to this animation action.
  38591. */
  38592. play() {
  38593. this._mixer._activateAction( this );
  38594. return this;
  38595. }
  38596. /**
  38597. * Stops the playback of the animation.
  38598. *
  38599. * @return {AnimationAction} A reference to this animation action.
  38600. */
  38601. stop() {
  38602. this._mixer._deactivateAction( this );
  38603. return this.reset();
  38604. }
  38605. /**
  38606. * Resets the playback of the animation.
  38607. *
  38608. * @return {AnimationAction} A reference to this animation action.
  38609. */
  38610. reset() {
  38611. this.paused = false;
  38612. this.enabled = true;
  38613. this.time = 0; // restart clip
  38614. this._loopCount = -1;// forget previous loops
  38615. this._startTime = null;// forget scheduling
  38616. return this.stopFading().stopWarping();
  38617. }
  38618. /**
  38619. * Returns `true` if the animation is running.
  38620. *
  38621. * @return {boolean} Whether the animation is running or not.
  38622. */
  38623. isRunning() {
  38624. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38625. this._startTime === null && this._mixer._isActiveAction( this );
  38626. }
  38627. /**
  38628. * Returns `true` when {@link AnimationAction#play} has been called.
  38629. *
  38630. * @return {boolean} Whether the animation is scheduled or not.
  38631. */
  38632. isScheduled() {
  38633. return this._mixer._isActiveAction( this );
  38634. }
  38635. /**
  38636. * Defines the time when the animation should start.
  38637. *
  38638. * @param {number} time - The start time in seconds.
  38639. * @return {AnimationAction} A reference to this animation action.
  38640. */
  38641. startAt( time ) {
  38642. this._startTime = time;
  38643. return this;
  38644. }
  38645. /**
  38646. * Configures the loop settings for this action.
  38647. *
  38648. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38649. * @param {number} repetitions - The number of repetitions.
  38650. * @return {AnimationAction} A reference to this animation action.
  38651. */
  38652. setLoop( mode, repetitions ) {
  38653. this.loop = mode;
  38654. this.repetitions = repetitions;
  38655. return this;
  38656. }
  38657. /**
  38658. * Sets the effective weight of this action.
  38659. *
  38660. * An action has no effect and thus an effective weight of zero when the
  38661. * action is disabled.
  38662. *
  38663. * @param {number} weight - The weight to set.
  38664. * @return {AnimationAction} A reference to this animation action.
  38665. */
  38666. setEffectiveWeight( weight ) {
  38667. this.weight = weight;
  38668. // note: same logic as when updated at runtime
  38669. this._effectiveWeight = this.enabled ? weight : 0;
  38670. return this.stopFading();
  38671. }
  38672. /**
  38673. * Returns the effective weight of this action.
  38674. *
  38675. * @return {number} The effective weight.
  38676. */
  38677. getEffectiveWeight() {
  38678. return this._effectiveWeight;
  38679. }
  38680. /**
  38681. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38682. * within the passed time interval.
  38683. *
  38684. * @param {number} duration - The duration of the fade.
  38685. * @return {AnimationAction} A reference to this animation action.
  38686. */
  38687. fadeIn( duration ) {
  38688. return this._scheduleFading( duration, 0, 1 );
  38689. }
  38690. /**
  38691. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38692. * within the passed time interval.
  38693. *
  38694. * @param {number} duration - The duration of the fade.
  38695. * @return {AnimationAction} A reference to this animation action.
  38696. */
  38697. fadeOut( duration ) {
  38698. return this._scheduleFading( duration, 1, 0 );
  38699. }
  38700. /**
  38701. * Causes this action to fade in and the given action to fade out,
  38702. * within the passed time interval.
  38703. *
  38704. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38705. * @param {number} duration - The duration of the fade.
  38706. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38707. * @return {AnimationAction} A reference to this animation action.
  38708. */
  38709. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38710. fadeOutAction.fadeOut( duration );
  38711. this.fadeIn( duration );
  38712. if ( warp === true ) {
  38713. const fadeInDuration = this._clip.duration,
  38714. fadeOutDuration = fadeOutAction._clip.duration,
  38715. startEndRatio = fadeOutDuration / fadeInDuration,
  38716. endStartRatio = fadeInDuration / fadeOutDuration;
  38717. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38718. this.warp( endStartRatio, 1.0, duration );
  38719. }
  38720. return this;
  38721. }
  38722. /**
  38723. * Causes this action to fade out and the given action to fade in,
  38724. * within the passed time interval.
  38725. *
  38726. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38727. * @param {number} duration - The duration of the fade.
  38728. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38729. * @return {AnimationAction} A reference to this animation action.
  38730. */
  38731. crossFadeTo( fadeInAction, duration, warp = false ) {
  38732. return fadeInAction.crossFadeFrom( this, duration, warp );
  38733. }
  38734. /**
  38735. * Stops any fading which is applied to this action.
  38736. *
  38737. * @return {AnimationAction} A reference to this animation action.
  38738. */
  38739. stopFading() {
  38740. const weightInterpolant = this._weightInterpolant;
  38741. if ( weightInterpolant !== null ) {
  38742. this._weightInterpolant = null;
  38743. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38744. }
  38745. return this;
  38746. }
  38747. /**
  38748. * Sets the effective time scale of this action.
  38749. *
  38750. * An action has no effect and thus an effective time scale of zero when the
  38751. * action is paused.
  38752. *
  38753. * @param {number} timeScale - The time scale to set.
  38754. * @return {AnimationAction} A reference to this animation action.
  38755. */
  38756. setEffectiveTimeScale( timeScale ) {
  38757. this.timeScale = timeScale;
  38758. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38759. return this.stopWarping();
  38760. }
  38761. /**
  38762. * Returns the effective time scale of this action.
  38763. *
  38764. * @return {number} The effective time scale.
  38765. */
  38766. getEffectiveTimeScale() {
  38767. return this._effectiveTimeScale;
  38768. }
  38769. /**
  38770. * Sets the duration for a single loop of this action.
  38771. *
  38772. * @param {number} duration - The duration to set.
  38773. * @return {AnimationAction} A reference to this animation action.
  38774. */
  38775. setDuration( duration ) {
  38776. this.timeScale = this._clip.duration / duration;
  38777. return this.stopWarping();
  38778. }
  38779. /**
  38780. * Synchronizes this action with the passed other action.
  38781. *
  38782. * @param {AnimationAction} action - The action to sync with.
  38783. * @return {AnimationAction} A reference to this animation action.
  38784. */
  38785. syncWith( action ) {
  38786. this.time = action.time;
  38787. this.timeScale = action.timeScale;
  38788. return this.stopWarping();
  38789. }
  38790. /**
  38791. * Decelerates this animation's speed to `0` within the passed time interval.
  38792. *
  38793. * @param {number} duration - The duration.
  38794. * @return {AnimationAction} A reference to this animation action.
  38795. */
  38796. halt( duration ) {
  38797. return this.warp( this._effectiveTimeScale, 0, duration );
  38798. }
  38799. /**
  38800. * Changes the playback speed, within the passed time interval, by modifying
  38801. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38802. * `endTimeScale`.
  38803. *
  38804. * @param {number} startTimeScale - The start time scale.
  38805. * @param {number} endTimeScale - The end time scale.
  38806. * @param {number} duration - The duration.
  38807. * @return {AnimationAction} A reference to this animation action.
  38808. */
  38809. warp( startTimeScale, endTimeScale, duration ) {
  38810. const mixer = this._mixer,
  38811. now = mixer.time,
  38812. timeScale = this.timeScale;
  38813. let interpolant = this._timeScaleInterpolant;
  38814. if ( interpolant === null ) {
  38815. interpolant = mixer._lendControlInterpolant();
  38816. this._timeScaleInterpolant = interpolant;
  38817. }
  38818. const times = interpolant.parameterPositions,
  38819. values = interpolant.sampleValues;
  38820. times[ 0 ] = now;
  38821. times[ 1 ] = now + duration;
  38822. values[ 0 ] = startTimeScale / timeScale;
  38823. values[ 1 ] = endTimeScale / timeScale;
  38824. return this;
  38825. }
  38826. /**
  38827. * Stops any scheduled warping which is applied to this action.
  38828. *
  38829. * @return {AnimationAction} A reference to this animation action.
  38830. */
  38831. stopWarping() {
  38832. const timeScaleInterpolant = this._timeScaleInterpolant;
  38833. if ( timeScaleInterpolant !== null ) {
  38834. this._timeScaleInterpolant = null;
  38835. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38836. }
  38837. return this;
  38838. }
  38839. /**
  38840. * Returns the animation mixer of this animation action.
  38841. *
  38842. * @return {AnimationMixer} The animation mixer.
  38843. */
  38844. getMixer() {
  38845. return this._mixer;
  38846. }
  38847. /**
  38848. * Returns the animation clip of this animation action.
  38849. *
  38850. * @return {AnimationClip} The animation clip.
  38851. */
  38852. getClip() {
  38853. return this._clip;
  38854. }
  38855. /**
  38856. * Returns the root object of this animation action.
  38857. *
  38858. * @return {Object3D} The root object.
  38859. */
  38860. getRoot() {
  38861. return this._localRoot || this._mixer._root;
  38862. }
  38863. // Internal
  38864. _update( time, deltaTime, timeDirection, accuIndex ) {
  38865. // called by the mixer
  38866. if ( ! this.enabled ) {
  38867. // call ._updateWeight() to update ._effectiveWeight
  38868. this._updateWeight( time );
  38869. return;
  38870. }
  38871. const startTime = this._startTime;
  38872. if ( startTime !== null ) {
  38873. // check for scheduled start of action
  38874. const timeRunning = ( time - startTime ) * timeDirection;
  38875. if ( timeRunning < 0 || timeDirection === 0 ) {
  38876. deltaTime = 0;
  38877. } else {
  38878. this._startTime = null; // unschedule
  38879. deltaTime = timeDirection * timeRunning;
  38880. }
  38881. }
  38882. // apply time scale and advance time
  38883. deltaTime *= this._updateTimeScale( time );
  38884. const clipTime = this._updateTime( deltaTime );
  38885. // note: _updateTime may disable the action resulting in
  38886. // an effective weight of 0
  38887. const weight = this._updateWeight( time );
  38888. if ( weight > 0 ) {
  38889. const interpolants = this._interpolants;
  38890. const propertyMixers = this._propertyBindings;
  38891. switch ( this.blendMode ) {
  38892. case AdditiveAnimationBlendMode:
  38893. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38894. interpolants[ j ].evaluate( clipTime );
  38895. propertyMixers[ j ].accumulateAdditive( weight );
  38896. }
  38897. break;
  38898. case NormalAnimationBlendMode:
  38899. default:
  38900. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38901. interpolants[ j ].evaluate( clipTime );
  38902. propertyMixers[ j ].accumulate( accuIndex, weight );
  38903. }
  38904. }
  38905. }
  38906. }
  38907. _updateWeight( time ) {
  38908. let weight = 0;
  38909. if ( this.enabled ) {
  38910. weight = this.weight;
  38911. const interpolant = this._weightInterpolant;
  38912. if ( interpolant !== null ) {
  38913. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38914. weight *= interpolantValue;
  38915. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38916. this.stopFading();
  38917. if ( interpolantValue === 0 ) {
  38918. // faded out, disable
  38919. this.enabled = false;
  38920. }
  38921. }
  38922. }
  38923. }
  38924. this._effectiveWeight = weight;
  38925. return weight;
  38926. }
  38927. _updateTimeScale( time ) {
  38928. let timeScale = 0;
  38929. if ( ! this.paused ) {
  38930. timeScale = this.timeScale;
  38931. const interpolant = this._timeScaleInterpolant;
  38932. if ( interpolant !== null ) {
  38933. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38934. timeScale *= interpolantValue;
  38935. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38936. this.stopWarping();
  38937. if ( timeScale === 0 ) {
  38938. // motion has halted, pause
  38939. this.paused = true;
  38940. } else {
  38941. // warp done - apply final time scale
  38942. this.timeScale = timeScale;
  38943. }
  38944. }
  38945. }
  38946. }
  38947. this._effectiveTimeScale = timeScale;
  38948. return timeScale;
  38949. }
  38950. _updateTime( deltaTime ) {
  38951. const duration = this._clip.duration;
  38952. const loop = this.loop;
  38953. let time = this.time + deltaTime;
  38954. let loopCount = this._loopCount;
  38955. const pingPong = ( loop === LoopPingPong );
  38956. if ( deltaTime === 0 ) {
  38957. if ( loopCount === -1 ) return time;
  38958. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38959. }
  38960. if ( loop === LoopOnce ) {
  38961. if ( loopCount === -1 ) {
  38962. // just started
  38963. this._loopCount = 0;
  38964. this._setEndings( true, true, false );
  38965. }
  38966. handle_stop: {
  38967. if ( time >= duration ) {
  38968. time = duration;
  38969. } else if ( time < 0 ) {
  38970. time = 0;
  38971. } else {
  38972. this.time = time;
  38973. break handle_stop;
  38974. }
  38975. if ( this.clampWhenFinished ) this.paused = true;
  38976. else this.enabled = false;
  38977. this.time = time;
  38978. this._mixer.dispatchEvent( {
  38979. type: 'finished', action: this,
  38980. direction: deltaTime < 0 ? -1 : 1
  38981. } );
  38982. }
  38983. } else { // repetitive Repeat or PingPong
  38984. if ( loopCount === -1 ) {
  38985. // just started
  38986. if ( deltaTime >= 0 ) {
  38987. loopCount = 0;
  38988. this._setEndings( true, this.repetitions === 0, pingPong );
  38989. } else {
  38990. // when looping in reverse direction, the initial
  38991. // transition through zero counts as a repetition,
  38992. // so leave loopCount at -1
  38993. this._setEndings( this.repetitions === 0, true, pingPong );
  38994. }
  38995. }
  38996. if ( time >= duration || time < 0 ) {
  38997. // wrap around
  38998. const loopDelta = Math.floor( time / duration ); // signed
  38999. time -= duration * loopDelta;
  39000. loopCount += Math.abs( loopDelta );
  39001. const pending = this.repetitions - loopCount;
  39002. if ( pending <= 0 ) {
  39003. // have to stop (switch state, clamp time, fire event)
  39004. if ( this.clampWhenFinished ) this.paused = true;
  39005. else this.enabled = false;
  39006. time = deltaTime > 0 ? duration : 0;
  39007. this.time = time;
  39008. this._mixer.dispatchEvent( {
  39009. type: 'finished', action: this,
  39010. direction: deltaTime > 0 ? 1 : -1
  39011. } );
  39012. } else {
  39013. // keep running
  39014. if ( pending === 1 ) {
  39015. // entering the last round
  39016. const atStart = deltaTime < 0;
  39017. this._setEndings( atStart, ! atStart, pingPong );
  39018. } else {
  39019. this._setEndings( false, false, pingPong );
  39020. }
  39021. this._loopCount = loopCount;
  39022. this.time = time;
  39023. this._mixer.dispatchEvent( {
  39024. type: 'loop', action: this, loopDelta: loopDelta
  39025. } );
  39026. }
  39027. } else {
  39028. this.time = time;
  39029. }
  39030. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  39031. // invert time for the "pong round"
  39032. return duration - time;
  39033. }
  39034. }
  39035. return time;
  39036. }
  39037. _setEndings( atStart, atEnd, pingPong ) {
  39038. const settings = this._interpolantSettings;
  39039. if ( pingPong ) {
  39040. settings.endingStart = ZeroSlopeEnding;
  39041. settings.endingEnd = ZeroSlopeEnding;
  39042. } else {
  39043. // assuming for LoopOnce atStart == atEnd == true
  39044. if ( atStart ) {
  39045. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39046. } else {
  39047. settings.endingStart = WrapAroundEnding;
  39048. }
  39049. if ( atEnd ) {
  39050. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39051. } else {
  39052. settings.endingEnd = WrapAroundEnding;
  39053. }
  39054. }
  39055. }
  39056. _scheduleFading( duration, weightNow, weightThen ) {
  39057. const mixer = this._mixer, now = mixer.time;
  39058. let interpolant = this._weightInterpolant;
  39059. if ( interpolant === null ) {
  39060. interpolant = mixer._lendControlInterpolant();
  39061. this._weightInterpolant = interpolant;
  39062. }
  39063. const times = interpolant.parameterPositions,
  39064. values = interpolant.sampleValues;
  39065. times[ 0 ] = now;
  39066. values[ 0 ] = weightNow;
  39067. times[ 1 ] = now + duration;
  39068. values[ 1 ] = weightThen;
  39069. return this;
  39070. }
  39071. }
  39072. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  39073. /**
  39074. * `AnimationMixer` is a player for animations on a particular object in
  39075. * the scene. When multiple objects in the scene are animated independently,
  39076. * one `AnimationMixer` may be used for each object.
  39077. */
  39078. class AnimationMixer extends EventDispatcher {
  39079. /**
  39080. * Constructs a new animation mixer.
  39081. *
  39082. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  39083. */
  39084. constructor( root ) {
  39085. super();
  39086. this._root = root;
  39087. this._initMemoryManager();
  39088. this._accuIndex = 0;
  39089. /**
  39090. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  39091. *
  39092. * @type {number}
  39093. * @default 0
  39094. */
  39095. this.time = 0;
  39096. /**
  39097. * A scaling factor for the global time.
  39098. *
  39099. * Note: Setting this member to `0` and later back to `1` is a
  39100. * possibility to pause/unpause all actions that are controlled by this
  39101. * mixer.
  39102. *
  39103. * @type {number}
  39104. * @default 1
  39105. */
  39106. this.timeScale = 1.0;
  39107. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  39108. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  39109. }
  39110. }
  39111. _bindAction( action, prototypeAction ) {
  39112. const root = action._localRoot || this._root,
  39113. tracks = action._clip.tracks,
  39114. nTracks = tracks.length,
  39115. bindings = action._propertyBindings,
  39116. interpolants = action._interpolants,
  39117. rootUuid = root.uuid,
  39118. bindingsByRoot = this._bindingsByRootAndName;
  39119. let bindingsByName = bindingsByRoot[ rootUuid ];
  39120. if ( bindingsByName === undefined ) {
  39121. bindingsByName = {};
  39122. bindingsByRoot[ rootUuid ] = bindingsByName;
  39123. }
  39124. for ( let i = 0; i !== nTracks; ++ i ) {
  39125. const track = tracks[ i ],
  39126. trackName = track.name;
  39127. let binding = bindingsByName[ trackName ];
  39128. if ( binding !== undefined ) {
  39129. ++ binding.referenceCount;
  39130. bindings[ i ] = binding;
  39131. } else {
  39132. binding = bindings[ i ];
  39133. if ( binding !== undefined ) {
  39134. // existing binding, make sure the cache knows
  39135. if ( binding._cacheIndex === null ) {
  39136. ++ binding.referenceCount;
  39137. this._addInactiveBinding( binding, rootUuid, trackName );
  39138. }
  39139. continue;
  39140. }
  39141. const path = prototypeAction && prototypeAction.
  39142. _propertyBindings[ i ].binding.parsedPath;
  39143. binding = new PropertyMixer(
  39144. PropertyBinding.create( root, trackName, path ),
  39145. track.ValueTypeName, track.getValueSize() );
  39146. ++ binding.referenceCount;
  39147. this._addInactiveBinding( binding, rootUuid, trackName );
  39148. bindings[ i ] = binding;
  39149. }
  39150. interpolants[ i ].resultBuffer = binding.buffer;
  39151. }
  39152. }
  39153. _activateAction( action ) {
  39154. if ( ! this._isActiveAction( action ) ) {
  39155. if ( action._cacheIndex === null ) {
  39156. // this action has been forgotten by the cache, but the user
  39157. // appears to be still using it -> rebind
  39158. const rootUuid = ( action._localRoot || this._root ).uuid,
  39159. clipUuid = action._clip.uuid,
  39160. actionsForClip = this._actionsByClip[ clipUuid ];
  39161. this._bindAction( action,
  39162. actionsForClip && actionsForClip.knownActions[ 0 ] );
  39163. this._addInactiveAction( action, clipUuid, rootUuid );
  39164. }
  39165. const bindings = action._propertyBindings;
  39166. // increment reference counts / sort out state
  39167. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39168. const binding = bindings[ i ];
  39169. if ( binding.useCount ++ === 0 ) {
  39170. this._lendBinding( binding );
  39171. binding.saveOriginalState();
  39172. }
  39173. }
  39174. this._lendAction( action );
  39175. }
  39176. }
  39177. _deactivateAction( action ) {
  39178. if ( this._isActiveAction( action ) ) {
  39179. const bindings = action._propertyBindings;
  39180. // decrement reference counts / sort out state
  39181. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39182. const binding = bindings[ i ];
  39183. if ( -- binding.useCount === 0 ) {
  39184. binding.restoreOriginalState();
  39185. this._takeBackBinding( binding );
  39186. }
  39187. }
  39188. this._takeBackAction( action );
  39189. }
  39190. }
  39191. // Memory manager
  39192. _initMemoryManager() {
  39193. this._actions = []; // 'nActiveActions' followed by inactive ones
  39194. this._nActiveActions = 0;
  39195. this._actionsByClip = {};
  39196. // inside:
  39197. // {
  39198. // knownActions: Array< AnimationAction > - used as prototypes
  39199. // actionByRoot: AnimationAction - lookup
  39200. // }
  39201. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  39202. this._nActiveBindings = 0;
  39203. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39204. this._controlInterpolants = []; // same game as above
  39205. this._nActiveControlInterpolants = 0;
  39206. const scope = this;
  39207. this.stats = {
  39208. actions: {
  39209. get total() {
  39210. return scope._actions.length;
  39211. },
  39212. get inUse() {
  39213. return scope._nActiveActions;
  39214. }
  39215. },
  39216. bindings: {
  39217. get total() {
  39218. return scope._bindings.length;
  39219. },
  39220. get inUse() {
  39221. return scope._nActiveBindings;
  39222. }
  39223. },
  39224. controlInterpolants: {
  39225. get total() {
  39226. return scope._controlInterpolants.length;
  39227. },
  39228. get inUse() {
  39229. return scope._nActiveControlInterpolants;
  39230. }
  39231. }
  39232. };
  39233. }
  39234. // Memory management for AnimationAction objects
  39235. _isActiveAction( action ) {
  39236. const index = action._cacheIndex;
  39237. return index !== null && index < this._nActiveActions;
  39238. }
  39239. _addInactiveAction( action, clipUuid, rootUuid ) {
  39240. const actions = this._actions,
  39241. actionsByClip = this._actionsByClip;
  39242. let actionsForClip = actionsByClip[ clipUuid ];
  39243. if ( actionsForClip === undefined ) {
  39244. actionsForClip = {
  39245. knownActions: [ action ],
  39246. actionByRoot: {}
  39247. };
  39248. action._byClipCacheIndex = 0;
  39249. actionsByClip[ clipUuid ] = actionsForClip;
  39250. } else {
  39251. const knownActions = actionsForClip.knownActions;
  39252. action._byClipCacheIndex = knownActions.length;
  39253. knownActions.push( action );
  39254. }
  39255. action._cacheIndex = actions.length;
  39256. actions.push( action );
  39257. actionsForClip.actionByRoot[ rootUuid ] = action;
  39258. }
  39259. _removeInactiveAction( action ) {
  39260. const actions = this._actions,
  39261. lastInactiveAction = actions[ actions.length - 1 ],
  39262. cacheIndex = action._cacheIndex;
  39263. lastInactiveAction._cacheIndex = cacheIndex;
  39264. actions[ cacheIndex ] = lastInactiveAction;
  39265. actions.pop();
  39266. action._cacheIndex = null;
  39267. const clipUuid = action._clip.uuid,
  39268. actionsByClip = this._actionsByClip,
  39269. actionsForClip = actionsByClip[ clipUuid ],
  39270. knownActionsForClip = actionsForClip.knownActions,
  39271. lastKnownAction =
  39272. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39273. byClipCacheIndex = action._byClipCacheIndex;
  39274. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39275. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39276. knownActionsForClip.pop();
  39277. action._byClipCacheIndex = null;
  39278. const actionByRoot = actionsForClip.actionByRoot,
  39279. rootUuid = ( action._localRoot || this._root ).uuid;
  39280. delete actionByRoot[ rootUuid ];
  39281. if ( knownActionsForClip.length === 0 ) {
  39282. delete actionsByClip[ clipUuid ];
  39283. }
  39284. this._removeInactiveBindingsForAction( action );
  39285. }
  39286. _removeInactiveBindingsForAction( action ) {
  39287. const bindings = action._propertyBindings;
  39288. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39289. const binding = bindings[ i ];
  39290. if ( -- binding.referenceCount === 0 ) {
  39291. this._removeInactiveBinding( binding );
  39292. }
  39293. }
  39294. }
  39295. _lendAction( action ) {
  39296. // [ active actions | inactive actions ]
  39297. // [ active actions >| inactive actions ]
  39298. // s a
  39299. // <-swap->
  39300. // a s
  39301. const actions = this._actions,
  39302. prevIndex = action._cacheIndex,
  39303. lastActiveIndex = this._nActiveActions ++,
  39304. firstInactiveAction = actions[ lastActiveIndex ];
  39305. action._cacheIndex = lastActiveIndex;
  39306. actions[ lastActiveIndex ] = action;
  39307. firstInactiveAction._cacheIndex = prevIndex;
  39308. actions[ prevIndex ] = firstInactiveAction;
  39309. }
  39310. _takeBackAction( action ) {
  39311. // [ active actions | inactive actions ]
  39312. // [ active actions |< inactive actions ]
  39313. // a s
  39314. // <-swap->
  39315. // s a
  39316. const actions = this._actions,
  39317. prevIndex = action._cacheIndex,
  39318. firstInactiveIndex = -- this._nActiveActions,
  39319. lastActiveAction = actions[ firstInactiveIndex ];
  39320. action._cacheIndex = firstInactiveIndex;
  39321. actions[ firstInactiveIndex ] = action;
  39322. lastActiveAction._cacheIndex = prevIndex;
  39323. actions[ prevIndex ] = lastActiveAction;
  39324. }
  39325. // Memory management for PropertyMixer objects
  39326. _addInactiveBinding( binding, rootUuid, trackName ) {
  39327. const bindingsByRoot = this._bindingsByRootAndName,
  39328. bindings = this._bindings;
  39329. let bindingByName = bindingsByRoot[ rootUuid ];
  39330. if ( bindingByName === undefined ) {
  39331. bindingByName = {};
  39332. bindingsByRoot[ rootUuid ] = bindingByName;
  39333. }
  39334. bindingByName[ trackName ] = binding;
  39335. binding._cacheIndex = bindings.length;
  39336. bindings.push( binding );
  39337. }
  39338. _removeInactiveBinding( binding ) {
  39339. const bindings = this._bindings,
  39340. propBinding = binding.binding,
  39341. rootUuid = propBinding.rootNode.uuid,
  39342. trackName = propBinding.path,
  39343. bindingsByRoot = this._bindingsByRootAndName,
  39344. bindingByName = bindingsByRoot[ rootUuid ],
  39345. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39346. cacheIndex = binding._cacheIndex;
  39347. lastInactiveBinding._cacheIndex = cacheIndex;
  39348. bindings[ cacheIndex ] = lastInactiveBinding;
  39349. bindings.pop();
  39350. delete bindingByName[ trackName ];
  39351. if ( Object.keys( bindingByName ).length === 0 ) {
  39352. delete bindingsByRoot[ rootUuid ];
  39353. }
  39354. }
  39355. _lendBinding( binding ) {
  39356. const bindings = this._bindings,
  39357. prevIndex = binding._cacheIndex,
  39358. lastActiveIndex = this._nActiveBindings ++,
  39359. firstInactiveBinding = bindings[ lastActiveIndex ];
  39360. binding._cacheIndex = lastActiveIndex;
  39361. bindings[ lastActiveIndex ] = binding;
  39362. firstInactiveBinding._cacheIndex = prevIndex;
  39363. bindings[ prevIndex ] = firstInactiveBinding;
  39364. }
  39365. _takeBackBinding( binding ) {
  39366. const bindings = this._bindings,
  39367. prevIndex = binding._cacheIndex,
  39368. firstInactiveIndex = -- this._nActiveBindings,
  39369. lastActiveBinding = bindings[ firstInactiveIndex ];
  39370. binding._cacheIndex = firstInactiveIndex;
  39371. bindings[ firstInactiveIndex ] = binding;
  39372. lastActiveBinding._cacheIndex = prevIndex;
  39373. bindings[ prevIndex ] = lastActiveBinding;
  39374. }
  39375. // Memory management of Interpolants for weight and time scale
  39376. _lendControlInterpolant() {
  39377. const interpolants = this._controlInterpolants,
  39378. lastActiveIndex = this._nActiveControlInterpolants ++;
  39379. let interpolant = interpolants[ lastActiveIndex ];
  39380. if ( interpolant === undefined ) {
  39381. interpolant = new LinearInterpolant(
  39382. new Float32Array( 2 ), new Float32Array( 2 ),
  39383. 1, _controlInterpolantsResultBuffer );
  39384. interpolant.__cacheIndex = lastActiveIndex;
  39385. interpolants[ lastActiveIndex ] = interpolant;
  39386. }
  39387. return interpolant;
  39388. }
  39389. _takeBackControlInterpolant( interpolant ) {
  39390. const interpolants = this._controlInterpolants,
  39391. prevIndex = interpolant.__cacheIndex,
  39392. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39393. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39394. interpolant.__cacheIndex = firstInactiveIndex;
  39395. interpolants[ firstInactiveIndex ] = interpolant;
  39396. lastActiveInterpolant.__cacheIndex = prevIndex;
  39397. interpolants[ prevIndex ] = lastActiveInterpolant;
  39398. }
  39399. /**
  39400. * Returns an instance of {@link AnimationAction} for the passed clip.
  39401. *
  39402. * If an action fitting the clip and root parameters doesn't yet exist, it
  39403. * will be created by this method. Calling this method several times with the
  39404. * same clip and root parameters always returns the same action.
  39405. *
  39406. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39407. * @param {Object3D} [optionalRoot] - An alternative root object.
  39408. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39409. * @return {?AnimationAction} The animation action.
  39410. */
  39411. clipAction( clip, optionalRoot, blendMode ) {
  39412. const root = optionalRoot || this._root,
  39413. rootUuid = root.uuid;
  39414. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39415. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39416. const actionsForClip = this._actionsByClip[ clipUuid ];
  39417. let prototypeAction = null;
  39418. if ( blendMode === undefined ) {
  39419. if ( clipObject !== null ) {
  39420. blendMode = clipObject.blendMode;
  39421. } else {
  39422. blendMode = NormalAnimationBlendMode;
  39423. }
  39424. }
  39425. if ( actionsForClip !== undefined ) {
  39426. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39427. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39428. return existingAction;
  39429. }
  39430. // we know the clip, so we don't have to parse all
  39431. // the bindings again but can just copy
  39432. prototypeAction = actionsForClip.knownActions[ 0 ];
  39433. // also, take the clip from the prototype action
  39434. if ( clipObject === null )
  39435. clipObject = prototypeAction._clip;
  39436. }
  39437. // clip must be known when specified via string
  39438. if ( clipObject === null ) return null;
  39439. // allocate all resources required to run it
  39440. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39441. this._bindAction( newAction, prototypeAction );
  39442. // and make the action known to the memory manager
  39443. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39444. return newAction;
  39445. }
  39446. /**
  39447. * Returns an existing animation action for the passed clip.
  39448. *
  39449. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39450. * @param {Object3D} [optionalRoot] - An alternative root object.
  39451. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39452. */
  39453. existingAction( clip, optionalRoot ) {
  39454. const root = optionalRoot || this._root,
  39455. rootUuid = root.uuid,
  39456. clipObject = typeof clip === 'string' ?
  39457. AnimationClip.findByName( root, clip ) : clip,
  39458. clipUuid = clipObject ? clipObject.uuid : clip,
  39459. actionsForClip = this._actionsByClip[ clipUuid ];
  39460. if ( actionsForClip !== undefined ) {
  39461. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39462. }
  39463. return null;
  39464. }
  39465. /**
  39466. * Deactivates all previously scheduled actions on this mixer.
  39467. *
  39468. * @return {AnimationMixer} A reference to this animation mixer.
  39469. */
  39470. stopAllAction() {
  39471. const actions = this._actions,
  39472. nActions = this._nActiveActions;
  39473. for ( let i = nActions - 1; i >= 0; -- i ) {
  39474. actions[ i ].stop();
  39475. }
  39476. return this;
  39477. }
  39478. /**
  39479. * Advances the global mixer time and updates the animation.
  39480. *
  39481. * This is usually done in the render loop by passing the delta
  39482. * time from {@link Clock} or {@link Timer}.
  39483. *
  39484. * @param {number} deltaTime - The delta time in seconds.
  39485. * @return {AnimationMixer} A reference to this animation mixer.
  39486. */
  39487. update( deltaTime ) {
  39488. deltaTime *= this.timeScale;
  39489. const actions = this._actions,
  39490. nActions = this._nActiveActions,
  39491. time = this.time += deltaTime,
  39492. timeDirection = Math.sign( deltaTime ),
  39493. accuIndex = this._accuIndex ^= 1;
  39494. // run active actions
  39495. for ( let i = 0; i !== nActions; ++ i ) {
  39496. const action = actions[ i ];
  39497. action._update( time, deltaTime, timeDirection, accuIndex );
  39498. }
  39499. // update scene graph
  39500. const bindings = this._bindings,
  39501. nBindings = this._nActiveBindings;
  39502. for ( let i = 0; i !== nBindings; ++ i ) {
  39503. bindings[ i ].apply( accuIndex );
  39504. }
  39505. return this;
  39506. }
  39507. /**
  39508. * Sets the global mixer to a specific time and updates the animation accordingly.
  39509. *
  39510. * This is useful when you need to jump to an exact time in an animation. The
  39511. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39512. *
  39513. * @param {number} time - The time to set in seconds.
  39514. * @return {AnimationMixer} A reference to this animation mixer.
  39515. */
  39516. setTime( time ) {
  39517. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39518. for ( let i = 0; i < this._actions.length; i ++ ) {
  39519. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39520. }
  39521. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39522. }
  39523. /**
  39524. * Returns this mixer's root object.
  39525. *
  39526. * @return {Object3D} The mixer's root object.
  39527. */
  39528. getRoot() {
  39529. return this._root;
  39530. }
  39531. /**
  39532. * Deallocates all memory resources for a clip. Before using this method make
  39533. * sure to call {@link AnimationAction#stop} for all related actions.
  39534. *
  39535. * @param {AnimationClip} clip - The clip to uncache.
  39536. */
  39537. uncacheClip( clip ) {
  39538. const actions = this._actions,
  39539. clipUuid = clip.uuid,
  39540. actionsByClip = this._actionsByClip,
  39541. actionsForClip = actionsByClip[ clipUuid ];
  39542. if ( actionsForClip !== undefined ) {
  39543. // note: just calling _removeInactiveAction would mess up the
  39544. // iteration state and also require updating the state we can
  39545. // just throw away
  39546. const actionsToRemove = actionsForClip.knownActions;
  39547. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39548. const action = actionsToRemove[ i ];
  39549. this._deactivateAction( action );
  39550. const cacheIndex = action._cacheIndex,
  39551. lastInactiveAction = actions[ actions.length - 1 ];
  39552. action._cacheIndex = null;
  39553. action._byClipCacheIndex = null;
  39554. lastInactiveAction._cacheIndex = cacheIndex;
  39555. actions[ cacheIndex ] = lastInactiveAction;
  39556. actions.pop();
  39557. this._removeInactiveBindingsForAction( action );
  39558. }
  39559. delete actionsByClip[ clipUuid ];
  39560. }
  39561. }
  39562. /**
  39563. * Deallocates all memory resources for a root object. Before using this
  39564. * method make sure to call {@link AnimationAction#stop} for all related
  39565. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39566. * mixer operates on a single root.
  39567. *
  39568. * @param {Object3D} root - The root object to uncache.
  39569. */
  39570. uncacheRoot( root ) {
  39571. const rootUuid = root.uuid,
  39572. actionsByClip = this._actionsByClip;
  39573. for ( const clipUuid in actionsByClip ) {
  39574. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39575. action = actionByRoot[ rootUuid ];
  39576. if ( action !== undefined ) {
  39577. this._deactivateAction( action );
  39578. this._removeInactiveAction( action );
  39579. }
  39580. }
  39581. const bindingsByRoot = this._bindingsByRootAndName,
  39582. bindingByName = bindingsByRoot[ rootUuid ];
  39583. if ( bindingByName !== undefined ) {
  39584. for ( const trackName in bindingByName ) {
  39585. const binding = bindingByName[ trackName ];
  39586. binding.restoreOriginalState();
  39587. this._removeInactiveBinding( binding );
  39588. }
  39589. }
  39590. }
  39591. /**
  39592. * Deallocates all memory resources for an action. The action is identified by the
  39593. * given clip and an optional root object. Before using this method make
  39594. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39595. *
  39596. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39597. * @param {Object3D} [optionalRoot] - An alternative root object.
  39598. */
  39599. uncacheAction( clip, optionalRoot ) {
  39600. const action = this.existingAction( clip, optionalRoot );
  39601. if ( action !== null ) {
  39602. this._deactivateAction( action );
  39603. this._removeInactiveAction( action );
  39604. }
  39605. }
  39606. }
  39607. /**
  39608. * Represents a 3D render target.
  39609. *
  39610. * @augments RenderTarget
  39611. */
  39612. class RenderTarget3D extends RenderTarget {
  39613. /**
  39614. * Constructs a new 3D render target.
  39615. *
  39616. * @param {number} [width=1] - The width of the render target.
  39617. * @param {number} [height=1] - The height of the render target.
  39618. * @param {number} [depth=1] - The height of the render target.
  39619. * @param {RenderTarget~Options} [options] - The configuration object.
  39620. */
  39621. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39622. super( width, height, options );
  39623. /**
  39624. * This flag can be used for type testing.
  39625. *
  39626. * @type {boolean}
  39627. * @readonly
  39628. * @default true
  39629. */
  39630. this.isRenderTarget3D = true;
  39631. this.depth = depth;
  39632. /**
  39633. * Overwritten with a different texture type.
  39634. *
  39635. * @type {Data3DTexture}
  39636. */
  39637. this.texture = new Data3DTexture( null, width, height, depth );
  39638. this._setTextureOptions( options );
  39639. this.texture.isRenderTargetTexture = true;
  39640. }
  39641. }
  39642. /**
  39643. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39644. *
  39645. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39646. * ```js
  39647. * uniforms: {
  39648. * time: { value: 1.0 },
  39649. * resolution: new Uniform( new Vector2() )
  39650. * };
  39651. * ```
  39652. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39653. * in {@link WebGLRenderer}.
  39654. */
  39655. class Uniform {
  39656. /**
  39657. * Constructs a new uniform.
  39658. *
  39659. * @param {any} value - The uniform value.
  39660. */
  39661. constructor( value ) {
  39662. /**
  39663. * The uniform value.
  39664. *
  39665. * @type {any}
  39666. */
  39667. this.value = value;
  39668. }
  39669. /**
  39670. * Returns a new uniform with copied values from this instance.
  39671. * If the value has a `clone()` method, the value is cloned as well.
  39672. *
  39673. * @return {Uniform} A clone of this instance.
  39674. */
  39675. clone() {
  39676. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39677. }
  39678. }
  39679. let _id = 0;
  39680. /**
  39681. * A class for managing multiple uniforms in a single group. The renderer will process
  39682. * such a definition as a single UBO.
  39683. *
  39684. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39685. * in {@link WebGLRenderer}.
  39686. *
  39687. * @augments EventDispatcher
  39688. */
  39689. class UniformsGroup extends EventDispatcher {
  39690. /**
  39691. * Constructs a new uniforms group.
  39692. */
  39693. constructor() {
  39694. super();
  39695. /**
  39696. * This flag can be used for type testing.
  39697. *
  39698. * @type {boolean}
  39699. * @readonly
  39700. * @default true
  39701. */
  39702. this.isUniformsGroup = true;
  39703. /**
  39704. * The ID of the 3D object.
  39705. *
  39706. * @name UniformsGroup#id
  39707. * @type {number}
  39708. * @readonly
  39709. */
  39710. Object.defineProperty( this, 'id', { value: _id ++ } );
  39711. /**
  39712. * The name of the uniforms group.
  39713. *
  39714. * @type {string}
  39715. */
  39716. this.name = '';
  39717. /**
  39718. * The buffer usage.
  39719. *
  39720. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39721. * @default StaticDrawUsage
  39722. */
  39723. this.usage = StaticDrawUsage;
  39724. /**
  39725. * An array holding the uniforms.
  39726. *
  39727. * @type {Array<Uniform>}
  39728. */
  39729. this.uniforms = [];
  39730. }
  39731. /**
  39732. * Adds the given uniform to this uniforms group.
  39733. *
  39734. * @param {Uniform} uniform - The uniform to add.
  39735. * @return {UniformsGroup} A reference to this uniforms group.
  39736. */
  39737. add( uniform ) {
  39738. this.uniforms.push( uniform );
  39739. return this;
  39740. }
  39741. /**
  39742. * Removes the given uniform from this uniforms group.
  39743. *
  39744. * @param {Uniform} uniform - The uniform to remove.
  39745. * @return {UniformsGroup} A reference to this uniforms group.
  39746. */
  39747. remove( uniform ) {
  39748. const index = this.uniforms.indexOf( uniform );
  39749. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39750. return this;
  39751. }
  39752. /**
  39753. * Sets the name of this uniforms group.
  39754. *
  39755. * @param {string} name - The name to set.
  39756. * @return {UniformsGroup} A reference to this uniforms group.
  39757. */
  39758. setName( name ) {
  39759. this.name = name;
  39760. return this;
  39761. }
  39762. /**
  39763. * Sets the usage of this uniforms group.
  39764. *
  39765. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39766. * @return {UniformsGroup} A reference to this uniforms group.
  39767. */
  39768. setUsage( value ) {
  39769. this.usage = value;
  39770. return this;
  39771. }
  39772. /**
  39773. * Frees the GPU-related resources allocated by this instance. Call this
  39774. * method whenever this instance is no longer used in your app.
  39775. *
  39776. * @fires Texture#dispose
  39777. */
  39778. dispose() {
  39779. this.dispatchEvent( { type: 'dispose' } );
  39780. }
  39781. /**
  39782. * Copies the values of the given uniforms group to this instance.
  39783. *
  39784. * @param {UniformsGroup} source - The uniforms group to copy.
  39785. * @return {UniformsGroup} A reference to this uniforms group.
  39786. */
  39787. copy( source ) {
  39788. this.name = source.name;
  39789. this.usage = source.usage;
  39790. const uniformsSource = source.uniforms;
  39791. this.uniforms.length = 0;
  39792. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39793. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39794. for ( let j = 0; j < uniforms.length; j ++ ) {
  39795. this.uniforms.push( uniforms[ j ].clone() );
  39796. }
  39797. }
  39798. return this;
  39799. }
  39800. /**
  39801. * Returns a new uniforms group with copied values from this instance.
  39802. *
  39803. * @return {UniformsGroup} A clone of this instance.
  39804. */
  39805. clone() {
  39806. return new this.constructor().copy( this );
  39807. }
  39808. }
  39809. /**
  39810. * An instanced version of an interleaved buffer.
  39811. *
  39812. * @augments InterleavedBuffer
  39813. */
  39814. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39815. /**
  39816. * Constructs a new instanced interleaved buffer.
  39817. *
  39818. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39819. * @param {number} stride - The number of typed-array elements per vertex.
  39820. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39821. */
  39822. constructor( array, stride, meshPerAttribute = 1 ) {
  39823. super( array, stride );
  39824. /**
  39825. * This flag can be used for type testing.
  39826. *
  39827. * @type {boolean}
  39828. * @readonly
  39829. * @default true
  39830. */
  39831. this.isInstancedInterleavedBuffer = true;
  39832. /**
  39833. * Defines how often a value of this buffer attribute should be repeated,
  39834. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39835. *
  39836. * @type {number}
  39837. * @default 1
  39838. */
  39839. this.meshPerAttribute = meshPerAttribute;
  39840. }
  39841. copy( source ) {
  39842. super.copy( source );
  39843. this.meshPerAttribute = source.meshPerAttribute;
  39844. return this;
  39845. }
  39846. clone( data ) {
  39847. const ib = super.clone( data );
  39848. ib.meshPerAttribute = this.meshPerAttribute;
  39849. return ib;
  39850. }
  39851. toJSON( data ) {
  39852. const json = super.toJSON( data );
  39853. json.isInstancedInterleavedBuffer = true;
  39854. json.meshPerAttribute = this.meshPerAttribute;
  39855. return json;
  39856. }
  39857. }
  39858. /**
  39859. * An alternative version of a buffer attribute with more control over the VBO.
  39860. *
  39861. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39862. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39863. *
  39864. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39865. * or even produces the VBOs in question.
  39866. *
  39867. * Notice that this class can only be used with {@link WebGLRenderer}.
  39868. */
  39869. class GLBufferAttribute {
  39870. /**
  39871. * Constructs a new GL buffer attribute.
  39872. *
  39873. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39874. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39875. * @param {number} itemSize - The item size.
  39876. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39877. * @param {number} count - The expected number of vertices in VBO.
  39878. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39879. */
  39880. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39881. /**
  39882. * This flag can be used for type testing.
  39883. *
  39884. * @type {boolean}
  39885. * @readonly
  39886. * @default true
  39887. */
  39888. this.isGLBufferAttribute = true;
  39889. /**
  39890. * The name of the buffer attribute.
  39891. *
  39892. * @type {string}
  39893. */
  39894. this.name = '';
  39895. /**
  39896. * The native WebGL buffer.
  39897. *
  39898. * @type {WebGLBuffer}
  39899. */
  39900. this.buffer = buffer;
  39901. /**
  39902. * The native data type.
  39903. *
  39904. * @type {number}
  39905. */
  39906. this.type = type;
  39907. /**
  39908. * The item size, see {@link BufferAttribute#itemSize}.
  39909. *
  39910. * @type {number}
  39911. */
  39912. this.itemSize = itemSize;
  39913. /**
  39914. * The corresponding size (in bytes) for the given `type` parameter.
  39915. *
  39916. * @type {number}
  39917. */
  39918. this.elementSize = elementSize;
  39919. /**
  39920. * The expected number of vertices in VBO.
  39921. *
  39922. * @type {number}
  39923. */
  39924. this.count = count;
  39925. /**
  39926. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39927. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39928. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39929. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39930. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39931. *
  39932. * @type {boolean}
  39933. */
  39934. this.normalized = normalized;
  39935. /**
  39936. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39937. *
  39938. * @type {number}
  39939. */
  39940. this.version = 0;
  39941. }
  39942. /**
  39943. * Flag to indicate that this attribute has changed and should be re-sent to
  39944. * the GPU. Set this to `true` when you modify the value of the array.
  39945. *
  39946. * @type {number}
  39947. * @default false
  39948. * @param {boolean} value
  39949. */
  39950. set needsUpdate( value ) {
  39951. if ( value === true ) this.version ++;
  39952. }
  39953. /**
  39954. * Sets the given native WebGL buffer.
  39955. *
  39956. * @param {WebGLBuffer} buffer - The buffer to set.
  39957. * @return {BufferAttribute} A reference to this instance.
  39958. */
  39959. setBuffer( buffer ) {
  39960. this.buffer = buffer;
  39961. return this;
  39962. }
  39963. /**
  39964. * Sets the given native data type and element size.
  39965. *
  39966. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39967. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39968. * @return {BufferAttribute} A reference to this instance.
  39969. */
  39970. setType( type, elementSize ) {
  39971. this.type = type;
  39972. this.elementSize = elementSize;
  39973. return this;
  39974. }
  39975. /**
  39976. * Sets the item size.
  39977. *
  39978. * @param {number} itemSize - The item size.
  39979. * @return {BufferAttribute} A reference to this instance.
  39980. */
  39981. setItemSize( itemSize ) {
  39982. this.itemSize = itemSize;
  39983. return this;
  39984. }
  39985. /**
  39986. * Sets the count (the expected number of vertices in VBO).
  39987. *
  39988. * @param {number} count - The count.
  39989. * @return {BufferAttribute} A reference to this instance.
  39990. */
  39991. setCount( count ) {
  39992. this.count = count;
  39993. return this;
  39994. }
  39995. }
  39996. const _matrix = /*@__PURE__*/ new Matrix4();
  39997. /**
  39998. * This class is designed to assist with raycasting. Raycasting is used for
  39999. * mouse picking (working out what objects in the 3d space the mouse is over)
  40000. * amongst other things.
  40001. */
  40002. class Raycaster {
  40003. /**
  40004. * Constructs a new raycaster.
  40005. *
  40006. * @param {Vector3} origin - The origin vector where the ray casts from.
  40007. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40008. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  40009. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  40010. */
  40011. constructor( origin, direction, near = 0, far = Infinity ) {
  40012. /**
  40013. * The ray used for raycasting.
  40014. *
  40015. * @type {Ray}
  40016. */
  40017. this.ray = new Ray( origin, direction );
  40018. /**
  40019. * All results returned are further away than near. Near can't be negative.
  40020. *
  40021. * @type {number}
  40022. * @default 0
  40023. */
  40024. this.near = near;
  40025. /**
  40026. * All results returned are closer than far. Far can't be lower than near.
  40027. *
  40028. * @type {number}
  40029. * @default Infinity
  40030. */
  40031. this.far = far;
  40032. /**
  40033. * The camera to use when raycasting against view-dependent objects such as
  40034. * billboarded objects like sprites. This field can be set manually or
  40035. * is set when calling `setFromCamera()`.
  40036. *
  40037. * @type {?Camera}
  40038. * @default null
  40039. */
  40040. this.camera = null;
  40041. /**
  40042. * Allows to selectively ignore 3D objects when performing intersection tests.
  40043. * The following code example ensures that only 3D objects on layer `1` will be
  40044. * honored by raycaster.
  40045. * ```js
  40046. * raycaster.layers.set( 1 );
  40047. * object.layers.enable( 1 );
  40048. * ```
  40049. *
  40050. * @type {Layers}
  40051. */
  40052. this.layers = new Layers();
  40053. /**
  40054. * A parameter object that configures the raycasting. It has the structure:
  40055. *
  40056. * ```
  40057. * {
  40058. * Mesh: {},
  40059. * Line: { threshold: 1 },
  40060. * LOD: {},
  40061. * Points: { threshold: 1 },
  40062. * Sprite: {}
  40063. * }
  40064. * ```
  40065. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  40066. *
  40067. * @type {Object}
  40068. */
  40069. this.params = {
  40070. Mesh: {},
  40071. Line: { threshold: 1 },
  40072. LOD: {},
  40073. Points: { threshold: 1 },
  40074. Sprite: {}
  40075. };
  40076. }
  40077. /**
  40078. * Updates the ray with a new origin and direction by copying the values from the arguments.
  40079. *
  40080. * @param {Vector3} origin - The origin vector where the ray casts from.
  40081. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40082. */
  40083. set( origin, direction ) {
  40084. // direction is assumed to be normalized (for accurate distance calculations)
  40085. this.ray.set( origin, direction );
  40086. }
  40087. /**
  40088. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  40089. *
  40090. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  40091. * X and Y components should be between `-1` and `1`.
  40092. * @param {Camera} camera - The camera from which the ray should originate.
  40093. */
  40094. setFromCamera( coords, camera ) {
  40095. if ( camera.isPerspectiveCamera ) {
  40096. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  40097. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  40098. this.camera = camera;
  40099. } else if ( camera.isOrthographicCamera ) {
  40100. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  40101. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  40102. this.camera = camera;
  40103. } else {
  40104. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  40105. }
  40106. }
  40107. /**
  40108. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  40109. *
  40110. * @param {WebXRController} controller - The controller to copy the position and direction from.
  40111. * @return {Raycaster} A reference to this raycaster.
  40112. */
  40113. setFromXRController( controller ) {
  40114. _matrix.identity().extractRotation( controller.matrixWorld );
  40115. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  40116. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  40117. return this;
  40118. }
  40119. /**
  40120. * The intersection point of a raycaster intersection test.
  40121. * @typedef {Object} Raycaster~Intersection
  40122. * @property {number} distance - The distance from the ray's origin to the intersection point.
  40123. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  40124. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  40125. * @property {Vector3} point - The intersection point, in world coordinates.
  40126. * @property {Object} face - The face that has been intersected.
  40127. * @property {number} faceIndex - The face index.
  40128. * @property {Object3D} object - The 3D object that has been intersected.
  40129. * @property {Vector2} uv - U,V coordinates at point of intersection.
  40130. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  40131. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  40132. * @property {number} instanceId - The index number of the instance where the ray
  40133. * intersects the {@link InstancedMesh}.
  40134. */
  40135. /**
  40136. * Checks all intersection between the ray and the object with or without the
  40137. * descendants. Intersections are returned sorted by distance, closest first.
  40138. *
  40139. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  40140. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  40141. * differently to ray casting than lines or points.
  40142. *
  40143. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  40144. * to be detected; intersections of the ray passing through the back of a face will not
  40145. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  40146. * to `THREE.DoubleSide`.
  40147. *
  40148. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  40149. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40150. * Otherwise it only checks intersection with the object.
  40151. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40152. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40153. */
  40154. intersectObject( object, recursive = true, intersects = [] ) {
  40155. intersect( object, this, intersects, recursive );
  40156. intersects.sort( ascSort );
  40157. return intersects;
  40158. }
  40159. /**
  40160. * Checks all intersection between the ray and the objects with or without
  40161. * the descendants. Intersections are returned sorted by distance, closest first.
  40162. *
  40163. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  40164. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40165. * Otherwise it only checks intersection with the object.
  40166. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40167. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40168. */
  40169. intersectObjects( objects, recursive = true, intersects = [] ) {
  40170. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  40171. intersect( objects[ i ], this, intersects, recursive );
  40172. }
  40173. intersects.sort( ascSort );
  40174. return intersects;
  40175. }
  40176. }
  40177. function ascSort( a, b ) {
  40178. return a.distance - b.distance;
  40179. }
  40180. function intersect( object, raycaster, intersects, recursive ) {
  40181. let propagate = true;
  40182. if ( object.layers.test( raycaster.layers ) ) {
  40183. const result = object.raycast( raycaster, intersects );
  40184. if ( result === false ) propagate = false;
  40185. }
  40186. if ( propagate === true && recursive === true ) {
  40187. const children = object.children;
  40188. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40189. intersect( children[ i ], raycaster, intersects, true );
  40190. }
  40191. }
  40192. }
  40193. /**
  40194. * This class is an alternative to {@link Clock} with a different API design and behavior.
  40195. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  40196. *
  40197. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  40198. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  40199. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  40200. * is inactive (e.g. tab switched or browser hidden).
  40201. *
  40202. * ```js
  40203. * const timer = new Timer();
  40204. * timer.connect( document ); // use Page Visibility API
  40205. * ```
  40206. */
  40207. class Timer {
  40208. /**
  40209. * Constructs a new timer.
  40210. */
  40211. constructor() {
  40212. this._previousTime = 0;
  40213. this._currentTime = 0;
  40214. this._startTime = performance.now();
  40215. this._delta = 0;
  40216. this._elapsed = 0;
  40217. this._timescale = 1;
  40218. this._document = null;
  40219. this._pageVisibilityHandler = null;
  40220. }
  40221. /**
  40222. * Connect the timer to the given document.Calling this method is not mandatory to
  40223. * use the timer but enables the usage of the Page Visibility API to avoid large time
  40224. * delta values.
  40225. *
  40226. * @param {Document} document - The document.
  40227. */
  40228. connect( document ) {
  40229. this._document = document;
  40230. // use Page Visibility API to avoid large time delta values
  40231. if ( document.hidden !== undefined ) {
  40232. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  40233. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  40234. }
  40235. }
  40236. /**
  40237. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  40238. */
  40239. disconnect() {
  40240. if ( this._pageVisibilityHandler !== null ) {
  40241. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  40242. this._pageVisibilityHandler = null;
  40243. }
  40244. this._document = null;
  40245. }
  40246. /**
  40247. * Returns the time delta in seconds.
  40248. *
  40249. * @return {number} The time delta in second.
  40250. */
  40251. getDelta() {
  40252. return this._delta / 1000;
  40253. }
  40254. /**
  40255. * Returns the elapsed time in seconds.
  40256. *
  40257. * @return {number} The elapsed time in second.
  40258. */
  40259. getElapsed() {
  40260. return this._elapsed / 1000;
  40261. }
  40262. /**
  40263. * Returns the timescale.
  40264. *
  40265. * @return {number} The timescale.
  40266. */
  40267. getTimescale() {
  40268. return this._timescale;
  40269. }
  40270. /**
  40271. * Sets the given timescale which scale the time delta computation
  40272. * in `update()`.
  40273. *
  40274. * @param {number} timescale - The timescale to set.
  40275. * @return {Timer} A reference to this timer.
  40276. */
  40277. setTimescale( timescale ) {
  40278. this._timescale = timescale;
  40279. return this;
  40280. }
  40281. /**
  40282. * Resets the time computation for the current simulation step.
  40283. *
  40284. * @return {Timer} A reference to this timer.
  40285. */
  40286. reset() {
  40287. this._currentTime = performance.now() - this._startTime;
  40288. return this;
  40289. }
  40290. /**
  40291. * Can be used to free all internal resources. Usually called when
  40292. * the timer instance isn't required anymore.
  40293. */
  40294. dispose() {
  40295. this.disconnect();
  40296. }
  40297. /**
  40298. * Updates the internal state of the timer. This method should be called
  40299. * once per simulation step and before you perform queries against the timer
  40300. * (e.g. via `getDelta()`).
  40301. *
  40302. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  40303. * from the `requestAnimationFrame` callback argument. If not provided, the current
  40304. * time will be determined with `performance.now`.
  40305. * @return {Timer} A reference to this timer.
  40306. */
  40307. update( timestamp ) {
  40308. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  40309. this._delta = 0;
  40310. } else {
  40311. this._previousTime = this._currentTime;
  40312. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  40313. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  40314. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  40315. }
  40316. return this;
  40317. }
  40318. }
  40319. function handleVisibilityChange() {
  40320. if ( this._document.hidden === false ) this.reset();
  40321. }
  40322. /**
  40323. * This class can be used to represent points in 3D space as
  40324. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40325. */
  40326. class Spherical {
  40327. /**
  40328. * Constructs a new spherical.
  40329. *
  40330. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40331. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40332. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40333. */
  40334. constructor( radius = 1, phi = 0, theta = 0 ) {
  40335. /**
  40336. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40337. *
  40338. * @type {number}
  40339. * @default 1
  40340. */
  40341. this.radius = radius;
  40342. /**
  40343. * The polar angle in radians from the y (up) axis.
  40344. *
  40345. * @type {number}
  40346. * @default 0
  40347. */
  40348. this.phi = phi;
  40349. /**
  40350. * The equator/azimuthal angle in radians around the y (up) axis.
  40351. *
  40352. * @type {number}
  40353. * @default 0
  40354. */
  40355. this.theta = theta;
  40356. }
  40357. /**
  40358. * Sets the spherical components by copying the given values.
  40359. *
  40360. * @param {number} radius - The radius.
  40361. * @param {number} phi - The polar angle.
  40362. * @param {number} theta - The azimuthal angle.
  40363. * @return {Spherical} A reference to this spherical.
  40364. */
  40365. set( radius, phi, theta ) {
  40366. this.radius = radius;
  40367. this.phi = phi;
  40368. this.theta = theta;
  40369. return this;
  40370. }
  40371. /**
  40372. * Copies the values of the given spherical to this instance.
  40373. *
  40374. * @param {Spherical} other - The spherical to copy.
  40375. * @return {Spherical} A reference to this spherical.
  40376. */
  40377. copy( other ) {
  40378. this.radius = other.radius;
  40379. this.phi = other.phi;
  40380. this.theta = other.theta;
  40381. return this;
  40382. }
  40383. /**
  40384. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40385. * `0.000001`.
  40386. *
  40387. * @return {Spherical} A reference to this spherical.
  40388. */
  40389. makeSafe() {
  40390. const EPS = 0.000001;
  40391. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40392. return this;
  40393. }
  40394. /**
  40395. * Sets the spherical components from the given vector which is assumed to hold
  40396. * Cartesian coordinates.
  40397. *
  40398. * @param {Vector3} v - The vector to set.
  40399. * @return {Spherical} A reference to this spherical.
  40400. */
  40401. setFromVector3( v ) {
  40402. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40403. }
  40404. /**
  40405. * Sets the spherical components from the given Cartesian coordinates.
  40406. *
  40407. * @param {number} x - The x value.
  40408. * @param {number} y - The y value.
  40409. * @param {number} z - The z value.
  40410. * @return {Spherical} A reference to this spherical.
  40411. */
  40412. setFromCartesianCoords( x, y, z ) {
  40413. this.radius = Math.sqrt( x * x + y * y + z * z );
  40414. if ( this.radius === 0 ) {
  40415. this.theta = 0;
  40416. this.phi = 0;
  40417. } else {
  40418. this.theta = Math.atan2( x, z );
  40419. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40420. }
  40421. return this;
  40422. }
  40423. /**
  40424. * Returns a new spherical with copied values from this instance.
  40425. *
  40426. * @return {Spherical} A clone of this instance.
  40427. */
  40428. clone() {
  40429. return new this.constructor().copy( this );
  40430. }
  40431. }
  40432. /**
  40433. * This class can be used to represent points in 3D space as
  40434. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40435. */
  40436. class Cylindrical {
  40437. /**
  40438. * Constructs a new cylindrical.
  40439. *
  40440. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40441. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40442. * @param {number} [y=0] - The height above the x-z plane.
  40443. */
  40444. constructor( radius = 1, theta = 0, y = 0 ) {
  40445. /**
  40446. * The distance from the origin to a point in the x-z plane.
  40447. *
  40448. * @type {number}
  40449. * @default 1
  40450. */
  40451. this.radius = radius;
  40452. /**
  40453. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40454. *
  40455. * @type {number}
  40456. * @default 0
  40457. */
  40458. this.theta = theta;
  40459. /**
  40460. * The height above the x-z plane.
  40461. *
  40462. * @type {number}
  40463. * @default 0
  40464. */
  40465. this.y = y;
  40466. }
  40467. /**
  40468. * Sets the cylindrical components by copying the given values.
  40469. *
  40470. * @param {number} radius - The radius.
  40471. * @param {number} theta - The theta angle.
  40472. * @param {number} y - The height value.
  40473. * @return {Cylindrical} A reference to this cylindrical.
  40474. */
  40475. set( radius, theta, y ) {
  40476. this.radius = radius;
  40477. this.theta = theta;
  40478. this.y = y;
  40479. return this;
  40480. }
  40481. /**
  40482. * Copies the values of the given cylindrical to this instance.
  40483. *
  40484. * @param {Cylindrical} other - The cylindrical to copy.
  40485. * @return {Cylindrical} A reference to this cylindrical.
  40486. */
  40487. copy( other ) {
  40488. this.radius = other.radius;
  40489. this.theta = other.theta;
  40490. this.y = other.y;
  40491. return this;
  40492. }
  40493. /**
  40494. * Sets the cylindrical components from the given vector which is assumed to hold
  40495. * Cartesian coordinates.
  40496. *
  40497. * @param {Vector3} v - The vector to set.
  40498. * @return {Cylindrical} A reference to this cylindrical.
  40499. */
  40500. setFromVector3( v ) {
  40501. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40502. }
  40503. /**
  40504. * Sets the cylindrical components from the given Cartesian coordinates.
  40505. *
  40506. * @param {number} x - The x value.
  40507. * @param {number} y - The x value.
  40508. * @param {number} z - The x value.
  40509. * @return {Cylindrical} A reference to this cylindrical.
  40510. */
  40511. setFromCartesianCoords( x, y, z ) {
  40512. this.radius = Math.sqrt( x * x + z * z );
  40513. this.theta = Math.atan2( x, z );
  40514. this.y = y;
  40515. return this;
  40516. }
  40517. /**
  40518. * Returns a new cylindrical with copied values from this instance.
  40519. *
  40520. * @return {Cylindrical} A clone of this instance.
  40521. */
  40522. clone() {
  40523. return new this.constructor().copy( this );
  40524. }
  40525. }
  40526. /**
  40527. * Represents a 2x2 matrix.
  40528. *
  40529. * A Note on Row-Major and Column-Major Ordering:
  40530. *
  40531. * The constructor and {@link Matrix2#set} method take arguments in
  40532. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40533. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40534. * This means that calling:
  40535. * ```js
  40536. * const m = new THREE.Matrix2();
  40537. * m.set( 11, 12,
  40538. * 21, 22 );
  40539. * ```
  40540. * will result in the elements array containing:
  40541. * ```js
  40542. * m.elements = [ 11, 21,
  40543. * 12, 22 ];
  40544. * ```
  40545. * and internally all calculations are performed using column-major ordering.
  40546. * However, as the actual ordering makes no difference mathematically and
  40547. * most people are used to thinking about matrices in row-major order, the
  40548. * three.js documentation shows matrices in row-major order. Just bear in
  40549. * mind that if you are reading the source code, you'll have to take the
  40550. * transpose of any matrices outlined here to make sense of the calculations.
  40551. */
  40552. class Matrix2 {
  40553. /**
  40554. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40555. * in row-major order. If no arguments are provided, the constructor
  40556. * initializes the matrix as an identity matrix.
  40557. *
  40558. * @param {number} [n11] - 1-1 matrix element.
  40559. * @param {number} [n12] - 1-2 matrix element.
  40560. * @param {number} [n21] - 2-1 matrix element.
  40561. * @param {number} [n22] - 2-2 matrix element.
  40562. */
  40563. constructor( n11, n12, n21, n22 ) {
  40564. /**
  40565. * This flag can be used for type testing.
  40566. *
  40567. * @type {boolean}
  40568. * @readonly
  40569. * @default true
  40570. */
  40571. Matrix2.prototype.isMatrix2 = true;
  40572. /**
  40573. * A column-major list of matrix values.
  40574. *
  40575. * @type {Array<number>}
  40576. */
  40577. this.elements = [
  40578. 1, 0,
  40579. 0, 1,
  40580. ];
  40581. if ( n11 !== undefined ) {
  40582. this.set( n11, n12, n21, n22 );
  40583. }
  40584. }
  40585. /**
  40586. * Sets this matrix to the 2x2 identity matrix.
  40587. *
  40588. * @return {Matrix2} A reference to this matrix.
  40589. */
  40590. identity() {
  40591. this.set(
  40592. 1, 0,
  40593. 0, 1,
  40594. );
  40595. return this;
  40596. }
  40597. /**
  40598. * Sets the elements of the matrix from the given array.
  40599. *
  40600. * @param {Array<number>} array - The matrix elements in column-major order.
  40601. * @param {number} [offset=0] - Index of the first element in the array.
  40602. * @return {Matrix2} A reference to this matrix.
  40603. */
  40604. fromArray( array, offset = 0 ) {
  40605. for ( let i = 0; i < 4; i ++ ) {
  40606. this.elements[ i ] = array[ i + offset ];
  40607. }
  40608. return this;
  40609. }
  40610. /**
  40611. * Sets the elements of the matrix.The arguments are supposed to be
  40612. * in row-major order.
  40613. *
  40614. * @param {number} n11 - 1-1 matrix element.
  40615. * @param {number} n12 - 1-2 matrix element.
  40616. * @param {number} n21 - 2-1 matrix element.
  40617. * @param {number} n22 - 2-2 matrix element.
  40618. * @return {Matrix2} A reference to this matrix.
  40619. */
  40620. set( n11, n12, n21, n22 ) {
  40621. const te = this.elements;
  40622. te[ 0 ] = n11; te[ 2 ] = n12;
  40623. te[ 1 ] = n21; te[ 3 ] = n22;
  40624. return this;
  40625. }
  40626. }
  40627. const _vector$4 = /*@__PURE__*/ new Vector2();
  40628. /**
  40629. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40630. */
  40631. class Box2 {
  40632. /**
  40633. * Constructs a new bounding box.
  40634. *
  40635. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40636. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40637. */
  40638. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40639. /**
  40640. * This flag can be used for type testing.
  40641. *
  40642. * @type {boolean}
  40643. * @readonly
  40644. * @default true
  40645. */
  40646. this.isBox2 = true;
  40647. /**
  40648. * The lower boundary of the box.
  40649. *
  40650. * @type {Vector2}
  40651. */
  40652. this.min = min;
  40653. /**
  40654. * The upper boundary of the box.
  40655. *
  40656. * @type {Vector2}
  40657. */
  40658. this.max = max;
  40659. }
  40660. /**
  40661. * Sets the lower and upper boundaries of this box.
  40662. * Please note that this method only copies the values from the given objects.
  40663. *
  40664. * @param {Vector2} min - The lower boundary of the box.
  40665. * @param {Vector2} max - The upper boundary of the box.
  40666. * @return {Box2} A reference to this bounding box.
  40667. */
  40668. set( min, max ) {
  40669. this.min.copy( min );
  40670. this.max.copy( max );
  40671. return this;
  40672. }
  40673. /**
  40674. * Sets the upper and lower bounds of this box so it encloses the position data
  40675. * in the given array.
  40676. *
  40677. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40678. * @return {Box2} A reference to this bounding box.
  40679. */
  40680. setFromPoints( points ) {
  40681. this.makeEmpty();
  40682. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40683. this.expandByPoint( points[ i ] );
  40684. }
  40685. return this;
  40686. }
  40687. /**
  40688. * Centers this box on the given center vector and sets this box's width, height and
  40689. * depth to the given size values.
  40690. *
  40691. * @param {Vector2} center - The center of the box.
  40692. * @param {Vector2} size - The x and y dimensions of the box.
  40693. * @return {Box2} A reference to this bounding box.
  40694. */
  40695. setFromCenterAndSize( center, size ) {
  40696. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40697. this.min.copy( center ).sub( halfSize );
  40698. this.max.copy( center ).add( halfSize );
  40699. return this;
  40700. }
  40701. /**
  40702. * Returns a new box with copied values from this instance.
  40703. *
  40704. * @return {Box2} A clone of this instance.
  40705. */
  40706. clone() {
  40707. return new this.constructor().copy( this );
  40708. }
  40709. /**
  40710. * Copies the values of the given box to this instance.
  40711. *
  40712. * @param {Box2} box - The box to copy.
  40713. * @return {Box2} A reference to this bounding box.
  40714. */
  40715. copy( box ) {
  40716. this.min.copy( box.min );
  40717. this.max.copy( box.max );
  40718. return this;
  40719. }
  40720. /**
  40721. * Makes this box empty which means in encloses a zero space in 2D.
  40722. *
  40723. * @return {Box2} A reference to this bounding box.
  40724. */
  40725. makeEmpty() {
  40726. this.min.x = this.min.y = + Infinity;
  40727. this.max.x = this.max.y = - Infinity;
  40728. return this;
  40729. }
  40730. /**
  40731. * Returns true if this box includes zero points within its bounds.
  40732. * Note that a box with equal lower and upper bounds still includes one
  40733. * point, the one both bounds share.
  40734. *
  40735. * @return {boolean} Whether this box is empty or not.
  40736. */
  40737. isEmpty() {
  40738. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40739. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40740. }
  40741. /**
  40742. * Returns the center point of this box.
  40743. *
  40744. * @param {Vector2} target - The target vector that is used to store the method's result.
  40745. * @return {Vector2} The center point.
  40746. */
  40747. getCenter( target ) {
  40748. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40749. }
  40750. /**
  40751. * Returns the dimensions of this box.
  40752. *
  40753. * @param {Vector2} target - The target vector that is used to store the method's result.
  40754. * @return {Vector2} The size.
  40755. */
  40756. getSize( target ) {
  40757. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40758. }
  40759. /**
  40760. * Expands the boundaries of this box to include the given point.
  40761. *
  40762. * @param {Vector2} point - The point that should be included by the bounding box.
  40763. * @return {Box2} A reference to this bounding box.
  40764. */
  40765. expandByPoint( point ) {
  40766. this.min.min( point );
  40767. this.max.max( point );
  40768. return this;
  40769. }
  40770. /**
  40771. * Expands this box equilaterally by the given vector. The width of this
  40772. * box will be expanded by the x component of the vector in both
  40773. * directions. The height of this box will be expanded by the y component of
  40774. * the vector in both directions.
  40775. *
  40776. * @param {Vector2} vector - The vector that should expand the bounding box.
  40777. * @return {Box2} A reference to this bounding box.
  40778. */
  40779. expandByVector( vector ) {
  40780. this.min.sub( vector );
  40781. this.max.add( vector );
  40782. return this;
  40783. }
  40784. /**
  40785. * Expands each dimension of the box by the given scalar. If negative, the
  40786. * dimensions of the box will be contracted.
  40787. *
  40788. * @param {number} scalar - The scalar value that should expand the bounding box.
  40789. * @return {Box2} A reference to this bounding box.
  40790. */
  40791. expandByScalar( scalar ) {
  40792. this.min.addScalar( - scalar );
  40793. this.max.addScalar( scalar );
  40794. return this;
  40795. }
  40796. /**
  40797. * Returns `true` if the given point lies within or on the boundaries of this box.
  40798. *
  40799. * @param {Vector2} point - The point to test.
  40800. * @return {boolean} Whether the bounding box contains the given point or not.
  40801. */
  40802. containsPoint( point ) {
  40803. return point.x >= this.min.x && point.x <= this.max.x &&
  40804. point.y >= this.min.y && point.y <= this.max.y;
  40805. }
  40806. /**
  40807. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40808. * If this box and the given one are identical, this function also returns `true`.
  40809. *
  40810. * @param {Box2} box - The bounding box to test.
  40811. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40812. */
  40813. containsBox( box ) {
  40814. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40815. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40816. }
  40817. /**
  40818. * Returns a point as a proportion of this box's width and height.
  40819. *
  40820. * @param {Vector2} point - A point in 2D space.
  40821. * @param {Vector2} target - The target vector that is used to store the method's result.
  40822. * @return {Vector2} A point as a proportion of this box's width and height.
  40823. */
  40824. getParameter( point, target ) {
  40825. // This can potentially have a divide by zero if the box
  40826. // has a size dimension of 0.
  40827. return target.set(
  40828. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40829. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40830. );
  40831. }
  40832. /**
  40833. * Returns `true` if the given bounding box intersects with this bounding box.
  40834. *
  40835. * @param {Box2} box - The bounding box to test.
  40836. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40837. */
  40838. intersectsBox( box ) {
  40839. // using 4 splitting planes to rule out intersections
  40840. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40841. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40842. }
  40843. /**
  40844. * Clamps the given point within the bounds of this box.
  40845. *
  40846. * @param {Vector2} point - The point to clamp.
  40847. * @param {Vector2} target - The target vector that is used to store the method's result.
  40848. * @return {Vector2} The clamped point.
  40849. */
  40850. clampPoint( point, target ) {
  40851. return target.copy( point ).clamp( this.min, this.max );
  40852. }
  40853. /**
  40854. * Returns the euclidean distance from any edge of this box to the specified point. If
  40855. * the given point lies inside of this box, the distance will be `0`.
  40856. *
  40857. * @param {Vector2} point - The point to compute the distance to.
  40858. * @return {number} The euclidean distance.
  40859. */
  40860. distanceToPoint( point ) {
  40861. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40862. }
  40863. /**
  40864. * Computes the intersection of this bounding box and the given one, setting the upper
  40865. * bound of this box to the lesser of the two boxes' upper bounds and the
  40866. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40867. * there's no overlap, makes this box empty.
  40868. *
  40869. * @param {Box2} box - The bounding box to intersect with.
  40870. * @return {Box2} A reference to this bounding box.
  40871. */
  40872. intersect( box ) {
  40873. this.min.max( box.min );
  40874. this.max.min( box.max );
  40875. if ( this.isEmpty() ) this.makeEmpty();
  40876. return this;
  40877. }
  40878. /**
  40879. * Computes the union of this box and another and the given one, setting the upper
  40880. * bound of this box to the greater of the two boxes' upper bounds and the
  40881. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40882. *
  40883. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40884. * @return {Box2} A reference to this bounding box.
  40885. */
  40886. union( box ) {
  40887. this.min.min( box.min );
  40888. this.max.max( box.max );
  40889. return this;
  40890. }
  40891. /**
  40892. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40893. * effectively moving it in 2D space.
  40894. *
  40895. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40896. * @return {Box2} A reference to this bounding box.
  40897. */
  40898. translate( offset ) {
  40899. this.min.add( offset );
  40900. this.max.add( offset );
  40901. return this;
  40902. }
  40903. /**
  40904. * Returns `true` if this bounding box is equal with the given one.
  40905. *
  40906. * @param {Box2} box - The box to test for equality.
  40907. * @return {boolean} Whether this bounding box is equal with the given one.
  40908. */
  40909. equals( box ) {
  40910. return box.min.equals( this.min ) && box.max.equals( this.max );
  40911. }
  40912. }
  40913. const _startP = /*@__PURE__*/ new Vector3();
  40914. const _startEnd = /*@__PURE__*/ new Vector3();
  40915. const _d1 = /*@__PURE__*/ new Vector3();
  40916. const _d2 = /*@__PURE__*/ new Vector3();
  40917. const _r = /*@__PURE__*/ new Vector3();
  40918. const _c1 = /*@__PURE__*/ new Vector3();
  40919. const _c2 = /*@__PURE__*/ new Vector3();
  40920. /**
  40921. * An analytical line segment in 3D space represented by a start and end point.
  40922. */
  40923. class Line3 {
  40924. /**
  40925. * Constructs a new line segment.
  40926. *
  40927. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40928. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40929. */
  40930. constructor( start = new Vector3(), end = new Vector3() ) {
  40931. /**
  40932. * Start of the line segment.
  40933. *
  40934. * @type {Vector3}
  40935. */
  40936. this.start = start;
  40937. /**
  40938. * End of the line segment.
  40939. *
  40940. * @type {Vector3}
  40941. */
  40942. this.end = end;
  40943. }
  40944. /**
  40945. * Sets the start and end values by copying the given vectors.
  40946. *
  40947. * @param {Vector3} start - The start point.
  40948. * @param {Vector3} end - The end point.
  40949. * @return {Line3} A reference to this line segment.
  40950. */
  40951. set( start, end ) {
  40952. this.start.copy( start );
  40953. this.end.copy( end );
  40954. return this;
  40955. }
  40956. /**
  40957. * Copies the values of the given line segment to this instance.
  40958. *
  40959. * @param {Line3} line - The line segment to copy.
  40960. * @return {Line3} A reference to this line segment.
  40961. */
  40962. copy( line ) {
  40963. this.start.copy( line.start );
  40964. this.end.copy( line.end );
  40965. return this;
  40966. }
  40967. /**
  40968. * Returns the center of the line segment.
  40969. *
  40970. * @param {Vector3} target - The target vector that is used to store the method's result.
  40971. * @return {Vector3} The center point.
  40972. */
  40973. getCenter( target ) {
  40974. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40975. }
  40976. /**
  40977. * Returns the delta vector of the line segment's start and end point.
  40978. *
  40979. * @param {Vector3} target - The target vector that is used to store the method's result.
  40980. * @return {Vector3} The delta vector.
  40981. */
  40982. delta( target ) {
  40983. return target.subVectors( this.end, this.start );
  40984. }
  40985. /**
  40986. * Returns the squared Euclidean distance between the line' start and end point.
  40987. *
  40988. * @return {number} The squared Euclidean distance.
  40989. */
  40990. distanceSq() {
  40991. return this.start.distanceToSquared( this.end );
  40992. }
  40993. /**
  40994. * Returns the Euclidean distance between the line' start and end point.
  40995. *
  40996. * @return {number} The Euclidean distance.
  40997. */
  40998. distance() {
  40999. return this.start.distanceTo( this.end );
  41000. }
  41001. /**
  41002. * Returns a vector at a certain position along the line segment.
  41003. *
  41004. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  41005. * @param {Vector3} target - The target vector that is used to store the method's result.
  41006. * @return {Vector3} The delta vector.
  41007. */
  41008. at( t, target ) {
  41009. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41010. }
  41011. /**
  41012. * Returns a point parameter based on the closest point as projected on the line segment.
  41013. *
  41014. * @param {Vector3} point - The point for which to return a point parameter.
  41015. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41016. * @return {number} The point parameter.
  41017. */
  41018. closestPointToPointParameter( point, clampToLine ) {
  41019. _startP.subVectors( point, this.start );
  41020. _startEnd.subVectors( this.end, this.start );
  41021. const startEnd2 = _startEnd.dot( _startEnd );
  41022. const startEnd_startP = _startEnd.dot( _startP );
  41023. let t = startEnd_startP / startEnd2;
  41024. if ( clampToLine ) {
  41025. t = clamp( t, 0, 1 );
  41026. }
  41027. return t;
  41028. }
  41029. /**
  41030. * Returns the closest point on the line for a given point.
  41031. *
  41032. * @param {Vector3} point - The point to compute the closest point on the line for.
  41033. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41034. * @param {Vector3} target - The target vector that is used to store the method's result.
  41035. * @return {Vector3} The closest point on the line.
  41036. */
  41037. closestPointToPoint( point, clampToLine, target ) {
  41038. const t = this.closestPointToPointParameter( point, clampToLine );
  41039. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41040. }
  41041. /**
  41042. * Returns the closest squared distance between this line segment and the given one.
  41043. *
  41044. * @param {Line3} line - The line segment to compute the closest squared distance to.
  41045. * @param {Vector3} [c1] - The closest point on this line segment.
  41046. * @param {Vector3} [c2] - The closest point on the given line segment.
  41047. * @return {number} The squared distance between this line segment and the given one.
  41048. */
  41049. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  41050. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  41051. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  41052. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  41053. // distance between between S1(s) and S2(t)
  41054. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  41055. let s, t;
  41056. const p1 = this.start;
  41057. const p2 = line.start;
  41058. const q1 = this.end;
  41059. const q2 = line.end;
  41060. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  41061. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  41062. _r.subVectors( p1, p2 );
  41063. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  41064. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  41065. const f = _d2.dot( _r );
  41066. // Check if either or both segments degenerate into points
  41067. if ( a <= EPSILON && e <= EPSILON ) {
  41068. // Both segments degenerate into points
  41069. c1.copy( p1 );
  41070. c2.copy( p2 );
  41071. c1.sub( c2 );
  41072. return c1.dot( c1 );
  41073. }
  41074. if ( a <= EPSILON ) {
  41075. // First segment degenerates into a point
  41076. s = 0;
  41077. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  41078. t = clamp( t, 0, 1 );
  41079. } else {
  41080. const c = _d1.dot( _r );
  41081. if ( e <= EPSILON ) {
  41082. // Second segment degenerates into a point
  41083. t = 0;
  41084. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  41085. } else {
  41086. // The general nondegenerate case starts here
  41087. const b = _d1.dot( _d2 );
  41088. const denom = a * e - b * b; // Always nonnegative
  41089. // If segments not parallel, compute closest point on L1 to L2 and
  41090. // clamp to segment S1. Else pick arbitrary s (here 0)
  41091. if ( denom !== 0 ) {
  41092. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  41093. } else {
  41094. s = 0;
  41095. }
  41096. // Compute point on L2 closest to S1(s) using
  41097. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  41098. t = ( b * s + f ) / e;
  41099. // If t in [0,1] done. Else clamp t, recompute s for the new value
  41100. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  41101. // and clamp s to [0, 1]
  41102. if ( t < 0 ) {
  41103. t = 0.;
  41104. s = clamp( - c / a, 0, 1 );
  41105. } else if ( t > 1 ) {
  41106. t = 1;
  41107. s = clamp( ( b - c ) / a, 0, 1 );
  41108. }
  41109. }
  41110. }
  41111. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  41112. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  41113. c1.sub( c2 );
  41114. return c1.dot( c1 );
  41115. }
  41116. /**
  41117. * Applies a 4x4 transformation matrix to this line segment.
  41118. *
  41119. * @param {Matrix4} matrix - The transformation matrix.
  41120. * @return {Line3} A reference to this line segment.
  41121. */
  41122. applyMatrix4( matrix ) {
  41123. this.start.applyMatrix4( matrix );
  41124. this.end.applyMatrix4( matrix );
  41125. return this;
  41126. }
  41127. /**
  41128. * Returns `true` if this line segment is equal with the given one.
  41129. *
  41130. * @param {Line3} line - The line segment to test for equality.
  41131. * @return {boolean} Whether this line segment is equal with the given one.
  41132. */
  41133. equals( line ) {
  41134. return line.start.equals( this.start ) && line.end.equals( this.end );
  41135. }
  41136. /**
  41137. * Returns a new line segment with copied values from this instance.
  41138. *
  41139. * @return {Line3} A clone of this instance.
  41140. */
  41141. clone() {
  41142. return new this.constructor().copy( this );
  41143. }
  41144. }
  41145. const _vector$3 = /*@__PURE__*/ new Vector3();
  41146. /**
  41147. * This displays a cone shaped helper object for a {@link SpotLight}.
  41148. *
  41149. * When the spot light or its target are transformed or light properties are
  41150. * changed, it's necessary to call the `update()` method of the respective helper.
  41151. *
  41152. * ```js
  41153. * const spotLight = new THREE.SpotLight( 0xffffff );
  41154. * spotLight.position.set( 10, 10, 10 );
  41155. * scene.add( spotLight );
  41156. *
  41157. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  41158. * scene.add( spotLightHelper );
  41159. * ```
  41160. *
  41161. * @augments Object3D
  41162. */
  41163. class SpotLightHelper extends Object3D {
  41164. /**
  41165. * Constructs a new spot light helper.
  41166. *
  41167. * @param {HemisphereLight} light - The light to be visualized.
  41168. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41169. * the color of the light.
  41170. */
  41171. constructor( light, color ) {
  41172. super();
  41173. /**
  41174. * The light being visualized.
  41175. *
  41176. * @type {SpotLight}
  41177. */
  41178. this.light = light;
  41179. this.matrixAutoUpdate = false;
  41180. /**
  41181. * The color parameter passed in the constructor.
  41182. * If not set, the helper will take the color of the light.
  41183. *
  41184. * @type {number|Color|string}
  41185. */
  41186. this.color = color;
  41187. this.type = 'SpotLightHelper';
  41188. const geometry = new BufferGeometry();
  41189. const positions = [
  41190. 0, 0, 0, 0, 0, 1,
  41191. 0, 0, 0, 1, 0, 1,
  41192. 0, 0, 0, -1, 0, 1,
  41193. 0, 0, 0, 0, 1, 1,
  41194. 0, 0, 0, 0, -1, 1
  41195. ];
  41196. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  41197. const p1 = ( i / l ) * Math.PI * 2;
  41198. const p2 = ( j / l ) * Math.PI * 2;
  41199. positions.push(
  41200. Math.cos( p1 ), Math.sin( p1 ), 1,
  41201. Math.cos( p2 ), Math.sin( p2 ), 1
  41202. );
  41203. }
  41204. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41205. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41206. this.cone = new LineSegments( geometry, material );
  41207. this.add( this.cone );
  41208. this.update();
  41209. }
  41210. /**
  41211. * Frees the GPU-related resources allocated by this instance. Call this
  41212. * method whenever this instance is no longer used in your app.
  41213. */
  41214. dispose() {
  41215. this.cone.geometry.dispose();
  41216. this.cone.material.dispose();
  41217. }
  41218. /**
  41219. * Updates the helper to match the position and direction of the
  41220. * light being visualized.
  41221. */
  41222. update() {
  41223. this.light.updateWorldMatrix( true, false );
  41224. this.light.target.updateWorldMatrix( true, false );
  41225. // update the local matrix based on the parent and light target transforms
  41226. if ( this.parent ) {
  41227. this.parent.updateWorldMatrix( true );
  41228. this.matrix
  41229. .copy( this.parent.matrixWorld )
  41230. .invert()
  41231. .multiply( this.light.matrixWorld );
  41232. } else {
  41233. this.matrix.copy( this.light.matrixWorld );
  41234. }
  41235. this.matrixWorld.copy( this.light.matrixWorld );
  41236. const coneLength = this.light.distance ? this.light.distance : 1000;
  41237. const coneWidth = coneLength * Math.tan( this.light.angle );
  41238. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41239. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41240. this.cone.lookAt( _vector$3 );
  41241. if ( this.color !== undefined ) {
  41242. this.cone.material.color.set( this.color );
  41243. } else {
  41244. this.cone.material.color.copy( this.light.color );
  41245. }
  41246. }
  41247. }
  41248. const _vector$2 = /*@__PURE__*/ new Vector3();
  41249. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41250. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41251. /**
  41252. * A helper object to assist with visualizing a {@link Skeleton}.
  41253. *
  41254. * ```js
  41255. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41256. * scene.add( helper );
  41257. * ```
  41258. *
  41259. * @augments LineSegments
  41260. */
  41261. class SkeletonHelper extends LineSegments {
  41262. /**
  41263. * Constructs a new skeleton helper.
  41264. *
  41265. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41266. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41267. */
  41268. constructor( object ) {
  41269. const bones = getBoneList( object );
  41270. const geometry = new BufferGeometry();
  41271. const vertices = [];
  41272. const colors = [];
  41273. for ( let i = 0; i < bones.length; i ++ ) {
  41274. const bone = bones[ i ];
  41275. if ( bone.parent && bone.parent.isBone ) {
  41276. vertices.push( 0, 0, 0 );
  41277. vertices.push( 0, 0, 0 );
  41278. colors.push( 0, 0, 0 );
  41279. colors.push( 0, 0, 0 );
  41280. }
  41281. }
  41282. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41283. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41284. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41285. super( geometry, material );
  41286. /**
  41287. * This flag can be used for type testing.
  41288. *
  41289. * @type {boolean}
  41290. * @readonly
  41291. * @default true
  41292. */
  41293. this.isSkeletonHelper = true;
  41294. this.type = 'SkeletonHelper';
  41295. /**
  41296. * The object being visualized.
  41297. *
  41298. * @type {Object3D}
  41299. */
  41300. this.root = object;
  41301. /**
  41302. * The list of bones that the helper visualizes.
  41303. *
  41304. * @type {Array<Bone>}
  41305. */
  41306. this.bones = bones;
  41307. this.matrix = object.matrixWorld;
  41308. this.matrixAutoUpdate = false;
  41309. // colors
  41310. const color1 = new Color( 0x0000ff );
  41311. const color2 = new Color( 0x00ff00 );
  41312. this.setColors( color1, color2 );
  41313. }
  41314. updateMatrixWorld( force ) {
  41315. const bones = this.bones;
  41316. const geometry = this.geometry;
  41317. const position = geometry.getAttribute( 'position' );
  41318. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41319. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41320. const bone = bones[ i ];
  41321. if ( bone.parent && bone.parent.isBone ) {
  41322. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41323. _vector$2.setFromMatrixPosition( _boneMatrix );
  41324. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41325. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41326. _vector$2.setFromMatrixPosition( _boneMatrix );
  41327. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41328. j += 2;
  41329. }
  41330. }
  41331. geometry.getAttribute( 'position' ).needsUpdate = true;
  41332. super.updateMatrixWorld( force );
  41333. }
  41334. /**
  41335. * Defines the colors of the helper.
  41336. *
  41337. * @param {Color} color1 - The first line color for each bone.
  41338. * @param {Color} color2 - The second line color for each bone.
  41339. * @return {SkeletonHelper} A reference to this helper.
  41340. */
  41341. setColors( color1, color2 ) {
  41342. const geometry = this.geometry;
  41343. const colorAttribute = geometry.getAttribute( 'color' );
  41344. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41345. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41346. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41347. }
  41348. colorAttribute.needsUpdate = true;
  41349. return this;
  41350. }
  41351. /**
  41352. * Frees the GPU-related resources allocated by this instance. Call this
  41353. * method whenever this instance is no longer used in your app.
  41354. */
  41355. dispose() {
  41356. this.geometry.dispose();
  41357. this.material.dispose();
  41358. }
  41359. }
  41360. function getBoneList( object ) {
  41361. const boneList = [];
  41362. if ( object.isBone === true ) {
  41363. boneList.push( object );
  41364. }
  41365. for ( let i = 0; i < object.children.length; i ++ ) {
  41366. boneList.push( ...getBoneList( object.children[ i ] ) );
  41367. }
  41368. return boneList;
  41369. }
  41370. /**
  41371. * This displays a helper object consisting of a spherical mesh for
  41372. * visualizing an instance of {@link PointLight}.
  41373. *
  41374. * ```js
  41375. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41376. * pointLight.position.set( 10, 10, 10 );
  41377. * scene.add( pointLight );
  41378. *
  41379. * const sphereSize = 1;
  41380. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41381. * scene.add( pointLightHelper );
  41382. * ```
  41383. *
  41384. * @augments Mesh
  41385. */
  41386. class PointLightHelper extends Mesh {
  41387. /**
  41388. * Constructs a new point light helper.
  41389. *
  41390. * @param {PointLight} light - The light to be visualized.
  41391. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41392. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41393. * the color of the light.
  41394. */
  41395. constructor( light, sphereSize, color ) {
  41396. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41397. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41398. super( geometry, material );
  41399. /**
  41400. * The light being visualized.
  41401. *
  41402. * @type {PointLight}
  41403. */
  41404. this.light = light;
  41405. /**
  41406. * The color parameter passed in the constructor.
  41407. * If not set, the helper will take the color of the light.
  41408. *
  41409. * @type {number|Color|string}
  41410. */
  41411. this.color = color;
  41412. this.type = 'PointLightHelper';
  41413. this.matrix = this.light.matrixWorld;
  41414. this.matrixAutoUpdate = false;
  41415. this.update();
  41416. /*
  41417. // TODO: delete this comment?
  41418. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  41419. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  41420. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  41421. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  41422. const d = light.distance;
  41423. if ( d === 0.0 ) {
  41424. this.lightDistance.visible = false;
  41425. } else {
  41426. this.lightDistance.scale.set( d, d, d );
  41427. }
  41428. this.add( this.lightDistance );
  41429. */
  41430. }
  41431. /**
  41432. * Frees the GPU-related resources allocated by this instance. Call this
  41433. * method whenever this instance is no longer used in your app.
  41434. */
  41435. dispose() {
  41436. this.geometry.dispose();
  41437. this.material.dispose();
  41438. }
  41439. /**
  41440. * Updates the helper to match the position of the
  41441. * light being visualized.
  41442. */
  41443. update() {
  41444. this.light.updateWorldMatrix( true, false );
  41445. if ( this.color !== undefined ) {
  41446. this.material.color.set( this.color );
  41447. } else {
  41448. this.material.color.copy( this.light.color );
  41449. }
  41450. /*
  41451. const d = this.light.distance;
  41452. if ( d === 0.0 ) {
  41453. this.lightDistance.visible = false;
  41454. } else {
  41455. this.lightDistance.visible = true;
  41456. this.lightDistance.scale.set( d, d, d );
  41457. }
  41458. */
  41459. }
  41460. }
  41461. const _vector$1 = /*@__PURE__*/ new Vector3();
  41462. const _color1 = /*@__PURE__*/ new Color();
  41463. const _color2 = /*@__PURE__*/ new Color();
  41464. /**
  41465. * Creates a visual aid consisting of a spherical mesh for a
  41466. * given {@link HemisphereLight}.
  41467. *
  41468. * When the hemisphere light is transformed or its light properties are changed,
  41469. * it's necessary to call the `update()` method of the respective helper.
  41470. *
  41471. * ```js
  41472. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41473. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41474. * scene.add( helper );
  41475. * ```
  41476. *
  41477. * @augments Object3D
  41478. */
  41479. class HemisphereLightHelper extends Object3D {
  41480. /**
  41481. * Constructs a new hemisphere light helper.
  41482. *
  41483. * @param {HemisphereLight} light - The light to be visualized.
  41484. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41485. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41486. * the color of the light.
  41487. */
  41488. constructor( light, size, color ) {
  41489. super();
  41490. /**
  41491. * The light being visualized.
  41492. *
  41493. * @type {HemisphereLight}
  41494. */
  41495. this.light = light;
  41496. this.matrix = light.matrixWorld;
  41497. this.matrixAutoUpdate = false;
  41498. /**
  41499. * The color parameter passed in the constructor.
  41500. * If not set, the helper will take the color of the light.
  41501. *
  41502. * @type {number|Color|string}
  41503. */
  41504. this.color = color;
  41505. this.type = 'HemisphereLightHelper';
  41506. const geometry = new OctahedronGeometry( size );
  41507. geometry.rotateY( Math.PI * 0.5 );
  41508. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41509. if ( this.color === undefined ) this.material.vertexColors = true;
  41510. const position = geometry.getAttribute( 'position' );
  41511. const colors = new Float32Array( position.count * 3 );
  41512. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41513. this.add( new Mesh( geometry, this.material ) );
  41514. this.update();
  41515. }
  41516. /**
  41517. * Frees the GPU-related resources allocated by this instance. Call this
  41518. * method whenever this instance is no longer used in your app.
  41519. */
  41520. dispose() {
  41521. this.children[ 0 ].geometry.dispose();
  41522. this.children[ 0 ].material.dispose();
  41523. }
  41524. /**
  41525. * Updates the helper to match the position and direction of the
  41526. * light being visualized.
  41527. */
  41528. update() {
  41529. const mesh = this.children[ 0 ];
  41530. if ( this.color !== undefined ) {
  41531. this.material.color.set( this.color );
  41532. } else {
  41533. const colors = mesh.geometry.getAttribute( 'color' );
  41534. _color1.copy( this.light.color );
  41535. _color2.copy( this.light.groundColor );
  41536. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41537. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41538. colors.setXYZ( i, color.r, color.g, color.b );
  41539. }
  41540. colors.needsUpdate = true;
  41541. }
  41542. this.light.updateWorldMatrix( true, false );
  41543. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41544. }
  41545. }
  41546. /**
  41547. * The helper is an object to define grids. Grids are two-dimensional
  41548. * arrays of lines.
  41549. *
  41550. * ```js
  41551. * const size = 10;
  41552. * const divisions = 10;
  41553. *
  41554. * const gridHelper = new THREE.GridHelper( size, divisions );
  41555. * scene.add( gridHelper );
  41556. * ```
  41557. *
  41558. * @augments LineSegments
  41559. */
  41560. class GridHelper extends LineSegments {
  41561. /**
  41562. * Constructs a new grid helper.
  41563. *
  41564. * @param {number} [size=10] - The size of the grid.
  41565. * @param {number} [divisions=10] - The number of divisions across the grid.
  41566. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41567. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41568. */
  41569. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41570. color1 = new Color( color1 );
  41571. color2 = new Color( color2 );
  41572. const center = divisions / 2;
  41573. const step = size / divisions;
  41574. const halfSize = size / 2;
  41575. const vertices = [], colors = [];
  41576. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41577. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41578. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41579. const color = i === center ? color1 : color2;
  41580. color.toArray( colors, j ); j += 3;
  41581. color.toArray( colors, j ); j += 3;
  41582. color.toArray( colors, j ); j += 3;
  41583. color.toArray( colors, j ); j += 3;
  41584. }
  41585. const geometry = new BufferGeometry();
  41586. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41587. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41588. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41589. super( geometry, material );
  41590. this.type = 'GridHelper';
  41591. }
  41592. /**
  41593. * Frees the GPU-related resources allocated by this instance. Call this
  41594. * method whenever this instance is no longer used in your app.
  41595. */
  41596. dispose() {
  41597. this.geometry.dispose();
  41598. this.material.dispose();
  41599. }
  41600. }
  41601. /**
  41602. * This helper is an object to define polar grids. Grids are
  41603. * two-dimensional arrays of lines.
  41604. *
  41605. * ```js
  41606. * const radius = 10;
  41607. * const sectors = 16;
  41608. * const rings = 8;
  41609. * const divisions = 64;
  41610. *
  41611. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41612. * scene.add( helper );
  41613. * ```
  41614. *
  41615. * @augments LineSegments
  41616. */
  41617. class PolarGridHelper extends LineSegments {
  41618. /**
  41619. * Constructs a new polar grid helper.
  41620. *
  41621. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41622. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41623. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41624. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41625. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41626. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41627. */
  41628. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41629. color1 = new Color( color1 );
  41630. color2 = new Color( color2 );
  41631. const vertices = [];
  41632. const colors = [];
  41633. // create the sectors
  41634. if ( sectors > 1 ) {
  41635. for ( let i = 0; i < sectors; i ++ ) {
  41636. const v = ( i / sectors ) * ( Math.PI * 2 );
  41637. const x = Math.sin( v ) * radius;
  41638. const z = Math.cos( v ) * radius;
  41639. vertices.push( 0, 0, 0 );
  41640. vertices.push( x, 0, z );
  41641. const color = ( i & 1 ) ? color1 : color2;
  41642. colors.push( color.r, color.g, color.b );
  41643. colors.push( color.r, color.g, color.b );
  41644. }
  41645. }
  41646. // create the rings
  41647. for ( let i = 0; i < rings; i ++ ) {
  41648. const color = ( i & 1 ) ? color1 : color2;
  41649. const r = radius - ( radius / rings * i );
  41650. for ( let j = 0; j < divisions; j ++ ) {
  41651. // first vertex
  41652. let v = ( j / divisions ) * ( Math.PI * 2 );
  41653. let x = Math.sin( v ) * r;
  41654. let z = Math.cos( v ) * r;
  41655. vertices.push( x, 0, z );
  41656. colors.push( color.r, color.g, color.b );
  41657. // second vertex
  41658. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41659. x = Math.sin( v ) * r;
  41660. z = Math.cos( v ) * r;
  41661. vertices.push( x, 0, z );
  41662. colors.push( color.r, color.g, color.b );
  41663. }
  41664. }
  41665. const geometry = new BufferGeometry();
  41666. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41667. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41668. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41669. super( geometry, material );
  41670. this.type = 'PolarGridHelper';
  41671. }
  41672. /**
  41673. * Frees the GPU-related resources allocated by this instance. Call this
  41674. * method whenever this instance is no longer used in your app.
  41675. */
  41676. dispose() {
  41677. this.geometry.dispose();
  41678. this.material.dispose();
  41679. }
  41680. }
  41681. const _v1 = /*@__PURE__*/ new Vector3();
  41682. const _v2 = /*@__PURE__*/ new Vector3();
  41683. const _v3 = /*@__PURE__*/ new Vector3();
  41684. /**
  41685. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41686. * effect on the scene. This consists of a plane and a line representing the
  41687. * light's position and direction.
  41688. *
  41689. * When the directional light or its target are transformed or light properties
  41690. * are changed, it's necessary to call the `update()` method of the respective helper.
  41691. *
  41692. * ```js
  41693. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41694. * scene.add( light );
  41695. *
  41696. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41697. * scene.add( helper );
  41698. * ```
  41699. *
  41700. * @augments Object3D
  41701. */
  41702. class DirectionalLightHelper extends Object3D {
  41703. /**
  41704. * Constructs a new directional light helper.
  41705. *
  41706. * @param {DirectionalLight} light - The light to be visualized.
  41707. * @param {number} [size=1] - The dimensions of the plane.
  41708. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41709. * the color of the light.
  41710. */
  41711. constructor( light, size, color ) {
  41712. super();
  41713. /**
  41714. * The light being visualized.
  41715. *
  41716. * @type {DirectionalLight}
  41717. */
  41718. this.light = light;
  41719. this.matrix = light.matrixWorld;
  41720. this.matrixAutoUpdate = false;
  41721. /**
  41722. * The color parameter passed in the constructor.
  41723. * If not set, the helper will take the color of the light.
  41724. *
  41725. * @type {number|Color|string}
  41726. */
  41727. this.color = color;
  41728. this.type = 'DirectionalLightHelper';
  41729. if ( size === undefined ) size = 1;
  41730. let geometry = new BufferGeometry();
  41731. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41732. - size, size, 0,
  41733. size, size, 0,
  41734. size, - size, 0,
  41735. - size, - size, 0,
  41736. - size, size, 0
  41737. ], 3 ) );
  41738. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41739. /**
  41740. * Contains the line showing the location of the directional light.
  41741. *
  41742. * @type {Line}
  41743. */
  41744. this.lightPlane = new Line( geometry, material );
  41745. this.add( this.lightPlane );
  41746. geometry = new BufferGeometry();
  41747. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41748. /**
  41749. * Represents the target line of the directional light.
  41750. *
  41751. * @type {Line}
  41752. */
  41753. this.targetLine = new Line( geometry, material );
  41754. this.add( this.targetLine );
  41755. this.update();
  41756. }
  41757. /**
  41758. * Frees the GPU-related resources allocated by this instance. Call this
  41759. * method whenever this instance is no longer used in your app.
  41760. */
  41761. dispose() {
  41762. this.lightPlane.geometry.dispose();
  41763. this.lightPlane.material.dispose();
  41764. this.targetLine.geometry.dispose();
  41765. this.targetLine.material.dispose();
  41766. }
  41767. /**
  41768. * Updates the helper to match the position and direction of the
  41769. * light being visualized.
  41770. */
  41771. update() {
  41772. this.light.updateWorldMatrix( true, false );
  41773. this.light.target.updateWorldMatrix( true, false );
  41774. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41775. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41776. _v3.subVectors( _v2, _v1 );
  41777. this.lightPlane.lookAt( _v2 );
  41778. if ( this.color !== undefined ) {
  41779. this.lightPlane.material.color.set( this.color );
  41780. this.targetLine.material.color.set( this.color );
  41781. } else {
  41782. this.lightPlane.material.color.copy( this.light.color );
  41783. this.targetLine.material.color.copy( this.light.color );
  41784. }
  41785. this.targetLine.lookAt( _v2 );
  41786. this.targetLine.scale.z = _v3.length();
  41787. }
  41788. }
  41789. const _vector = /*@__PURE__*/ new Vector3();
  41790. const _camera = /*@__PURE__*/ new Camera();
  41791. /**
  41792. * This helps with visualizing what a camera contains in its frustum. It
  41793. * visualizes the frustum of a camera using a line segments.
  41794. *
  41795. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  41796. *
  41797. * `CameraHelper` must be a child of the scene.
  41798. *
  41799. * When the camera is transformed or its projection matrix is changed, it's necessary
  41800. * to call the `update()` method of the respective helper.
  41801. *
  41802. * ```js
  41803. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41804. * const helper = new THREE.CameraHelper( camera );
  41805. * scene.add( helper );
  41806. * ```
  41807. *
  41808. * @augments LineSegments
  41809. */
  41810. class CameraHelper extends LineSegments {
  41811. /**
  41812. * Constructs a new arrow helper.
  41813. *
  41814. * @param {Camera} camera - The camera to visualize.
  41815. */
  41816. constructor( camera ) {
  41817. const geometry = new BufferGeometry();
  41818. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41819. const vertices = [];
  41820. const colors = [];
  41821. const pointMap = {};
  41822. // near
  41823. addLine( 'n1', 'n2' );
  41824. addLine( 'n2', 'n4' );
  41825. addLine( 'n4', 'n3' );
  41826. addLine( 'n3', 'n1' );
  41827. // far
  41828. addLine( 'f1', 'f2' );
  41829. addLine( 'f2', 'f4' );
  41830. addLine( 'f4', 'f3' );
  41831. addLine( 'f3', 'f1' );
  41832. // sides
  41833. addLine( 'n1', 'f1' );
  41834. addLine( 'n2', 'f2' );
  41835. addLine( 'n3', 'f3' );
  41836. addLine( 'n4', 'f4' );
  41837. // cone
  41838. addLine( 'p', 'n1' );
  41839. addLine( 'p', 'n2' );
  41840. addLine( 'p', 'n3' );
  41841. addLine( 'p', 'n4' );
  41842. // up
  41843. addLine( 'u1', 'u2' );
  41844. addLine( 'u2', 'u3' );
  41845. addLine( 'u3', 'u1' );
  41846. // target
  41847. addLine( 'c', 't' );
  41848. addLine( 'p', 'c' );
  41849. // cross
  41850. addLine( 'cn1', 'cn2' );
  41851. addLine( 'cn3', 'cn4' );
  41852. addLine( 'cf1', 'cf2' );
  41853. addLine( 'cf3', 'cf4' );
  41854. function addLine( a, b ) {
  41855. addPoint( a );
  41856. addPoint( b );
  41857. }
  41858. function addPoint( id ) {
  41859. vertices.push( 0, 0, 0 );
  41860. colors.push( 0, 0, 0 );
  41861. if ( pointMap[ id ] === undefined ) {
  41862. pointMap[ id ] = [];
  41863. }
  41864. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41865. }
  41866. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41867. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41868. super( geometry, material );
  41869. this.type = 'CameraHelper';
  41870. /**
  41871. * The camera being visualized.
  41872. *
  41873. * @type {Camera}
  41874. */
  41875. this.camera = camera;
  41876. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41877. this.matrix = camera.matrixWorld;
  41878. this.matrixAutoUpdate = false;
  41879. /**
  41880. * This contains the points used to visualize the camera.
  41881. *
  41882. * @type {Object<string,Array<number>>}
  41883. */
  41884. this.pointMap = pointMap;
  41885. this.update();
  41886. // colors
  41887. const colorFrustum = new Color( 0xffaa00 );
  41888. const colorCone = new Color( 0xff0000 );
  41889. const colorUp = new Color( 0x00aaff );
  41890. const colorTarget = new Color( 0xffffff );
  41891. const colorCross = new Color( 0x333333 );
  41892. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41893. }
  41894. /**
  41895. * Defines the colors of the helper.
  41896. *
  41897. * @param {Color} frustum - The frustum line color.
  41898. * @param {Color} cone - The cone line color.
  41899. * @param {Color} up - The up line color.
  41900. * @param {Color} target - The target line color.
  41901. * @param {Color} cross - The cross line color.
  41902. * @return {CameraHelper} A reference to this helper.
  41903. */
  41904. setColors( frustum, cone, up, target, cross ) {
  41905. const geometry = this.geometry;
  41906. const colorAttribute = geometry.getAttribute( 'color' );
  41907. // near
  41908. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41909. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41910. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41911. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41912. // far
  41913. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41914. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41915. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41916. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41917. // sides
  41918. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41919. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41920. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41921. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41922. // cone
  41923. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41924. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41925. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41926. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41927. // up
  41928. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41929. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41930. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41931. // target
  41932. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41933. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41934. // cross
  41935. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41936. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41937. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41938. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41939. colorAttribute.needsUpdate = true;
  41940. return this;
  41941. }
  41942. /**
  41943. * Updates the helper based on the projection matrix of the camera.
  41944. */
  41945. update() {
  41946. const geometry = this.geometry;
  41947. const pointMap = this.pointMap;
  41948. const w = 1, h = 1;
  41949. let nearZ, farZ;
  41950. // we need just camera projection matrix inverse
  41951. // world matrix must be identity
  41952. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41953. // Adjust z values based on coordinate system
  41954. if ( this.camera.reversedDepth === true ) {
  41955. nearZ = 1;
  41956. farZ = 0;
  41957. } else {
  41958. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41959. nearZ = -1;
  41960. farZ = 1;
  41961. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41962. nearZ = 0;
  41963. farZ = 1;
  41964. } else {
  41965. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41966. }
  41967. }
  41968. // center / target
  41969. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41970. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41971. // near
  41972. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41973. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41974. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41975. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41976. // far
  41977. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41978. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41979. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41980. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41981. // up
  41982. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41983. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41984. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41985. // cross
  41986. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41987. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41988. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41989. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41990. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41991. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41992. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41993. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41994. geometry.getAttribute( 'position' ).needsUpdate = true;
  41995. }
  41996. /**
  41997. * Frees the GPU-related resources allocated by this instance. Call this
  41998. * method whenever this instance is no longer used in your app.
  41999. */
  42000. dispose() {
  42001. this.geometry.dispose();
  42002. this.material.dispose();
  42003. }
  42004. }
  42005. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  42006. _vector.set( x, y, z ).unproject( camera );
  42007. const points = pointMap[ point ];
  42008. if ( points !== undefined ) {
  42009. const position = geometry.getAttribute( 'position' );
  42010. for ( let i = 0, l = points.length; i < l; i ++ ) {
  42011. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  42012. }
  42013. }
  42014. }
  42015. const _box = /*@__PURE__*/ new Box3();
  42016. /**
  42017. * Helper object to graphically show the world-axis-aligned bounding box
  42018. * around an object. The actual bounding box is handled with {@link Box3},
  42019. * this is just a visual helper for debugging. It can be automatically
  42020. * resized with {@link BoxHelper#update} when the object it's created from
  42021. * is transformed. Note that the object must have a geometry for this to work,
  42022. * so it won't work with sprites.
  42023. *
  42024. * ```js
  42025. * const sphere = new THREE.SphereGeometry();
  42026. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  42027. * const box = new THREE.BoxHelper( object, 0xffff00 );
  42028. * scene.add( box );
  42029. * ```
  42030. *
  42031. * @augments LineSegments
  42032. */
  42033. class BoxHelper extends LineSegments {
  42034. /**
  42035. * Constructs a new box helper.
  42036. *
  42037. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  42038. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42039. */
  42040. constructor( object, color = 0xffff00 ) {
  42041. 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 ] );
  42042. const positions = new Float32Array( 8 * 3 );
  42043. const geometry = new BufferGeometry();
  42044. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42045. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  42046. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42047. /**
  42048. * The 3D object being visualized.
  42049. *
  42050. * @type {Object3D}
  42051. */
  42052. this.object = object;
  42053. this.type = 'BoxHelper';
  42054. this.matrixAutoUpdate = false;
  42055. this.update();
  42056. }
  42057. /**
  42058. * Updates the helper's geometry to match the dimensions of the object,
  42059. * including any children.
  42060. */
  42061. update() {
  42062. if ( this.object !== undefined ) {
  42063. _box.setFromObject( this.object );
  42064. }
  42065. if ( _box.isEmpty() ) return;
  42066. const min = _box.min;
  42067. const max = _box.max;
  42068. /*
  42069. 5____4
  42070. 1/___0/|
  42071. | 6__|_7
  42072. 2/___3/
  42073. 0: max.x, max.y, max.z
  42074. 1: min.x, max.y, max.z
  42075. 2: min.x, min.y, max.z
  42076. 3: max.x, min.y, max.z
  42077. 4: max.x, max.y, min.z
  42078. 5: min.x, max.y, min.z
  42079. 6: min.x, min.y, min.z
  42080. 7: max.x, min.y, min.z
  42081. */
  42082. const position = this.geometry.attributes.position;
  42083. const array = position.array;
  42084. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  42085. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  42086. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  42087. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  42088. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  42089. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  42090. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  42091. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  42092. position.needsUpdate = true;
  42093. this.geometry.computeBoundingSphere();
  42094. }
  42095. /**
  42096. * Updates the wireframe box for the passed object.
  42097. *
  42098. * @param {Object3D} object - The 3D object to create the helper for.
  42099. * @return {BoxHelper} A reference to this instance.
  42100. */
  42101. setFromObject( object ) {
  42102. this.object = object;
  42103. this.update();
  42104. return this;
  42105. }
  42106. copy( source, recursive ) {
  42107. super.copy( source, recursive );
  42108. this.object = source.object;
  42109. return this;
  42110. }
  42111. /**
  42112. * Frees the GPU-related resources allocated by this instance. Call this
  42113. * method whenever this instance is no longer used in your app.
  42114. */
  42115. dispose() {
  42116. this.geometry.dispose();
  42117. this.material.dispose();
  42118. }
  42119. }
  42120. /**
  42121. * A helper object to visualize an instance of {@link Box3}.
  42122. *
  42123. * ```js
  42124. * const box = new THREE.Box3();
  42125. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  42126. *
  42127. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  42128. * scene.add( helper )
  42129. * ```
  42130. *
  42131. * @augments LineSegments
  42132. */
  42133. class Box3Helper extends LineSegments {
  42134. /**
  42135. * Constructs a new box3 helper.
  42136. *
  42137. * @param {Box3} box - The box to visualize.
  42138. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42139. */
  42140. constructor( box, color = 0xffff00 ) {
  42141. 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 ] );
  42142. 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 ];
  42143. const geometry = new BufferGeometry();
  42144. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42145. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42146. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42147. /**
  42148. * The box being visualized.
  42149. *
  42150. * @type {Box3}
  42151. */
  42152. this.box = box;
  42153. this.type = 'Box3Helper';
  42154. this.geometry.computeBoundingSphere();
  42155. }
  42156. updateMatrixWorld( force ) {
  42157. const box = this.box;
  42158. if ( box.isEmpty() ) return;
  42159. box.getCenter( this.position );
  42160. box.getSize( this.scale );
  42161. this.scale.multiplyScalar( 0.5 );
  42162. super.updateMatrixWorld( force );
  42163. }
  42164. /**
  42165. * Frees the GPU-related resources allocated by this instance. Call this
  42166. * method whenever this instance is no longer used in your app.
  42167. */
  42168. dispose() {
  42169. this.geometry.dispose();
  42170. this.material.dispose();
  42171. }
  42172. }
  42173. /**
  42174. * A helper object to visualize an instance of {@link Plane}.
  42175. *
  42176. * ```js
  42177. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  42178. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  42179. * scene.add( helper );
  42180. * ```
  42181. *
  42182. * @augments Line
  42183. */
  42184. class PlaneHelper extends Line {
  42185. /**
  42186. * Constructs a new plane helper.
  42187. *
  42188. * @param {Plane} plane - The plane to be visualized.
  42189. * @param {number} [size=1] - The side length of plane helper.
  42190. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  42191. */
  42192. constructor( plane, size = 1, hex = 0xffff00 ) {
  42193. const color = hex;
  42194. 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 ];
  42195. const geometry = new BufferGeometry();
  42196. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42197. geometry.computeBoundingSphere();
  42198. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42199. this.type = 'PlaneHelper';
  42200. /**
  42201. * The plane being visualized.
  42202. *
  42203. * @type {Plane}
  42204. */
  42205. this.plane = plane;
  42206. /**
  42207. * The side length of plane helper.
  42208. *
  42209. * @type {number}
  42210. * @default 1
  42211. */
  42212. this.size = size;
  42213. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  42214. const geometry2 = new BufferGeometry();
  42215. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42216. geometry2.computeBoundingSphere();
  42217. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42218. }
  42219. updateMatrixWorld( force ) {
  42220. this.position.set( 0, 0, 0 );
  42221. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42222. this.lookAt( this.plane.normal );
  42223. this.translateZ( - this.plane.constant );
  42224. super.updateMatrixWorld( force );
  42225. }
  42226. /**
  42227. * Updates the helper to match the position and direction of the
  42228. * light being visualized.
  42229. */
  42230. dispose() {
  42231. this.geometry.dispose();
  42232. this.material.dispose();
  42233. this.children[ 0 ].geometry.dispose();
  42234. this.children[ 0 ].material.dispose();
  42235. }
  42236. }
  42237. const _axis = /*@__PURE__*/ new Vector3();
  42238. let _lineGeometry, _coneGeometry;
  42239. /**
  42240. * An 3D arrow object for visualizing directions.
  42241. *
  42242. * ```js
  42243. * const dir = new THREE.Vector3( 1, 2, 0 );
  42244. *
  42245. * //normalize the direction vector (convert to vector of length 1)
  42246. * dir.normalize();
  42247. *
  42248. * const origin = new THREE.Vector3( 0, 0, 0 );
  42249. * const length = 1;
  42250. * const hex = 0xffff00;
  42251. *
  42252. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42253. * scene.add( arrowHelper );
  42254. * ```
  42255. *
  42256. * @augments Object3D
  42257. */
  42258. class ArrowHelper extends Object3D {
  42259. /**
  42260. * Constructs a new arrow helper.
  42261. *
  42262. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42263. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42264. * @param {number} [length=1] - Length of the arrow in world units.
  42265. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42266. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42267. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42268. */
  42269. 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 ) {
  42270. super();
  42271. this.type = 'ArrowHelper';
  42272. if ( _lineGeometry === undefined ) {
  42273. _lineGeometry = new BufferGeometry();
  42274. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42275. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42276. _coneGeometry.translate( 0, -0.5, 0 );
  42277. }
  42278. this.position.copy( origin );
  42279. /**
  42280. * The line part of the arrow helper.
  42281. *
  42282. * @type {Line}
  42283. */
  42284. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42285. this.line.matrixAutoUpdate = false;
  42286. this.add( this.line );
  42287. /**
  42288. * The cone part of the arrow helper.
  42289. *
  42290. * @type {Mesh}
  42291. */
  42292. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42293. this.cone.matrixAutoUpdate = false;
  42294. this.add( this.cone );
  42295. this.setDirection( dir );
  42296. this.setLength( length, headLength, headWidth );
  42297. }
  42298. /**
  42299. * Sets the direction of the helper.
  42300. *
  42301. * @param {Vector3} dir - The normalized direction vector.
  42302. */
  42303. setDirection( dir ) {
  42304. // dir is assumed to be normalized
  42305. if ( dir.y > 0.99999 ) {
  42306. this.quaternion.set( 0, 0, 0, 1 );
  42307. } else if ( dir.y < -0.99999 ) {
  42308. this.quaternion.set( 1, 0, 0, 0 );
  42309. } else {
  42310. _axis.set( dir.z, 0, - dir.x ).normalize();
  42311. const radians = Math.acos( dir.y );
  42312. this.quaternion.setFromAxisAngle( _axis, radians );
  42313. }
  42314. }
  42315. /**
  42316. * Sets the length of the helper.
  42317. *
  42318. * @param {number} length - Length of the arrow in world units.
  42319. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42320. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42321. */
  42322. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42323. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42324. this.line.updateMatrix();
  42325. this.cone.scale.set( headWidth, headLength, headWidth );
  42326. this.cone.position.y = length;
  42327. this.cone.updateMatrix();
  42328. }
  42329. /**
  42330. * Sets the color of the helper.
  42331. *
  42332. * @param {number|Color|string} color - The color to set.
  42333. */
  42334. setColor( color ) {
  42335. this.line.material.color.set( color );
  42336. this.cone.material.color.set( color );
  42337. }
  42338. copy( source ) {
  42339. super.copy( source, false );
  42340. this.line.copy( source.line );
  42341. this.cone.copy( source.cone );
  42342. return this;
  42343. }
  42344. /**
  42345. * Frees the GPU-related resources allocated by this instance. Call this
  42346. * method whenever this instance is no longer used in your app.
  42347. */
  42348. dispose() {
  42349. this.line.geometry.dispose();
  42350. this.line.material.dispose();
  42351. this.cone.geometry.dispose();
  42352. this.cone.material.dispose();
  42353. }
  42354. }
  42355. /**
  42356. * An axis object to visualize the 3 axes in a simple way.
  42357. * The X axis is red. The Y axis is green. The Z axis is blue.
  42358. *
  42359. * ```js
  42360. * const axesHelper = new THREE.AxesHelper( 5 );
  42361. * scene.add( axesHelper );
  42362. * ```
  42363. *
  42364. * @augments LineSegments
  42365. */
  42366. class AxesHelper extends LineSegments {
  42367. /**
  42368. * Constructs a new axes helper.
  42369. *
  42370. * @param {number} [size=1] - Size of the lines representing the axes.
  42371. */
  42372. constructor( size = 1 ) {
  42373. const vertices = [
  42374. 0, 0, 0, size, 0, 0,
  42375. 0, 0, 0, 0, size, 0,
  42376. 0, 0, 0, 0, 0, size
  42377. ];
  42378. const colors = [
  42379. 1, 0, 0, 1, 0.6, 0,
  42380. 0, 1, 0, 0.6, 1, 0,
  42381. 0, 0, 1, 0, 0.6, 1
  42382. ];
  42383. const geometry = new BufferGeometry();
  42384. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42385. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42386. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42387. super( geometry, material );
  42388. this.type = 'AxesHelper';
  42389. }
  42390. /**
  42391. * Defines the colors of the axes helper.
  42392. *
  42393. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42394. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42395. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42396. * @return {AxesHelper} A reference to this axes helper.
  42397. */
  42398. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42399. const color = new Color();
  42400. const array = this.geometry.attributes.color.array;
  42401. color.set( xAxisColor );
  42402. color.toArray( array, 0 );
  42403. color.toArray( array, 3 );
  42404. color.set( yAxisColor );
  42405. color.toArray( array, 6 );
  42406. color.toArray( array, 9 );
  42407. color.set( zAxisColor );
  42408. color.toArray( array, 12 );
  42409. color.toArray( array, 15 );
  42410. this.geometry.attributes.color.needsUpdate = true;
  42411. return this;
  42412. }
  42413. /**
  42414. * Frees the GPU-related resources allocated by this instance. Call this
  42415. * method whenever this instance is no longer used in your app.
  42416. */
  42417. dispose() {
  42418. this.geometry.dispose();
  42419. this.material.dispose();
  42420. }
  42421. }
  42422. /**
  42423. * This class is used to convert a series of paths to an array of
  42424. * shapes. It is specifically used in context of fonts and SVG.
  42425. */
  42426. class ShapePath {
  42427. /**
  42428. * Constructs a new shape path.
  42429. */
  42430. constructor() {
  42431. this.type = 'ShapePath';
  42432. /**
  42433. * The color of the shape.
  42434. *
  42435. * @type {Color}
  42436. */
  42437. this.color = new Color();
  42438. /**
  42439. * The paths that have been generated for this shape.
  42440. *
  42441. * @type {Array<Path>}
  42442. * @default null
  42443. */
  42444. this.subPaths = [];
  42445. /**
  42446. * The current path that is being generated.
  42447. *
  42448. * @type {?Path}
  42449. * @default null
  42450. */
  42451. this.currentPath = null;
  42452. }
  42453. /**
  42454. * Creates a new path and moves it current point to the given one.
  42455. *
  42456. * @param {number} x - The x coordinate.
  42457. * @param {number} y - The y coordinate.
  42458. * @return {ShapePath} A reference to this shape path.
  42459. */
  42460. moveTo( x, y ) {
  42461. this.currentPath = new Path();
  42462. this.subPaths.push( this.currentPath );
  42463. this.currentPath.moveTo( x, y );
  42464. return this;
  42465. }
  42466. /**
  42467. * Adds an instance of {@link LineCurve} to the path by connecting
  42468. * the current point with the given one.
  42469. *
  42470. * @param {number} x - The x coordinate of the end point.
  42471. * @param {number} y - The y coordinate of the end point.
  42472. * @return {ShapePath} A reference to this shape path.
  42473. */
  42474. lineTo( x, y ) {
  42475. this.currentPath.lineTo( x, y );
  42476. return this;
  42477. }
  42478. /**
  42479. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42480. * the current point with the given one.
  42481. *
  42482. * @param {number} aCPx - The x coordinate of the control point.
  42483. * @param {number} aCPy - The y coordinate of the control point.
  42484. * @param {number} aX - The x coordinate of the end point.
  42485. * @param {number} aY - The y coordinate of the end point.
  42486. * @return {ShapePath} A reference to this shape path.
  42487. */
  42488. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42489. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42490. return this;
  42491. }
  42492. /**
  42493. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42494. * the current point with the given one.
  42495. *
  42496. * @param {number} aCP1x - The x coordinate of the first control point.
  42497. * @param {number} aCP1y - The y coordinate of the first control point.
  42498. * @param {number} aCP2x - The x coordinate of the second control point.
  42499. * @param {number} aCP2y - The y coordinate of the second control point.
  42500. * @param {number} aX - The x coordinate of the end point.
  42501. * @param {number} aY - The y coordinate of the end point.
  42502. * @return {ShapePath} A reference to this shape path.
  42503. */
  42504. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42505. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42506. return this;
  42507. }
  42508. /**
  42509. * Adds an instance of {@link SplineCurve} to the path by connecting
  42510. * the current point with the given list of points.
  42511. *
  42512. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42513. * @return {ShapePath} A reference to this shape path.
  42514. */
  42515. splineThru( pts ) {
  42516. this.currentPath.splineThru( pts );
  42517. return this;
  42518. }
  42519. /**
  42520. * Converts the paths into an array of shapes.
  42521. *
  42522. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42523. * If this flag is set to `true`, then those are flipped.
  42524. * @return {Array<Shape>} An array of shapes.
  42525. */
  42526. toShapes( isCCW ) {
  42527. function toShapesNoHoles( inSubpaths ) {
  42528. const shapes = [];
  42529. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42530. const tmpPath = inSubpaths[ i ];
  42531. const tmpShape = new Shape();
  42532. tmpShape.curves = tmpPath.curves;
  42533. shapes.push( tmpShape );
  42534. }
  42535. return shapes;
  42536. }
  42537. function isPointInsidePolygon( inPt, inPolygon ) {
  42538. const polyLen = inPolygon.length;
  42539. // inPt on polygon contour => immediate success or
  42540. // toggling of inside/outside at every single! intersection point of an edge
  42541. // with the horizontal line through inPt, left of inPt
  42542. // not counting lowerY endpoints of edges and whole edges on that line
  42543. let inside = false;
  42544. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42545. let edgeLowPt = inPolygon[ p ];
  42546. let edgeHighPt = inPolygon[ q ];
  42547. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42548. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42549. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42550. // not parallel
  42551. if ( edgeDy < 0 ) {
  42552. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42553. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42554. }
  42555. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42556. if ( inPt.y === edgeLowPt.y ) {
  42557. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42558. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42559. } else {
  42560. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42561. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42562. if ( perpEdge < 0 ) continue;
  42563. inside = ! inside; // true intersection left of inPt
  42564. }
  42565. } else {
  42566. // parallel or collinear
  42567. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42568. // edge lies on the same horizontal line as inPt
  42569. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42570. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42571. // continue;
  42572. }
  42573. }
  42574. return inside;
  42575. }
  42576. const isClockWise = ShapeUtils.isClockWise;
  42577. const subPaths = this.subPaths;
  42578. if ( subPaths.length === 0 ) return [];
  42579. let solid, tmpPath, tmpShape;
  42580. const shapes = [];
  42581. if ( subPaths.length === 1 ) {
  42582. tmpPath = subPaths[ 0 ];
  42583. tmpShape = new Shape();
  42584. tmpShape.curves = tmpPath.curves;
  42585. shapes.push( tmpShape );
  42586. return shapes;
  42587. }
  42588. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42589. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42590. // log("Holes first", holesFirst);
  42591. const betterShapeHoles = [];
  42592. const newShapes = [];
  42593. let newShapeHoles = [];
  42594. let mainIdx = 0;
  42595. let tmpPoints;
  42596. newShapes[ mainIdx ] = undefined;
  42597. newShapeHoles[ mainIdx ] = [];
  42598. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42599. tmpPath = subPaths[ i ];
  42600. tmpPoints = tmpPath.getPoints();
  42601. solid = isClockWise( tmpPoints );
  42602. solid = isCCW ? ! solid : solid;
  42603. if ( solid ) {
  42604. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42605. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42606. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42607. if ( holesFirst ) mainIdx ++;
  42608. newShapeHoles[ mainIdx ] = [];
  42609. //log('cw', i);
  42610. } else {
  42611. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42612. //log('ccw', i);
  42613. }
  42614. }
  42615. // only Holes? -> probably all Shapes with wrong orientation
  42616. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42617. if ( newShapes.length > 1 ) {
  42618. let ambiguous = false;
  42619. let toChange = 0;
  42620. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42621. betterShapeHoles[ sIdx ] = [];
  42622. }
  42623. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42624. const sho = newShapeHoles[ sIdx ];
  42625. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42626. const ho = sho[ hIdx ];
  42627. let hole_unassigned = true;
  42628. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42629. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42630. if ( sIdx !== s2Idx ) toChange ++;
  42631. if ( hole_unassigned ) {
  42632. hole_unassigned = false;
  42633. betterShapeHoles[ s2Idx ].push( ho );
  42634. } else {
  42635. ambiguous = true;
  42636. }
  42637. }
  42638. }
  42639. if ( hole_unassigned ) {
  42640. betterShapeHoles[ sIdx ].push( ho );
  42641. }
  42642. }
  42643. }
  42644. if ( toChange > 0 && ambiguous === false ) {
  42645. newShapeHoles = betterShapeHoles;
  42646. }
  42647. }
  42648. let tmpHoles;
  42649. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42650. tmpShape = newShapes[ i ].s;
  42651. shapes.push( tmpShape );
  42652. tmpHoles = newShapeHoles[ i ];
  42653. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42654. tmpShape.holes.push( tmpHoles[ j ].h );
  42655. }
  42656. }
  42657. //log("shape", shapes);
  42658. return shapes;
  42659. }
  42660. }
  42661. /**
  42662. * Abstract base class for controls.
  42663. *
  42664. * @abstract
  42665. * @augments EventDispatcher
  42666. */
  42667. class Controls extends EventDispatcher {
  42668. /**
  42669. * Constructs a new controls instance.
  42670. *
  42671. * @param {Object3D} object - The object that is managed by the controls.
  42672. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42673. */
  42674. constructor( object, domElement = null ) {
  42675. super();
  42676. /**
  42677. * The object that is managed by the controls.
  42678. *
  42679. * @type {Object3D}
  42680. */
  42681. this.object = object;
  42682. /**
  42683. * The HTML element used for event listeners.
  42684. *
  42685. * @type {?HTMLElement}
  42686. * @default null
  42687. */
  42688. this.domElement = domElement;
  42689. /**
  42690. * Whether the controls responds to user input or not.
  42691. *
  42692. * @type {boolean}
  42693. * @default true
  42694. */
  42695. this.enabled = true;
  42696. /**
  42697. * The internal state of the controls.
  42698. *
  42699. * @type {number}
  42700. * @default -1
  42701. */
  42702. this.state = -1;
  42703. /**
  42704. * This object defines the keyboard input of the controls.
  42705. *
  42706. * @type {Object}
  42707. */
  42708. this.keys = {};
  42709. /**
  42710. * This object defines what type of actions are assigned to the available mouse buttons.
  42711. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42712. *
  42713. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42714. */
  42715. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42716. /**
  42717. * This object defines what type of actions are assigned to what kind of touch interaction.
  42718. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42719. *
  42720. * @type {{ONE: ?number, TWO: ?number}}
  42721. */
  42722. this.touches = { ONE: null, TWO: null };
  42723. }
  42724. /**
  42725. * Connects the controls to the DOM. This method has so called "side effects" since
  42726. * it adds the module's event listeners to the DOM.
  42727. *
  42728. * @param {HTMLElement} element - The DOM element to connect to.
  42729. */
  42730. connect( element ) {
  42731. if ( element === undefined ) {
  42732. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42733. return;
  42734. }
  42735. if ( this.domElement !== null ) this.disconnect();
  42736. this.domElement = element;
  42737. }
  42738. /**
  42739. * Disconnects the controls from the DOM.
  42740. */
  42741. disconnect() {}
  42742. /**
  42743. * Call this method if you no longer want use to the controls. It frees all internal
  42744. * resources and removes all event listeners.
  42745. */
  42746. dispose() {}
  42747. /**
  42748. * Controls should implement this method if they have to update their internal state
  42749. * per simulation step.
  42750. *
  42751. * @param {number} [delta] - The time delta in seconds.
  42752. */
  42753. update( /* delta */ ) {}
  42754. }
  42755. /**
  42756. * Scales the texture as large as possible within its surface without cropping
  42757. * or stretching the texture. The method preserves the original aspect ratio of
  42758. * the texture. Akin to CSS `object-fit: contain`
  42759. *
  42760. * @param {Texture} texture - The texture.
  42761. * @param {number} aspect - The texture's aspect ratio.
  42762. * @return {Texture} The updated texture.
  42763. */
  42764. function contain( texture, aspect ) {
  42765. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42766. if ( imageAspect > aspect ) {
  42767. texture.repeat.x = 1;
  42768. texture.repeat.y = imageAspect / aspect;
  42769. texture.offset.x = 0;
  42770. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42771. } else {
  42772. texture.repeat.x = aspect / imageAspect;
  42773. texture.repeat.y = 1;
  42774. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42775. texture.offset.y = 0;
  42776. }
  42777. return texture;
  42778. }
  42779. /**
  42780. * Scales the texture to the smallest possible size to fill the surface, leaving
  42781. * no empty space. The method preserves the original aspect ratio of the texture.
  42782. * Akin to CSS `object-fit: cover`.
  42783. *
  42784. * @param {Texture} texture - The texture.
  42785. * @param {number} aspect - The texture's aspect ratio.
  42786. * @return {Texture} The updated texture.
  42787. */
  42788. function cover( texture, aspect ) {
  42789. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42790. if ( imageAspect > aspect ) {
  42791. texture.repeat.x = aspect / imageAspect;
  42792. texture.repeat.y = 1;
  42793. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42794. texture.offset.y = 0;
  42795. } else {
  42796. texture.repeat.x = 1;
  42797. texture.repeat.y = imageAspect / aspect;
  42798. texture.offset.x = 0;
  42799. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42800. }
  42801. return texture;
  42802. }
  42803. /**
  42804. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42805. *
  42806. * @param {Texture} texture - The texture.
  42807. * @return {Texture} The updated texture.
  42808. */
  42809. function fill( texture ) {
  42810. texture.repeat.x = 1;
  42811. texture.repeat.y = 1;
  42812. texture.offset.x = 0;
  42813. texture.offset.y = 0;
  42814. return texture;
  42815. }
  42816. /**
  42817. * Determines how many bytes must be used to represent the texture.
  42818. *
  42819. * @param {number} width - The width of the texture.
  42820. * @param {number} height - The height of the texture.
  42821. * @param {number} format - The texture's format.
  42822. * @param {number} type - The texture's type.
  42823. * @return {number} The byte length.
  42824. */
  42825. function getByteLength( width, height, format, type ) {
  42826. const typeByteLength = getTextureTypeByteLength( type );
  42827. switch ( format ) {
  42828. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42829. case AlphaFormat:
  42830. return width * height;
  42831. case RedFormat:
  42832. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42833. case RedIntegerFormat:
  42834. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42835. case RGFormat:
  42836. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42837. case RGIntegerFormat:
  42838. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42839. case RGBFormat:
  42840. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42841. case RGBAFormat:
  42842. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42843. case RGBAIntegerFormat:
  42844. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42845. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42846. case RGB_S3TC_DXT1_Format:
  42847. case RGBA_S3TC_DXT1_Format:
  42848. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42849. case RGBA_S3TC_DXT3_Format:
  42850. case RGBA_S3TC_DXT5_Format:
  42851. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42852. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42853. case RGB_PVRTC_2BPPV1_Format:
  42854. case RGBA_PVRTC_2BPPV1_Format:
  42855. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42856. case RGB_PVRTC_4BPPV1_Format:
  42857. case RGBA_PVRTC_4BPPV1_Format:
  42858. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42859. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42860. case RGB_ETC1_Format:
  42861. case RGB_ETC2_Format:
  42862. case R11_EAC_Format:
  42863. case SIGNED_R11_EAC_Format:
  42864. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42865. case RGBA_ETC2_EAC_Format:
  42866. case RG11_EAC_Format:
  42867. case SIGNED_RG11_EAC_Format:
  42868. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42869. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42870. case RGBA_ASTC_4x4_Format:
  42871. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42872. case RGBA_ASTC_5x4_Format:
  42873. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42874. case RGBA_ASTC_5x5_Format:
  42875. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42876. case RGBA_ASTC_6x5_Format:
  42877. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42878. case RGBA_ASTC_6x6_Format:
  42879. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42880. case RGBA_ASTC_8x5_Format:
  42881. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42882. case RGBA_ASTC_8x6_Format:
  42883. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42884. case RGBA_ASTC_8x8_Format:
  42885. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42886. case RGBA_ASTC_10x5_Format:
  42887. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42888. case RGBA_ASTC_10x6_Format:
  42889. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42890. case RGBA_ASTC_10x8_Format:
  42891. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42892. case RGBA_ASTC_10x10_Format:
  42893. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42894. case RGBA_ASTC_12x10_Format:
  42895. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42896. case RGBA_ASTC_12x12_Format:
  42897. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42898. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42899. case RGBA_BPTC_Format:
  42900. case RGB_BPTC_SIGNED_Format:
  42901. case RGB_BPTC_UNSIGNED_Format:
  42902. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42903. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42904. case RED_RGTC1_Format:
  42905. case SIGNED_RED_RGTC1_Format:
  42906. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42907. case RED_GREEN_RGTC2_Format:
  42908. case SIGNED_RED_GREEN_RGTC2_Format:
  42909. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42910. }
  42911. throw new Error(
  42912. `Unable to determine texture byte length for ${format} format.`,
  42913. );
  42914. }
  42915. function getTextureTypeByteLength( type ) {
  42916. switch ( type ) {
  42917. case UnsignedByteType:
  42918. case ByteType:
  42919. return { byteLength: 1, components: 1 };
  42920. case UnsignedShortType:
  42921. case ShortType:
  42922. case HalfFloatType:
  42923. return { byteLength: 2, components: 1 };
  42924. case UnsignedShort4444Type:
  42925. case UnsignedShort5551Type:
  42926. return { byteLength: 2, components: 4 };
  42927. case UnsignedIntType:
  42928. case IntType:
  42929. case FloatType:
  42930. return { byteLength: 4, components: 1 };
  42931. case UnsignedInt5999Type:
  42932. case UnsignedInt101111Type:
  42933. return { byteLength: 4, components: 3 };
  42934. }
  42935. throw new Error( `Unknown texture type ${type}.` );
  42936. }
  42937. /**
  42938. * A class containing utility functions for textures.
  42939. *
  42940. * @hideconstructor
  42941. */
  42942. class TextureUtils {
  42943. /**
  42944. * Scales the texture as large as possible within its surface without cropping
  42945. * or stretching the texture. The method preserves the original aspect ratio of
  42946. * the texture. Akin to CSS `object-fit: contain`
  42947. *
  42948. * @param {Texture} texture - The texture.
  42949. * @param {number} aspect - The texture's aspect ratio.
  42950. * @return {Texture} The updated texture.
  42951. */
  42952. static contain( texture, aspect ) {
  42953. return contain( texture, aspect );
  42954. }
  42955. /**
  42956. * Scales the texture to the smallest possible size to fill the surface, leaving
  42957. * no empty space. The method preserves the original aspect ratio of the texture.
  42958. * Akin to CSS `object-fit: cover`.
  42959. *
  42960. * @param {Texture} texture - The texture.
  42961. * @param {number} aspect - The texture's aspect ratio.
  42962. * @return {Texture} The updated texture.
  42963. */
  42964. static cover( texture, aspect ) {
  42965. return cover( texture, aspect );
  42966. }
  42967. /**
  42968. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42969. *
  42970. * @param {Texture} texture - The texture.
  42971. * @return {Texture} The updated texture.
  42972. */
  42973. static fill( texture ) {
  42974. return fill( texture );
  42975. }
  42976. /**
  42977. * Determines how many bytes must be used to represent the texture.
  42978. *
  42979. * @param {number} width - The width of the texture.
  42980. * @param {number} height - The height of the texture.
  42981. * @param {number} format - The texture's format.
  42982. * @param {number} type - The texture's type.
  42983. * @return {number} The byte length.
  42984. */
  42985. static getByteLength( width, height, format, type ) {
  42986. return getByteLength( width, height, format, type );
  42987. }
  42988. }
  42989. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42990. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42991. revision: REVISION,
  42992. } } ) );
  42993. }
  42994. if ( typeof window !== 'undefined' ) {
  42995. if ( window.__THREE__ ) {
  42996. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42997. } else {
  42998. window.__THREE__ = REVISION;
  42999. }
  43000. }
  43001. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, 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, 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, WebGLCubeRenderTarget, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, arrayNeedsUint32, cloneUniforms, createCanvasElement, createElementNS, error, getByteLength, getConsoleFunction, getUnlitUniformColorSpace, isTypedArray, log, mergeUniforms, probeAsync, setConsoleFunction, warn, warnOnce };
粤ICP备19079148号